0

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?

2
  • Have you considered using setUp and tearDown methods of TestCase class django-testing-docs.readthedocs.io/en/latest/…? Since you're not using Django models for Create and Update, the statement that django TestCase runs query in transaction does not apply. Commented Aug 21, 2017 at 8:02
  • yes now i am doing using the both. In setUp i will insert data into tables and in teardown i will delete those data. But these all are carried out on actual database. Is there any way to create test data base in a way django does for testing. Commented Aug 21, 2017 at 9:15

1 Answer 1

1

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.

References

Sign up to request clarification or add additional context in comments.

11 Comments

But this required to define database back engine, right?
I haven't use any database backend. I am using mysql-server through MySQLdb in python.
Yes. Do you mean you don't have a database set in settings.py?
Yeah, i don't have.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.