0

SOLVED: The example here was not accurate and didn't show the problem. The solution is in the answer I've given below.


How can I import a factory from a different app's unit test module, and use it to create instances in this test module?

I have a Django project with several apps. The unit tests are using Factory Boy to create instances of the models for testing. (The models are managed by South, and the settings have SOUTH_TESTS_MIGRATE = False as advised.)

In app bar's unit tests, I want to create test instances of Foo, a model defined in app foo.

App foo's unit test module already has a factory FooFactory, which is the factory I want to use:

# foo/tests.py

import factory
…

from . import models

class FooFactory(factory.Factory):
    FACTORY_FOR = models.Foo

    spam = 0
    …

So in bar, the app I'm now writing tests for, I need that FooFactory. I try to import and use it:

# bar/tests.py

import factory
…

from . import models
from foo.tests import FooFactory

class BarFactory(factory.Factory):
    FACTORY_FOR = models.Bar

    foo = factory.SubFactory(FooFactory)
    …

class BarTest(TestCase):
    """ Test cases for ‘Bar’ model. """

    def test_frobnicates_to_spanguloid(self):
        """ The instance should frobnicate to a spanguloid. """
        test_foo = FooFactory(code=34)
        test_bar = BarFactory(foo=test_foo)

But the test cases fail with django.db.utils.DatabaseError: no such table: foo_foo trying to create an instance of foo.Foo.

1 Answer 1

0

The problem (not evidenced in the simplified example) was an attempt to call the factory in the definition of another factory:

class BarFactory(factory.Factory):
    FACTORY_FOR = models.Bar

    spam = FooFactory(code=34)

That fails with django.db.utils.DatabaseError: no such table: foo_foo, because the call is made when Django's test runner is importing the unit test module. At that point, none of the models are in the database.

Instead, any calls to the factories must wait until the tests are run, not when the classes are defined. In this case:

class BarFactory(factory.Factory):
    FACTORY_FOR = models.Bar

    spam = factory.SubFactory(FooFactory)
    …

class BarTestCase(TestCase):

    def setUp(self):
        """ Set up test fixtures. """
        self.test_foo = FooFactory(code=34)

    def test_frobnicates_to_spanguloid(self):
        """ The instance should frobnicate to a spanguloid. """
        test_bar = BarFactory(foo=self.test_foo)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.