我正在尝试使用 DRF APITestcase 测试基于 API 的 DRF 并面临此错误 {"detail":"User not found","code":"user_not_found"} '

I am trying to test a DRF based API using DRF APITestcase and facing this error {"detail":"User not found","code":"user_not_found"}'

您好,我正在 运行宁 python 中基于 API 的 DRF 测试用例,使用来自 Django-Rest-Framework 的 API 测试用例。此测试用例是为测试帐户创建而编写的。在邮递员中同样有效,但是在测试用例中 运行ning 时,我遇到了这个错误。我指的是文档 DRF APi testig Documentation.

在下面找到我的 Test.py 代码。

from django import test
from django.conf.urls import url
from django.http import response
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient, APITestCase

from account.api import serializer
from account.models import Account


# Create your tests here.
class RegistrationTestCase(APITestCase):
    
    databases = {"default", "django_tables"}
    
    def test_create_account(self):
        # Details to create new user
        data = {
            "username": "test2@gmail.com",
            "email": "test2@gmail.com",
            "password": "**********",
            "confirm_password": "**********"
        }
        #url = reverse('register',current_app='account')        
        self.client = APIClient()
        self.client.credentials(HTTP_AUTHORIZATION='Bearer ***********************')
        #client.force_authenticate(user=None)
        response = self.client.post('http://127.0.0.1:8000/api/account/register',data,format='json')
        print(response.content)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

Views.py

from django.contrib.auth.models import User
from rest_framework.response import Response
from rest_framework.decorators import api_view

from .serializer import RegistrationSerializer
from rest_framework.authtoken.models import Token
from rest_framework_simplejwt.tokens import RefreshToken, AccessToken

# # this represents to accounsts app
# # To create a new account

@api_view(['POST', ])
def registration_view(request):
    if request.method == 'POST':
        serializer = RegistrationSerializer(data=request.data)
        data = {}
        if serializer.is_valid():
            account = serializer.save()
            data['response'] = "Successfully registered a new user."
            data['email'] = account.email
            data['username'] = account.username
            
            # call function to generate tokens manually 
            token_dict = get_tokens_for_user(account)
            refresh = token_dict['refresh']
            access = token_dict['access']
            data['refresh'] = refresh
            data['access'] = access
        else:
            data = serializer.errors
        return Response(data)

# Generate the referesh token manually and display when new user is created
def get_tokens_for_user(user):
    refresh = RefreshToken.for_user(user)

    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    }

错误响应

(env) E:\Django\cemd-api\app>py manage.py test
Creating test database for alias 'default'...
Creating test database for alias 'django_tables'...
System check identified no issues (0 silenced).
b'{"detail":"User not found","code":"user_not_found"}'
F
======================================================================
FAIL: test_create_account (account.tests.RegistrationTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "E:\Django\cemd-api\app\account\tests.py", line 29, in test_create_account
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)
AssertionError: 401 != 201

----------------------------------------------------------------------
Ran 1 test in 5.072s

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

我也想在未来对其他 URL 进行自动化,它可以在特定的时间间隔内 运行 然后单独记录测试结果。除此之外,请帮助我处理任何其他包以及 API 测试。我对 Django 很陌生,请帮忙。 提前致谢!!!

这很可能是由您的 REST_FRAMEWORK 设置的默认身份验证 类 引起的。尝试为您的 register 视图禁用身份验证 类 和权限 类:

from rest_framework.decorators import api_view, permission_classes, authentication_classes

@api_view(['POST', ])
@authentication_classes([])
@permission_classes([])
def register(request):
    ...