Can Django flush the database between each unit test?

Django (1.2 beta) will reset the database (s) between each test that runs, which means that each test runs on an empty database. However, the database (s) are not painted . One of the effects of database cleanup is auto_increment reset counters.

Consider a test that retrieves data from a database using a primary key:

 class ChangeLogTest(django.test.TestCase): def test_one(self): do_something_which_creates_two_log_entries() log = LogEntry.objects.get(id=1) assert_log_entry_correct(log) log = LogEntry.objects.get(id=2) assert_log_entry_correct(log) 

This will pass because only two journal entries have ever been created. However, if another test is added to ChangeLogTest and it starts before test_one , the primary keys of the log entries are no longer 1 and 2, they can be 2 and 3. Now test_one does not work.

This is a two-part question:

  • Is it possible to get ./manage.py test to reset the database between each test case?
  • Since Django does not clear the database between each test by default, there may be a good reason. Somebody knows?
+6
database django unit-testing
source share
2 answers

Is it possible to force a test. /manage.py to clear the database between each test case?

Take a look at the implementation of the django.core.management.commands.flush.py team.

You can call the flush command from your test call (possibly in TestCase.setUp):

 management.call_command('flush') 

maybe there is a good reason. Somebody knows?

Yes there is: Speed ​​up. Flushing and reloading a lot of data from json takes some time ...

Maybe you should take a look at TransactionTestCase

+7
source share

The answer to this question: do not write down your tests in such a way that they depend on certain key values. For example, your test is better to write:

 def test_one(self): do_something_which_creates_two_log_entries() logs = LogEntry.objects.all() assert_log_entry_correct(log[0]) assert_log_entry_correct(log[1]) 
+8
source share

All Articles