python - factory_boy DjangoModelFactory 没有为测试创建模型条目
问题描述
我正在尝试使用 factory_boy 测试我的 django 应用程序来设置模型实例。
我为某些 Django 模型设置了以下工厂。
class StudyFactory(DjangoModelFactory):
class Meta:
model = Study
group = SubFactory(GroupFactory)
@create_attrs(values)
class SomeFactory(DjangoModelFactory):
class Meta:
model = SomeModel
study = SubFactory(StudyFactory)
some_attr = "some attribute"
@create_attrs(values)
class AnotherFactory(DjangoModelFactory):
class Meta:
model = AnotherModel
study = SubFactory(StudyFactory)
我正在尝试使用以下设置和拆卸运行测试:
class SomeTests(TestCase):
fixtures = ["users.json"]
def setUp(self):
self.study = StudyFactory()
self.some = SomeFactory(study=self.study)
self.another = AnotherFactory(study=self.study)
def tearDown(self):
self.study.delete()
self.some.delete()
self.another.delete()
首先,这会引发以下错误:
AttributeError: type object 'SomeFactory' has no attribute 'delete'
所以我检查了以下细节self.study
:
isinstance(self.study, Study)
>>> True
Study.objects.all()
>>> <QuerySet [<Study: 2014-02-14>]> # queryset contains values
self.study.group.id
>>> 2
Factory 似乎创建了一个适当的 Study 实例以用于测试。但是当我查看以下详细信息时self.some
:
isinstance(self.some, SomeModel)
>>> False # not SomeModel
type(self.some)
>>> FactoryMetaClass
Some.objects.all()
>>> <QuerySet []> # empty queryset
self.some.some_attr
>>> "some attribute" # the attribute can still be called!
self.some.study.group.id
>>> AttributeError: 'SubFactory' object has no attribute 'id' # fails even though self.study.group.id did not
所以 StudyFactory 创建了一个可用的 Django 对象,而 SomeFactory 没有,而是创建了一个 FactoryMetaClass。
问题的原因是:我需要能够在 SomeFactory() 实例上执行一些功能,如果在调用 SomeFactory() 后我无法从 SomeModel 生成查询集,它们将不起作用。
我想知道这是我在 SomeFactory 上使用的装饰器造成的,还是因为两者之间的 SubFactory 关系,或者是否还有其他我不明白的效果。
感谢您的帮助。
解决方案
推荐阅读
- cmake - CMake 的 add_custom_command 不会触发库的重建
- javascript - 从 HTML、CSS、JS 转换为 JSX、CSS、JS 时,如何在 react 中链接我的 javascript 文件?
- python - 在 Pyhon 中写入 CSV 文件,用于数据帧。记录结果
- php - 为什么我的电子邮件格式检查器不起作用?
- sql - 如何在postgres中对几个月的日期记录分组后填补时间间隔
- google-app-engine - GAE 的默认配额是否不够大,无法运行 phoenix 项目?
- php - Bootstrap 导航栏切换器图标在移动设备上不起作用
- r - R 中是否有替代 elrm(精确逻辑回归)的方法 - 存储库中没有 elrm 包
- javascript - TypeScript 错误 - 应有 1-2 个参数,但有 0 个或更多。TS2556
- azure - Azure - 容器实例与应用服务