【问题标题】:DRF + DREST : how to ensure during tests, the serializer is compiled with the setUp test data?DRF + DREST :如何确保在测试期间,序列化程序是用 setUp 测试数据编译的?
【发布时间】:2018-11-12 14:41:11
【问题描述】:

使用

  • Django:1.11
  • Python 3.6
  • DRF: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 的 setUp 方法中,我都有

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 方法中。

但是我遇到了同样的问题

【问题讨论】:

  • erm 我实际上有一个 UgField 记录,它的字符串 global.scope 作为字段 dotted_path 的值。当我正确运行应用程序时,没有问题。只有在测试期间我才会遇到这个问题
  • 也许在测试时记录不存在,但在运行时它已经存在,所以你得到一个不同的序列化器?也许在测试框架的不同点初始化它?在课堂上使用try 只是......粗略,虽然很聪明。我希望它所做的报告在这种情况下是准确的,我没有经验。也许它实际上在 except: 字段中的代码上抛出了一个异常

标签: django django-rest-framework dynamic-rest


【解决方案1】:

要使用.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')

【讨论】:

  • 感谢您的努力。但是在 django 测试期间仍会跳过该行。查看更新的问题。
猜你喜欢
  • 1970-01-01
  • 2015-09-18
  • 2018-12-19
  • 2018-08-22
  • 1970-01-01
  • 2010-09-05
  • 1970-01-01
  • 1970-01-01
  • 2021-08-16
相关资源
最近更新 更多