To manually send a GET request with a header, I do this with curl:
curl http://example.com/endpoint -H "Key: Value"
I want to write a unit test that makes a request (using django.test.RequestFactory) containing a header. How can I add a header to the request?
For clarity, below is an example of what I'd like to be able to do, though what I have written below is not valid code because RequestFactory.get() does not have a headers parameter:
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)
You need to pass HTTP_* kwargs to the get(...) ( or any valid http methods) to pass a custom HTTP header in the request.
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With