【发布时间】:2018-12-14 16:13:13
【问题描述】:
我正在尝试设置一个 API 端点,以根据传入请求的 Accept 标头使用 HTML 或 JSON 进行回复。我已经让它工作了,通过 curl 进行测试:
> curl --no-proxy localhost -H "Accept: application/json" -X GET http://localhost:8000/feedback/
{"message":"feedback Hello, world!"}
> curl --no-proxy localhost -H "Accept: text/html" -X GET http://localhost:8000/feedback/
<html><body>
<h1>Root</h1>
<h2>feedback Hello, world!</h2>
</body></html>
不过,我不知道如何使用 APITestCase().self.client 来指定应该接受哪些内容。
我的观点看起来像
class Root(APIView):
renderer_classes = (TemplateHTMLRenderer,JSONRenderer)
template_name="feedback/root.html"
def get(self,request,format=None):
data={"message": "feedback Hello, world!"}
return Response(data)
我的测试代码看起来像
class RootTests(APITestCase):
def test_can_get_json(self):
response = self.client.get('/feedback/',format='json',Accept='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.accepted_media_type,'application/json')
js=response.json()
self.assertIn('message', js)
self.assertEqual(js['message'],'feedback Hello, world!')
在 response.accepted_media_type 的测试中死亡。这样做的正确方法是什么?我能找到的所有内容都表明格式参数应该足够了。
【问题讨论】:
-
Accept='application/json'是干什么用的?删除后会发生什么? -
@DušanMaďar 我希望它将作为标头传递到底层请求中。无论有没有它,测试都会失败,有和没有“headers={'accept':'application/json'}”参数。
-
@cakins 根据django-rest-framework.org/api-guide/testing/#configuration检查你的设置
-
@Ken4scholars 将其表述为 self.client.get('/feedback/', HTTP_ACCEPT='application/json') 效果很好,我一定看过有关“额外”参数五的文档次。写出来让我接受。
标签: python django testing django-rest-framework