当pytest与REST框架交互时,PATCH和PUT不能按预期工作

Dav*_*han 10 python put django-rest-framework pytest-django

我正在使用django REST框架构建API.

为了测试这个API,我使用pytest和测试客户端,如下所示:

def test_doesnt_find(self, client):
    resp = client.post(self.url, data={'name': '123'})
    assert resp.status_code == 404
Run Code Online (Sandbox Code Playgroud)

要么

def test_doesnt_find(self, client):
    resp = client.get(self.url, data={'name': '123'})
    assert resp.status_code == 404
Run Code Online (Sandbox Code Playgroud)

在使用REST框架的常规GET,POST和DELETE类时(例如DestroyAPIView,RetrieveUpdateAPIView或仅APIView使用get和post函数)都可以工作

我遇到问题的地方是使用PATCH和PUT视图.如RetrieveUpdateAPIView.在这里,我突然不得不使用:

resp = client.patch(self.url, data="name=123", content_type='application/x-www-form-urlencoded')
Run Code Online (Sandbox Code Playgroud)

要么

resp = client.patch(self.url, data=json.dumps({'name': '123'}), content_type='application/json')
Run Code Online (Sandbox Code Playgroud)

如果我只是尝试像我习惯的那样使用测试客户端,我会收到错误:

rest_framework.exceptions.UnsupportedMediaType: Unsupported media type "application/octet-stream" in request.
Run Code Online (Sandbox Code Playgroud)

当我在client.patch()调用中指定'application/json'时:

rest_framework.exceptions.ParseError: JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)`
Run Code Online (Sandbox Code Playgroud)

任何人都可以向我解释这种行为吗?特别难以捕捉,因为卷曲只是用得很好-X PATCH -d"name=123".

Lin*_*via 7

rest_framework.exceptions.ParseError:JSON解析错误 - 期望用双引号括起来的属性名:第1行第2列(char 1)

这通常表示您在json中的字符串中发送字符串.例如:

resp = client.patch(self.url, data=json.dumps("name=123"), content_type='application/json')
Run Code Online (Sandbox Code Playgroud)

会引起这种问题.

rest_framework.exceptions.UnsupportedMediaType:请求中不支持的媒体类型"application/octet-stream".

这意味着请求已作为"application/octet-stream"发送,这是Django的测试默认值.

为了减轻处理所有这些问题的痛苦,Django REST框架自己提供了一个客户端:http://www.django-rest-framework.org/api-guide/testing/#apiclient

请注意,语法与Django的语法略有不同,您不必处理json编码.

  • 提示:与其实例化 APIClient ,您还可以从测试类的 APITestCase 继承 (4认同)
  • ```resp = client.patch(self.url, json={"name": 123})``` (2认同)