【发布时间】: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