工厂男孩和相关的对象创建

时间:2017-11-24 13:49:23

标签: python django unit-testing factory factory-boy

假设你有这些相关的Django模型:

class Service:
   restaurant = models.ForeignKey(Restaurant)
   hist_day_period = models.ForeignKey(DayPeriod)

class DayPeriod:
   restaurant = models.ForeignKey(Restaurant)

我想使用Factory创建一个Service对象。它应该创建所有3个模型,但使用相同的餐厅。

使用此代码:

class ServiceFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Service

    restaurant = factory.SubFactory('restaurants.factories.RestaurantFactory')

    hist_day_period = factory.SubFactory(
        'day_periods.factories.DayPeriodFactory', restaurant=restaurant)

工厂男孩将创建2个不同的餐厅:

s1 = ServiceFactory.create()
s1.restaurant == s1.hist_day_period.restaurant
>>> False

有关如何做到这一点的任何想法?我不清楚我是否应该使用related factors代替SubFactory来完成此任务。

2 个答案:

答案 0 :(得分:5)

您想使用factoryboy的parentsSelfAttribute

class ServiceFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Service

    restaurant = factory.SubFactory('restaurants.factories.RestaurantFactory')

    hist_day_period = factory.SubFactory(
        'day_periods.factories.DayPeriodFactory',
        restaurant=factory.SelfAttribute('..restaurant')
    )

使用此测试应用程序

In [1]: from service.tests import ServiceFactory
In [2]: s1 = ServiceFactory.create()
In [3]: s1.restaurant == s1.hist_day_period.restaurant
Out[3]: True

In [4]: s1.restaurant_id
Out[4]: 4

In [5]: s1.hist_day_period.restaurant_id
Out[5]: 4

答案 1 :(得分:0)

您可以使用带有查询集的re.sub来代替SubFactory

例如:

Iterator

不过,我不确定创建该class ServiceFactory(factory.django.DjangoModelFactory): class Meta: model = Service restaurant = factory.Iterator(models.Restaurant.object.all()) hist_day_period = factory.SubFactory( 'day_periods.factories.DayPeriodFactory', restaurant=restaurant) 的最佳位置。在我们的代码库中,我重写了Restaurant并在那里创建了用于此目的的模型(在DiscoverRunner中,感觉就像是黑客一样)。