试图测试嵌套的 serilailzer,如何创建所需的子工厂?

Trying to test a nested serilailzer, how to create required subfactories?

我的测试失败了,因为(我认为)我无法添加子工厂字段。

我有一个调用另一个序列化程序的序列化程序。我发现很难在测试(特别是工厂)中复制它。这个问题是由我的测试引起的:_expected_restuarant_response。它期望包含员工字段的响应(就像序列化程序一样)。问题是我无法将此子工厂字段添加到 RestaurantFactory,因为 RestaurantFactory 位于 factories.py 文件中的 EmployeeFactory 上方(EmployeeFactory 尚未在文件中的那个点初始化)。我也不能把 EmployeeFactory 放得比 RestaurantFactory 高,因为它指的是 RestaurantFactory.

有人能指出我正确的方向吗?谢谢。

我的文件的简化版本:

models.py:

class Restaurant(models.Model):
    name = models.CharField(max_length=20)

class Employee(models.Model):
    badge_id = models.CharField(max_length=20)
    restaurant = models.ForeignKey(Restaurant)

serializers.py:

class EmployeeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Employee
        fields = [
            'badge_id']

class RestaurantSerializer(serializers.ModelSerializer):
    employee = EmployeeSerializer(many=True, read_only=True)
    class Meta:
        model = Restaurant
        fields = [
            'name',
            'employee']

factories.py:

class RestaurantFactory(factory.django.DjangoModelFactory):
    name = factory.Faker('company')
         < ----------------------------------- do I need to add an Employee subfactory here? If so how?

class EmployeeFactory(factory.django.DjangoModelFactory):
    badge_id = factory.Faker('id')
    restaurant = factory.SubFactory(RestaurantFactory) 

test.py:

def _expected_restuarant_response(restaurant):
    return {
        restaurant.name,
        restaurant.employee_set.badge_id     <---- the test fails here because the RestaurantFactory does not include this field
         }

assert response_json == [_expected_restaurant_response(RestaurantFactory())]

就工厂创建而言,您可能会这样做:

class RestaurantFactory(factory.django.DjangoModelFactory):
    name = factory.Faker('company')
    employee = factory.SubFactory('path.to.EmployeeFactory', employee=None)

然后在 EmployeeFactory 上执行此操作:

class EmployeeFactory(factory.django.DjangoModelFactory):
    badge_id = factory.Faker('id')
    restaurant = factory.RelatedFactory(RestaurantFactory, factory_related_name='employee')