说我有一个工厂有两个需要相关的SubFactories。 FactoryBoy提供了哪些钩子可以提供前/后生成来关联这些SubFactories?
class AppointmentFactory(factory.DjangoModelFactory):
class Meta:
model = Appointment
team_member = factory.SubFactory(TeamMemberFactory)
merchant_location = factory.SubFactory(MerchantLocationFactory)
检查在shell会话中创建的内容会产生理论上无效的对象 - 来自不同位置的团队成员。
> appt = AppointmentFactory.create()
>
> print(appt.merchant_location)
> <MerchantLocation: object (3)>
>
> print(appt.team_member.merchant_location)
> <MerchantLocation: object (4)>
理想情况下,这个钩子可以让我访问传递给工厂的args,这样我就可以确定使用哪个SubFactory作为真实来源&#34;为了这段关系。
示例逻辑:
# handle: AppointmentFactory(team_member=tm_A) or AppointmentFactory(location=loc_A)
@factory.my_desired_hook
def associate_stuff(self, *args, **kwargs):
if 'team_member' in kwargs and 'merchant_location' in kwargs:
pass . # assume caller taking responsibility for correctness
elif 'team_member' in kwargs:
self.merchant_location = team_member.merchant_location
elif 'merchant_location' in kwargs:
self.team_member.merchant_location = self.merchant_location
答案 0 :(得分:1)
最好的解决方法是在你的子问题中使用factory.SelfAttribute
:
class AppointmentFactory(factory.Factory):
class Meta:
model = Appointment
merchant_location = factory.SubFactory(MerchantLocationFactory)
team_member = factory.SubFactory(
TeamMemberFactory,
# Fetch the `merchant_location` from the parent object.
merchant_location=factory.SelfAttribute('..merchant_location'),
)
这并未解决提供任何一种情况的可能性,并让工厂自动调整。 这部分更复杂,因为库没有提供帮助来打破循环依赖。