1

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:

  • Django 1.6

  • Running tests using django-nose

4

1 回答 1

0

bar_factory 参数 foo_inst 在模块导入时进行评估。当时通常数据库仍然指向本地开发数据库,​​而不是测试数据库。

您必须重写默认值,以便稍后对其进行评估。例如,不是传递实例,而是传递一个可调用对象并在您的 bar_factory 中调用它。

于 2014-04-28T12:08:33.500 回答