如何从rest_framework.test.Client指定Accept标头?

时间:2018-12-14 16:13:14

标签: python django testing django-rest-framework

我正在尝试设置一个API终结点,以使用HTML或JSON进行回复,具体取决于传入请求的Accept标头。我已经通过卷曲测试了它:

> 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>

不过,我不知道如何使用API​​TestCase()。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时死亡。什么是正确的方法?我发现所有内容都表明format参数已经足够。

1 个答案:

答案 0 :(得分:1)

正如正确here所述,文档似乎并没有过多地说明如何使用测试客户端将标头添加到请求中。但是,可以使用extra参数,但要诀是您必须以http标头看起来的确切方式编写它。因此,您应该这样做:

self.client.get('/feedback/', HTTP_ACCEPT='application/json')