0

For an application that uses SSO for login I have implemented a AuthBackend with Django Rest Framework. This custom AuthBackend class checks for the USERID present in the headers and based on that returns the user instance.

I have added permission classes to the views for verifying the authenticated users. In order to add unit tests to the code the APIClient must enable us to add custom header like {'FOO': 'BAR'}

The default class seems to be APIClient I have tried the following but none of them work:

class AccountsTests(APITestCase):

    def test_user_is_authenticated(self):
        ...

        headers = {'USERID': 'john.doe', 'FOO': 'BAR' }
        self.client.get(url, headers)       # Doesn't work
        self.client.get(url, **headers)     # Doesn't work
        self.client.headers.update(headers) # Doesn't work

        ...

abybaddi009
  • 1,014
  • 9
  • 22
  • Have you tried `headers = {'HTTP_USERID': 'john.doe', 'HTTP_FOO': 'BAR' }`? Read the _CGI specification_ in https://docs.djangoproject.com/en/4.0/topics/testing/tools/#django.test.Client.get – wiaterb Jul 28 '22 at 13:01
  • The problem is that `HTTP_` cannot be prefixed for these custom headers because the Auth service sets `USERID`. – abybaddi009 Jul 28 '22 at 14:43
  • Does this answer your question? [Django Rest Framework API Client Custom Header](https://stackoverflow.com/questions/53073763/django-rest-framework-api-client-custom-header) – Andrew Aug 01 '22 at 17:26
  • 1
    Nope that adds the `HTTP_` to the header key as prefix and we can only choose from the ones that are available. – abybaddi009 Aug 19 '22 at 09:51

1 Answers1

0

I was able to fix the issue by using RequestsClient as follows:

from rest_framework.test import RequestsClient

class AccountTests(APITestCase):
    def setUp(self):
        self.client = RequestsClient()

    def test_user_is_authenticated(self):
        ...

        headers = {'USERID': 'john.doe', 'FOO': 'BAR' }
        self.client.headers.update(headers)
        response = self.client.get(url)
        ...

abybaddi009
  • 1,014
  • 9
  • 22