微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么 django 测试客户端会丢弃我额外的标头

如何解决为什么 django 测试客户端会丢弃我额外的标头

我正在尝试测试使用某些标题的视图。在我的测试代码中,我有这样的事情:

headers = {'X-Github-Event': 'pull_request'}
body = {useful stuff}
url = reverse(my_view) 

我已尝试使用以下客户端和发布调用的所有可能组合向我的视图发出请求:

client = Client(extra=headers)        
client = apiclient(headers=headers)
client = apiclient(extra=headers)

response = client.post(url,data=body,format="json",headers=headers)
response = client.post(url,extra=headers)

我的视图实际上是这样的:

@api_view(["POST","GET"])
def github_webhook(request):
    print(request.headers)

从我的测试代码调用时,我的视图永远不会打印出我的 X-Github-Event 标头。

如果我运行 runserver 并向该端点发送请求,则标头可以正常工作。只是测试代码被破坏了。

在这里错过了什么?如何为我的测试设置标题

解决方法

我认为以下代码段会对您有所帮助:

import json
from django.test import TestCase
from rest_framework.test import APIClient


class FooTestCase(TestCase):

    def setUpTestData(cls):
        cls.client = APIClient(ACCEPT='application/json')

    def test_foo(self):
        headers = {"ACCEPT": "application/json",'HTTP_X_GITHUB_EVENT': 'pull_request'}
        url = reverse(my_view)
        payload = json.dumps(body)
        response = self.client.post(url,data=payload,content_type='application/json',**headers)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。