简体   繁体   English

测试drf时如何避免认证错误?

[英]How to avoid an authentication error during testing drf?

During the development process, all classes were written with a variable permission_classes = [permissions.AllowAny, ] .在开发过程中,所有类都使用变量permission_classes = [permissions.AllowAny, ]编写。 In the file setting.py set在文件setting.py中设置

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

When writing the tests, it was not considered that user authentication is required to fulfill the request.在编写测试时,没有考虑到需要用户身份验证来完成请求。 Therefore, when the parameter [permissions.AllowAny, ] was removed the error 401 Unauthorized occurred.因此,当参数[permissions.AllowAny, ]被删除时,出现错误401 Unauthorized

old_test.py 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')

I tried to add force_authenticate() configuration in the following way:我尝试通过以下方式添加 force_authenticate() 配置:

class ContactsUpdateViewTest(APITestCase):

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

    def test_contact_partial_update_api(self):
        ....

But there have been no changes.但是没有任何变化。

You should call the force_authenticate(...) method in your test function您应该在测试 function 中调用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

You need to pass the user instance to authenticate.您需要传递用户实例进行身份验证。 And it's better to do the test initialization in setUp method provided by TestCase if you're testing Private endpoints.如果您正在测试私有端点,最好在 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM