Django Api-Key with unit test

I am trying to implement unit tests to an existing project, the existing project uses Api-Key's to access and authenticate against the Api endpoints.

if I do the following via postman or command line:

curl --location --request GET '' \
--header 'Authorization: Api-Key REDACTED' \
--header 'Content-Type: application/json' \
--data-raw '{
    "username" : "testuser@localhost"

Everything works great, however when trying to add the Api-Key to the header in Unit tests I receive the following :

'detail': ErrorDetail(string='Authentication credentials were not provided.', code='not_authenticated')}
AssertionError: 403 != 200

from rest_framework.test import APITestCase
from rest_framework import status
from django.urls import reverse
import environ

env = environ.Env()

class GetUserTestCase(APITestCase):
    def test_get_user_account(self):
        getdata = {
                    "username" : "testuser@localhost"

        response    =   self.client.get(reverse('users_db'), data=getdata, **{ "HTTP_AUTHORIZATION": f"Api-Key {env('API_KEY')}" })
        self.assertEqual(response.status_code, status.HTTP_200_OK)

Also tried with the following items:

headers = {
            'Authorization': f'Api-Key {env("API_KEY")}',
            'Content-Type': 'application/json'
response    =   self.client.get(reverse('users_db'), data=getdata, headers=headers)


self.client.credentials(HTTP_AUTHORIZATION=f"Api-Key {env('API_KEY')}")

No joy so far, anyone else had this problem and find a way forward?

Back to Top