Django Testing and Postgresql Flush

Just to be clear on terminology, the following code has one test class with two tests:

from django.test import TestCase

class MyTest(TestCase):
    def test_some_stuff(self):
        print 'Some test code'
    def test_some_other_stuff(self):
        print 'Some other test code'

The test database is supposed to be flushed between tests. You can run the tests individually like this:

python test my_app.MyTest.test_some_stuff
python test my_app.MyTest.test_some_other_stuff

What does it mean when the tests work when they are run individually, but they fail when run together as:

python test my_app.MyTest

One possibility is that the database is not really being flushed. In fact this is kind of true. It turns out that although the database is flushed, the auto-indexing is not reset. So if you are silly enough to base an assertion on an instance ID., things might not work as expected.

Of course you would never be that silly. But a lesser programmer might do it this way. Suppose junk contains a foreign key to stuff. The programmer might not care which junk is used. He might write:

junk = Junk.objects.get(id=1)   # Just grab the first one
stuff = Stuff(junk=junk)

The problem occurs when this test comes after another test that makes junk. Because auto-indexing did not reset, there may not be a junk record with id=1.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s