from rest_framework.test import APITestCase from rest_framework import status from rest_framework.test import APIClient from labs.models import User, APIKey class APIKeyTests(APITestCase): ME_URL = "/api/user/me" def setUp(self): self.user = User.objects.create_user(email="test@example.com") self.api_key = APIKey.objects.create_api_key(self.user, "test") self.client = APIClient() def test_api_key_auth(self): response = self.client.get(self.ME_URL) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) response = self.client.get( self.ME_URL, {"email": "test@example.com"}, headers={"Authorization": f"Bearer {self.api_key}"}, ) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual("test@example.com", response.data["email"]) def test_api_key_auth_invalid(self): response = self.client.get( self.ME_URL, headers={"Authorization": f"Bearer non-existing-api-key"}, ) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_api_key_auth_invalid_format(self): response = self.client.get( self.ME_URL, headers={"Authorization": f"invalid-format-api-key"}, ) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)