【问题标题】:How to avoid an authentication error during testing drf?测试drf时如何避免认证错误?
【发布时间】:2020-05-13 06:54:34
【问题描述】:

在开发过程中,所有类都使用变量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):
        ....

但没有任何变化。

【问题讨论】:

    标签: django unit-testing django-rest-framework django-unittest


    【解决方案1】:

    您应该在测试函数中调用 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

    【讨论】:

      【解决方案2】:

      您需要传递用户实例进行身份验证。如果您正在测试 Private 端点,最好在 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)
      

      【讨论】:

        猜你喜欢
        • 2020-06-01
        • 2018-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-10
        • 2015-10-04
        • 1970-01-01
        相关资源
        最近更新 更多