Django authentication testing failure: Authentication credentials were not provided

I am working on the user logic of my Django project. Despite the fact that logout (using session cookie authentication) works perfectly fine in the browser, it is not working during testing for some reason. It appears as if the cookie from the login response isn't being correctly saved for the subsequent request. Here are the relevant excerpts from my project code:

views.py

class UserLogoutView(generics.GenericAPIView):
    permission_classes: list[permissions.BasePermission] = [permissions.IsAuthenticated]

    def get_serializer_class(self) -> serializers.Serializer:
        return serializers.Serializer  # Return basic Serializer class

    def delete(self, request: Request) -> Response:
        response: Response
        try:
            session_key: str = request.COOKIES.get("session")
            token: Token = Token.objects.get(key=session_key)
            response = Response(
                status=status.HTTP_200_OK,
                data={"detail": "Logout successful"},
            )
            response.delete_cookie(key="session")
            token.delete()

        except ObjectDoesNotExist:
            response = Response(
                {"error": "Session cookie not found"},
                status=status.HTTP_401_UNAUTHORIZED,
            )
        except Exception as error:
            print(error)
            response = Response(
                {"error": str(error)},
                status=status.HTTP_400_BAD_REQUEST,
            )

        return response

tests_views.py

class TestLogoutViews(TestCase):
    def setUp(self) -> None:
        self.client = Client()
        self.data: dict[str, str] = {
            "username": "testuser",
            "email": "test@test.com",
            "password": "Password1",
        }
        self.logout_url: str = reverse("user_logout")
        self.login_url: str = reverse("user_login")

        self.client.post(
            reverse("user_register"),
            json.dumps(self.data),
            content_type="application/json",
        )
        self.data.pop("email")

    def test_logout_view_correct_DELETE(self) -> None:

        # Log in first
        response: HttpResponse = self.client.post(
            self.login_url,
            json.dumps(self.data),
            content_type="application/json",
        )

        print()
        print(response.status_code, self.client.cookies)
        print()

        # Send the DELETE request
        response: HttpResponse = self.client.delete(self.logout_url)

        # Check if the response is 200
        self.assertEqual(
            response.status_code,
            200,
            msg=(
                f"Response is {response.status_code}, expected 200. ",
                f"Response content: {response.content}",
            ),
        )

        # Check if the cookie is deleted
        self.assertFalse(
            "session" in self.client.cookies, msg="Cookie should be deleted"
        )

settings.py

REST_FRAMEWORK: dict[str, str] = {
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework.authentication.TokenAuthentication",
        "rest_framework.authentication.SessionAuthentication",
    ),
    "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
}

Output:

200 Set-Cookie: session=304a23566b589374cf24e577aac2d2370c40de98; HttpOnly; Path=/; SameSite=lax; Secure
======================================================================
FAIL: test_logout_view_correct_DELETE (users.test_views.TestLogoutViews)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\user\repositories\flicks-and-picks\src\backend\apps\users\test_views.py", line 518, in test_logout_view_correct_DELETE
    self.assertEqual(
AssertionError: 401 != 200 : ('Response is 401, expected 200. ', 'Response content: b\'{"detail":"Authentication credentials were not provided."}\'')
Back to Top