python - 如何从 rest_framework.test.Client 指定接受 header ?

标签 python django testing django-rest-framework

我正在尝试设置 API 端点以根据传入请求的 Accept header 使用 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 测试中死亡。这样做的正确方法是什么?我能找到的所有内容都表明格式参数应该足够了。

最佳答案

如前所述here , 文档似乎没有太多关于如何使用测试客户端向请求添加 header 的内容。但是,extra 参数可用于此目的,但诀窍在于您必须按照 http header 的外观来编写它。所以你应该这样做:

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

关于python - 如何从 rest_framework.test.Client 指定接受 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53783306/

相关文章:

python - 如何将 django 中的 ListCreateAPIView 和 RetrieveUpdateDestroyAPIView 合并到支持所有四种 CRUD 操作的单个 View 中?

python - python For循环中跳过错误的方法

python - 我如何知道我是否已成功创建表(Python、Psycopg2)?

python - 在 Jenkins Pipeline Shell 中运行 Python 脚本

perl - 有没有办法在测试运行之间将 perl 测试数据保存在内存中?

scala - 测试 Right[Seq[MyClass]] 和属性

javascript - 有没有办法在测试中发现 JavaScript 内存泄漏?

python - 用户输入中使用了数组 A 和数组 B 中的多少个单词?

python - 你如何序列化 Django Rest Framework 中的用户模型

Django 根项目 url 命名空间不起作用