我正在使用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)`
有人能向我解释这种行为吗?它很难捕捉,因为curl只需使用-X PATCH -d"name=123"
就可以正常工作。