如何在测试 drf 时避免身份验证错误?

How to avoid an authentication error during testing drf?

在开发过程中,所有类都写了一个变量permission_classes = [permissions.AllowAny, ]。在文件 setting.py 中设置

'DEFAULT_AUTHENTICATION_CLASSES': [
    'rest_framework_simplejwt.authentication.JWTAuthentication', 
    'rest_framework.authentication.SessionAuthentication', 
],

编写测试时,没有考虑到需要用户身份验证才能满足请求。因此,当删除参数 [permissions.AllowAny, ] 时,会发生错误 401 Unauthorized

old_test.py

from django.test import TestCase, Client
from django.urls import reverse
from django.db import IntegrityError

from rest_framework.test import APITestCase
from rest_framework import status

class VendorProfileUpdateViewTest(APITestCase):

    def test_check_partial_update_api(self):
        data = {"vendor_name": "UN"}
        vendor = Vendors.objects.create(vendor_name="U4", country="US", nda="2020-12-12", )
        VendorContacts.objects.create(contact_name="Mrk", phone="2373823", email="test@gmail.com", vendor=vendor)
        _id = vendor.vendorid
        url = reverse('vendor_update',  kwargs={'vendorid': _id})
        response = self.client.put(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        vendor = Vendors.objects.get(vendorid=_id)
        self.assertEqual(vendor.vendor_name, 'UN')

我尝试通过以下方式添加 force_authenticate() 配置:

class ContactsUpdateViewTest(APITestCase):

    def tearDown(self): 
        self.client.force_authenticate(user=None)

    def test_contact_partial_update_api(self):
        ....

但是没有任何变化。

您应该在测试函数中调用 force_authenticate(...) 方法

class ContactsUpdateViewTest(APITestCase):

    def test_contact_partial_update_api(self):
        user = User.objects.get(pk=1)
        self.client.force_authenticate(user=user)
        # rest of your test case

您需要通过用户实例进行身份验证。如果你正在测试私有端点,最好在 TestCase 提供的 setUp 方法中进行测试初始化​​。

    def setUp(self):
        self.client = APIClient()
        self.user = get_user_model().objects.create(
            username="testUser",
            password="testpass",
           // other fields
        )
        self.client.force_authenticate(self.user)