From b02eaf87f2d7c0830606f0cc7d7b4ce1958532d8 Mon Sep 17 00:00:00 2001 From: enrico Date: Sat, 6 Apr 2024 10:02:25 +0800 Subject: [PATCH] Added function based view tests for authentication --- tests/test_authentication.py | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/tests/test_authentication.py b/tests/test_authentication.py index f28bdd1..144fb37 100644 --- a/tests/test_authentication.py +++ b/tests/test_authentication.py @@ -4,7 +4,9 @@ from django.test import TestCase, override_settings from adrf.views import APIView +from adrf.decorators import api_view from rest_framework import permissions, status +from rest_framework.decorators import permission_classes, authentication_classes from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import AuthenticationFailed from rest_framework.test import APIRequestFactory @@ -53,21 +55,37 @@ async def get(self, request): return HttpResponse({"a": 1, "b": 2, "c": 3}) +@api_view(("GET",)) +@permission_classes([permissions.IsAuthenticated]) +@authentication_classes([AsyncAuthentication]) +async def mock_view_func(request): + return HttpResponse({"a": 1, "b": 2, "c": 3}) + + @override_settings(ROOT_URLCONF=__name__) class TestAsyncAuthentication(TestCase): - async def test_admit_customtoken(self): + async def test_admit_customtoken_class_view(self): auth = "Bearer admitme" request = factory.get("/view/", HTTP_AUTHORIZATION=auth) - response = await MockView.as_view()(request) - self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(request.user, faked_user) - async def test_reject_customtoken(self): + async def test_reject_customtoken_class_view(self): auth = "Bearer expired" request = factory.get("/view/", HTTP_AUTHORIZATION=auth) - response = await MockView.as_view()(request) + self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) + async def test_admit_customtoken_func_view(self): + auth = "Bearer admitme" + request = factory.get("/view/", HTTP_AUTHORIZATION=auth) + response = await mock_view_func(request) + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual(request.user, faked_user) + + async def test_reject_customtoken_func_view(self): + auth = "Bearer expired" + request = factory.get("/view/", HTTP_AUTHORIZATION=auth) + response = await mock_view_func(request) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)