【发布时间】:2017-02-15 20:18:03
【问题描述】:
我正在使用 django REST 框架构建一个 API。
为了测试这个 API,我使用 pytest 和测试客户端,如下所示:
def test_doesnt_find(self, client):
resp = client.post(self.url, data={'name': '123'})
assert resp.status_code == 404
或
def test_doesnt_find(self, client):
resp = client.get(self.url, data={'name': '123'})
assert resp.status_code == 404
在使用 REST 框架的通用 GET、POST 和 DELETE 类(如 DestroyAPIView、RetrieveUpdateAPIView 或仅使用 get 和 post 函数的 APIView)时,两者都可以工作
我遇到问题的地方是使用 PATCH 和 PUT 视图时。如RetrieveUpdateAPIView。这里突然不得不用:
resp = client.patch(self.url, data="name=123", content_type='application/x-www-form-urlencoded')
或
resp = client.patch(self.url, data=json.dumps({'name': '123'}), content_type='application/json')
如果我只是像以前一样尝试使用测试客户端,我会收到错误:
rest_framework.exceptions.UnsupportedMediaType: Unsupported media type "application/octet-stream" in request.
当我在 client.patch() 调用中指定 'application/json' 时:
rest_framework.exceptions.ParseError: JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)`
谁能向我解释这种行为?使用 -X PATCH -d"name=123" 时,curl 也能正常工作。
【问题讨论】:
-
你指的测试客户端是什么?姜戈? DRF ?另一个?
-
是django测试客户端[pytest-django.readthedocs.io/en/latest/…
标签: python django-rest-framework put pytest-django