ted*_*ner 9 django unit-testing http-headers
要手动发送带有标头的 GET 请求,我可以这样做curl:
curl http://example.com/endpoint -H "Key: Value"
django.test.RequestFactory我想编写一个单元测试来发出包含标头的请求(使用)。如何向请求添加标头?
为了清楚起见,下面是我希望能够执行的操作的示例,尽管我在下面编写的代码不是有效的代码,因为RequestFactory.get()没有headers参数:
from django.test import TestCase, RequestFactory
class TestClassForMyDjangoApp(TestCase):
    def test_for_my_app(self):
        factory = RequestFactory()
        
        my_header = dict(key=value, another_key=another_value)
        factory.get('/endpoint/', headers=my_header)
JPG*_*JPG 15
您需要将HTTP_*kwargs 传递给get(...)(或任何有效的 http 方法)以在请求中传递自定义 HTTP 标头。
class TestClassForMyDjangoApp(TestCase):
    def test_for_my_app(self):
        factory = RequestFactory()
        my_header = {"HTTP_CUSTOM_KEY": "VALUE"}
        request = factory.get("/some/url/", **my_header)
        print(request.headers) # {'Custom-Key': 'VALUE'}