Dr. Cyanide Dr. Cyanide - 4 months ago 15
Python Question

Django test DB returning nothing

I'm getting the exact same issue as when does the database is being destroy in django tests? , where my test DB seems to be getting deleted between each method. I know it's being cleared out each time I re-run python3 manage.py test , but it shouldn't be deleted in the middle of the test.

I'm running Python 3.4.3, Postgresql 9.5.3, Django 1.9

from django.test import TestCase
class myTestCases(TestCase):
def test_1_load_regions(self):
self.assertEqual(True, len(Region.objects.all()) >= minRegionsExpected)
print("Regions: %s Languages: %s"%(len(Region.objects.all()), len(Language.objects.all())))

def test_2_load_languages(self):
# Generated by _updateRegions, just check that a few languages exist
print("Regions: %s Languages: %s"%(len(Region.objects.all()), len(Language.objects.all())))

self.assertEqual(True, len(Language.objects.all()) >= minLanguagesExpected)

And I'm get an output like this:

Regions: 11 Languages: 19
.Regions: 0 Languages: 0

That makes me think everything is saving when the first test ends, but somehow when the second test starts everything is cleared out. I would rather avoid re-running everything at the start of each test, but right now I'm stumped at how to get the test DB to actually keep my results...

Edit/Results: So after some poking in the right direction from the comments and answers, I found what I was looking for.


If your tests rely on database access such as creating or querying models, be sure to create your test classes as subclasses of django.test.TestCase rather than unittest.TestCase.

Using unittest.TestCase avoids the cost of running each test in a transaction and flushing the database, but if your tests interact with the database their behavior will vary based on the order that the test runner executes them. This can lead to unit tests that pass when run in isolation but fail when run in a suite.

I was using test_1, test_2, test_3 as my names to ensure the order of operations, so that wasn't a problem. By swapping from django.test.TestCase to unittest.TestCase I got the results I wanted, with my database persisting between each test case.


Actually, according to the Django tutorial, the database is rolled back between each test. (See the bottom of the linked section.)

If you're looking to have a common setup between tests, you should consider overriding the TestCase method setUp. This is run before each test function. The unittest documentation should be helpful for this, and Django has an example in their documentation as well.