试图测试嵌套的serilailzer,如何创建所需的子因子



我得到了一个失败的测试,因为(我认为(我无法添加子系数字段。

我有一个调用另一个序列化程序的序列化程序。我发现很难在测试(特别是工厂(中复制这一点。问题是由我的测试_expected_restuarant_response引起的。它期望一个包含employee字段的响应(就像序列化程序所做的那样(。问题是,我无法将此子系数字段添加到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')

相关内容

  • 没有找到相关文章

最新更新