我如何添加一个头到Django RequestFactory请求?



要手动发送带有标头的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)

您需要传递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'}

最新更新