【问题标题】:Why is django test client throwing away my extra headers为什么 django 测试客户端会丢弃我的额外标头
【发布时间】:2021-04-19 10:10:37
【问题描述】:

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

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

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

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, data=body, format="json", extra=headers)

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

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

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

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

我在这里缺少什么?如何为我的测试设置标题?

【问题讨论】:

    标签: python-3.x django django-rest-framework django-testing


    【解决方案1】:

    我认为下面的sn-p会对你有所帮助:

    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)
    

    【讨论】:

      猜你喜欢
      • 2015-11-01
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-01
      • 2020-08-16
      相关资源
      最近更新 更多