pythondjangotestingfactorydjango-nose

Why does my Django factory function create models in local DB, not test DB?


I have some tests in my Django project that needs to create a few models and save them to the DB. I extracted the instance-creating code into some "factory" functions that lives in a separate module (.py file), helping me to quickly create sets of related models etc (hence the object.create() stuff). These functions are very simple and look something like this:

def foo_factory():
    return Foo.objects.create(
       bar="random data"
    )

def bar_factory(foo_inst=foo_factory())
    return Bar.objects.create(
        related=foo_inst
    )

When I run the tests, the tests that call this functionality (inside django's TestCase class) save their model instances to my local dev DB (as specified in my local settings file), not the automatically created temporary test DB.

Tests look something like this:

TestFooThing(TestCase):
    def test_foo_stuff(self):
        foo_inst = foo_factory()
        self.assertTrue(foo_inst.blah)

My understanding was that the whole environment is bootstrapped using the test environment settings, but this specific case seems to not work that way. Other tests use the test DB just fine.

What am I missing here?

Details:


Solution

  • bar_factory parameter foo_inst is evaluated at the time of module import. At that time usually databases still point to local dev db, not test db.

    You have to rewrite default value so that it's evaluated much later. For example instead of passing instance, pass a callable and call that within your bar_factory.