I am using mysql-server and MySQLdb for accessing my database. I have not even used django models to accessing the database tables.
Now the problem comes while testing. All the django documentation is talking about the testing using django models. While testing a data, i have to insert data into the database using cursor.execute()
function then i have to read from that. 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?
I am using MySQLdb since it is faster than django models. Can anyone tell me how can i make the testing simpler ? How can i test the database in 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.
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
.
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
@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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.