我正在尝试使用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关系,或者是否有其他影响我不明白。
感谢您的帮助。