Search code examples
djangodjango-rest-frameworkdjango-testing

Request headers in APITestCase


I have a test (APITestCase), and I need to specify custom headers:

class ListAppsAPITest(APITestCase):
    def test_list_apps_versions(self):
        response = self.client.get(reverse('api:applications:list'), None, **{'Device-Id': 'deadbeef'})

I've tried different combinations of arguments, but it did not work.

How to specify custom headers in tests?


Solution

  • Just because Django have they own way to define the header, you can take a look at here to see why and how to achieve that.

    With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.

    In your case, like so:

    class ListAppsAPITest(APITestCase):
        def test_list_apps_versions(self):
            response = self.client.get(reverse('api:applications:list'), None, **{'HTTP_DEVICE_ID': 'deadbeef'})
    

    Hope that helps!