Django Api-Key与单元测试

ztigrdn8  于 2023-03-20  发布在  Go
关注(0)|答案(2)|浏览(182)

我正在尝试对现有项目实施单元测试,现有项目使用Api-Key来访问Api端点并进行身份验证。
如果我通过 Postman 或命令行执行以下操作:

curl --location --request GET 'http://127.0.0.1:8000/api/user_db' \
--header 'Authorization: Api-Key REDACTED' \
--header 'Content-Type: application/json' \
--data-raw '{
    "username" : "test@testing.local"
}'

这将调用下面的view函数,并返回带有相应oid(json响应)的用户详细信息,没有错误。

from django.shortcuts import render
from rest_framework_api_key.permissions import HasAPIKey
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from user_api.classes.UserController import (
    GetBusinessUser, 
    CreateBusinessUser, 
    UpdateBusinessUser, 
    DeleteBusinesssUser
)
from celery.utils.log import get_task_logger
import environ

logger = get_task_logger(__name__)
env = environ.Env()

class ProcessUserRequest(APIView):
    permission_classes = [HasAPIKey |IsAuthenticated ]
    def get(self, request):
        logger.info("Get Business User Request Received")
        result = GetBusinessUser(request)
        return Response(result["result"], 
                        content_type='application/json charset=utf-8', 
                        status=result["statuscode"]

这会额外调用以下缩短函数:

def GetBusinessUser(request) -> Dict[str, Union[str, int]]:
    logger.info(f"Processing Get Username Request: {request.data}")
    valid_serializer = ValidateGetBusinessUserFormSerializer(data=request.data)
    valid_serializer.is_valid(raise_exception=True)
    username = valid_serializer.validated_data['username']
    return BusinessUser.objects.filter(username=username).first()

由于我希望创建单元测试用例以确保可以在部署之前进行验证,因此我在模块www.example.com文件中实现了以下内容tests.py:

from rest_framework.test import APITestCase, APIClient
from rest_framework_api_key.models import APIKey
from user_api.classes.UserController import GetBusinessUser
from django.urls import reverse

# Class Method for GetBusinessUser (truncated)
# try except handling and other user checks removed for stack

class ProcessUserRequestTest(APITestCase):
    def setUp(self):
        self.client = APIClient()
        # have also tried: self.headers = {'HTTP_AUTHORIZATION': f'Api-Key {self.api_key.key}'}
        self.client.credentials(HTTP_AUTHORIZATION='Api-Key SomeApiKeyValue')
        self.url = reverse('business_user')
        self.valid_payload = {'username': 'test@testing.local'}
        self.invalid_payload = {'param1': '', 'param2': 'value2'}

    def test_get_business_user_request(self):
        # also tried based on above:
        #  response = self.client.get(self.url, **self.headers, format='json')
        response = self.client.get(self.url, data=self.valid_payload, format='json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data, GetBusinessUser(response.data).data)

无论我做什么,下面的代码总是被返回,所以从测试中可以看出,添加身份验证头或使用client.credentials不工作,Authorization: Api-Key somekey作为头?

creating test database for alias 'default'...
System check identified no issues (0 silenced).
{'detail': ErrorDetail(string='Authentication credentials were not provided.', code='not_authenticated')}
F
======================================================================
FAIL: test_get_business_user_request (user_api.tests.ProcessUserRequestTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "../truncated/tests.py", line 19, in in test_get_business_user_request
    self.assertEqual(response.status_code, 200)
    AssertionError: 403 != 200

----------------------------------------------------------------------
Ran 1 test in 0.018s

FAILED (failures=1)
Destroying test database for alias 'default'...

以前遇到过这种情况吗?有没有可行的解决方案,以便我可以创建单元测试?

vs91vp4v

vs91vp4v1#

我已经为此挣扎了一段时间,但想通了,下面是一个例子,为我工作。

_, key = APIKey.objects.create_key(name="test")
authorization = f"Api-Key {key}"
response = self.client.put(url, data, HTTP_AUTHORIZATION=authorization, format="json")

现在,在你的情况下,我认为它看起来更像:

from rest_framework.test import APITestCase, APIClient
from rest_framework_api_key.models import APIKey
from user_api.classes.UserController import GetBusinessUser
from django.urls import reverse

class ProcessUserRequestTest(APITestCase):
    def setUp(self):
        self.client = APIClient()
        self.url = reverse('business_user')
        self.valid_payload = {'username': 'test@testing.local'}
        self.invalid_payload = {'param1': '', 'param2': 'value2'}

    def test_get_business_user_request(self):
         _, key = APIKey.objects.create_key(name="test")
        authorization = f"Api-Key {key}"
        response = self.client.get(self.url, data=self.valid_payload, HTTP_AUTHORIZATION=authorization, format='json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data, GetBusinessUser(response.data).data)

我还没有测试你的代码,把它看作伪代码。请让我知道,如果你能使它的工作,然后我可以调整我的伪代码相应。
干杯

jv4diomz

jv4diomz2#

我认为你必须手动测试API-KEY,但是当你必须访问API时,你只需要验证被请求的现有用户。

force_authenticate(request, user=user)  # to docs
self.client.force_authenticate(user=self.user) # im using like this it works

参见https://www.django-rest-framework.org/api-guide/testing/

  • 强制身份验证

在DRF原始文档的给定链接上检查此点

相关问题