首页 > 解决方案 > 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 关系,或者是否还有其他我不明白的效果。

感谢您的帮助。

标签: pythondjango-testingfactory-boy

解决方案


推荐阅读