2

我有一组工厂,我在测试阶段通过一个名为Create. 当我需要引用现有项目时,我将其作为参数传递,如果没有,我使用 FactoryBoy 创建一个新项目:

def Create(project=ProjectFactory()):
    # do stuff with project

我这样调用函数:

Create() # new project will be defined
Create(existing_project) # existing project will be used

但它不起作用,我有一堆错误:

E   ProgrammingError: relation "auth_user" does not exist
E   LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user...
E                                                                 ^

在尝试了几天不同的解决方法后,我发现这个版本有效:

def Create(project=None):
    project = ProjectFactory() if not project else project
    # do stuff with project

对我来说,它做同样的事情,我在这里错过了什么?

4

1 回答 1

2

请注意,默认参数 indef Create(project=ProjectFactory()):在模块加载时绑定,主要是在测试运行程序启动时。由于测试运行程序从头开始迁移测试数据库,因此它无法Project在此时创建和保存 a。

在第二个版本

def Create(project=None):
    project = ProjectFactory() if not project else project

The code that creates the Project is inside the function and is, thus, only executed once the function is called -- after the migrations ran.

于 2016-04-04T09:20:14.907 回答