代码之家  ›  专栏  ›  技术社区  ›  Kim Stacks

drf+drest:如何确保在测试期间,序列化程序是用设置测试数据编译的?

  •  0
  • Kim Stacks  · 技术社区  · 6 年前

    使用

    • 姜戈:1.11
    • 蟒蛇3.6
    • 图纸编号:3.7
    • Drest(又名动态休息):1.8

    我有一个这样写的序列化程序:

    class SubProjectAsFKWithAttachedFieldsSerializer(DynamicModelSerializer):
        # attached_fields = AttachedFieldSerializer(embed=True, many=True)
        try:
            scope_object = UgField.objects.get(dotted_path='global.scope')
            scopes = DynamicRelationField(
                AttachedFieldWithDirectValuesSerializer,
                source='attached_fields',
                many=True,
                embed=True,
                read_only=True,
                queryset=AttachedField.objects.filter(ug_field=scope_object)
            )
        except ObjectDoesNotExist:
            scopes = DynamicRelationField(AttachedFieldWithDirectValuesSerializer,
                                          source='attached_fields',
                                          many=True,
                                          read_only=True,
                                          embed=True)
    

    目前,几乎所有我的 tests.py 在设置方法中,我有

    self.global_scope_field = UgFieldFactory(dotted_path='global.scope', name='Scope')
    

    出于某种原因,这条线

    scope_object = UgField.objects.get(dotted_path='global.scope')
    

    尽管我已经使用 DjangoModelFactory

    我应该怎么做才能确保在运行测试时行总是通过?

    更新

    1. 只是为了指出我实际上有一个ugfield记录,它有一个字符串 global.scope 作为字段的值 dotted_path .
    2. 只有当我跑步时 python manage.py test 我要面对这个问题吗?
    3. 当我正确运行应用程序时,没有问题。

    我也试过设置

    (self.global_scope_field, created) = UgField.objects.get_or_create(dotted_path='global.scope', name='Scope')
    

    在我的 setUp 方法。

    但后来我又遇到了同样的问题

    enter image description here

    1 回复  |  直到 6 年前
        1
  •  0
  •   bdoubleu    6 年前

    用于可检索的对象 .get() 必须保存。

    self.global_scope_field = UgFieldFactory(dotted_path='global.scope', name='Scope')
    self.global_scope_field.is_valid()
    self.global_scope_field.save()
    

    或者,您可以创建没有窗体的对象。

    self.global_scope_field = UgField.objects.create(dotted_path='global.scope', name='Scope')