简体   繁体   English

在Django模型以外的Django中测试数据库

[英]Testing database in django other than django models

I am using mysql-server and MySQLdb for accessing my database. 我正在使用mysql-server和MySQLdb访问我的数据库。 I have not even used django models to accessing the database tables. 我什至没有使用django模型来访问数据库表。

Now the problem comes while testing. 现在问题出在测试时。 All the django documentation is talking about the testing using django models. django的所有文档都在谈论使用django模型的测试。 While testing a data, i have to insert data into the database using cursor.execute() function then i have to read from that. 在测试数据时,我必须使用cursor.execute()函数将数据插入数据库,然后从中读取数据。 But this waste out my time. 但这浪费了我的时间。

Also TestCase class run all database query in transaction and my doubt is that, this will be same for mysql-server and myqldb? 另外TestCase类在事务中运行所有数据库查询,我的疑问是,这对于mysql-server和myqldb是否相同?

I am using MySQLdb since it is faster than django models. 我正在使用MySQLdb,因为它比Django模型更快。 Can anyone tell me how can i make the testing simpler ? 谁能告诉我如何简化测试? How can i test the database in django? 如何在Django中测试数据库?

A better approach to setting up your database than overriding setUp and tearDown methods for TestCase is to get out of Django's way by implementing setUpTestData instead. 与重写TestCase setUptearDown方法相比,一种更好的数据库设置方法是改为通过实现setUpTestData摆脱Django的方式。

from django.db import connections

class BasicTest(TestCase):
     @classmethod
     def setUpTestData(cls):
         alias = 'default'
         cursor = connections[alias].cursor()
         query = 'your query here'
         cursor.execute(query)

Django will drop the test database on tearDownClass . Django会将测试数据库放置在tearDownClass

For the case you don't have a configuration entry in settings.py for your database, you'll need to provide your own setUp and tearDown for your TestCase 如果您在settings.py中没有数据库的配置条目,则需要为TestCase提供自己的setUptearDown

@classmethod
def setUpClass(cls):
    super(BasicTest, self).setUpClass()
    db = MySQLdb.connect(host="localhost",user="root",passwd="toor")
    cls.cursor = db.cursor()

    query = 'CREATE DATABASE IF NOT EXISTS test;'
    cls.cursor.execute(query)

    query = 'USE test;'
    cls.cursor.execute(query)

@classmethod
def tearDownClass(cls):
    query = 'DROP DATABASE test;'
    cls.cursor.execute(query)
    cls.cursor.close()

With this, you can still do your other data operations in setUpTestData but the cursor you'll use here is cls.cursor . 这样,您仍然可以在setUpTestData执行其他数据操作,但是此处将使用的光标是cls.cursor

References 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM