【问题标题】:How do I send data along with APITestCase client.patch() in DjangoRestFramework?如何在 DjangoRestFramework 中与 APITestCase client.patch() 一起发送数据?
【发布时间】:2020-05-16 11:24:09
【问题描述】:

我的测试用例:

class MyApiTests(APITestCase):
    def test_retrieve(self):
        resp = self.client.patch('/my/endpoint/', data={
            'name': 'new name',
            'age': 25,
            'some_array': [{
                'my_subobject_name': 'foo'
            }]
        }

在我的视图中,如果我抓住data['some_array'],我会得到:

u"{'my_subobject_name': 'foo'}".

为什么是一个字符串而不是一个字典的数组?

如果我发送一个字符串化版本的

{
    'name': 'new name',
    'age': 25,
    'some_array': [{
        'my_subobject_name': 'foo'
    }]
}

通过我的浏览器,DRF 工作正常,some_array 将是一个数组,其中包含一个字典,正如预期的那样。

在 APITestCase 单元测试中发送复杂数据结构和 patch() 的正确方法是什么?

【问题讨论】:

    标签: django unit-testing django-rest-framework http-patch


    【解决方案1】:

    尝试在补丁函数调用中添加format='json' 参数,即

    class MyApiTests(APITestCase):
        def test_retrieve(self):
            resp = self.client.patch('/my/endpoint/', data={
                'name': 'new name',
                'age': 25,
                'some_array': [{
                    'my_subobject_name': 'foo'
                }]
            }, format='json')
    

    【讨论】:

      猜你喜欢
      • 2015-02-13
      • 2015-03-29
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      相关资源
      最近更新 更多