Factory Boy - 关联两个子工厂

Factory Boy - relate two SubFactories

假设我有一个工厂有两个需要关联的 SubFactories。 FactoryBoy 提供什么钩子 pre/post 代来关联这些 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)>

理想情况下,这个挂钩可以让我访问传递给工厂的参数,这样我就可以确定将哪个 SubFactory 用作关系的 "source of truth"。

示例逻辑:

   # 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

最好的钩子是在你的子工厂中使用 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'),
    )

这不解决提供的可能性,并让工厂自动调整。 这部分比较复杂,因为库不提供帮助程序来打破循环依赖。