django - 为 Django 认证的 API 视图编写测试用例
问题描述
我已经在 TestCase 上成功写了,它工作得很好。
首先看看我的代码:
下面是我的tests.py
from django.shortcuts import reverse
from rest_framework.test import APITestCase
from ng.models import Contact
class TestNoteApi(APITestCase):
def setUp(self):
# create movie
self.contact = Contact(userId=254, name="The Space Between Us", phone=2017, email='doe@f.com')
self.contact.save()
def test_movie_creation(self):
response = self.client.post(reverse('getAndPost'), {
'userId': 253,
'name': 'Bee Movie',
'phone': 2007,
'email': 'ad@kjfd.com'
})
self.assertEqual(Contact.objects.count(), 2)
上面的代码片段工作正常,但问题是.. 一旦我实现了身份验证系统,它就不起作用
下面是我的settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
如果我更改为AllowAny
许可,则测试效果很好,但如果保留IsAuthenticated
而不是AllowAny
,则它不起作用。
我希望即使我IsAuthenticated
得到许可,测试也应该运行良好。
谁能建议我该怎么做?我没有得到要更改的内容或tests.py
文件中添加的内容。
解决方案
您应该在方法中创建user
对象setUp
,并使用client.login()
orforce_authenticate()
发出经过身份验证的请求:
class TestNoteApi(APITestCase):
def setUp(self):
# create user
self.user = User.objects.create(username="test", password="test")
# create movie
self.contact = Contact(userId=254, name="The Space Between Us", phone=2017, email='doe@f.com')
self.contact.save()
def test_movie_creation(self):
# authenticate client before request
self.client.login(username='test', password='test')
# or
self.clint.force_authenticate(user=self.user)
response = self.client.post(reverse('getAndPost'), {
'userId': 253,
'name': 'Bee Movie',
'phone': 2007,
'email': 'ad@kjfd.com'
})
self.assertEqual(Contact.objects.count(), 2)
推荐阅读
- arcgis-js-api - ArcGIS API for JavaScript 4 相当于 JavaScript 3 下一个和上一个范围?
- python - iterm2 API:连接调用失败('127.0.0.1',1912)
- java - 在 spring boot 2.4.4 rest java 11 应用程序中是否可以在 rest 控制器和控制器建议之间进行映射?
- python - 如何在 Django 中创建带有下拉列表的提交表单?
- swift - 如何更改文本和背景颜色 UIMenu | UIAction (Swift 5)
- python - 无法在 selenium python 中通过 xpath 选择按钮
- sql - 如何将 ORACLE 日期和时间戳类型转换为带时区的字符串?
- kubernetes - Openshift 4 证书位置和手动续订过程
- android - Android Kotlin-Flow:改造调用失败,没有抛出异常
- java - Criteria API:查找字段中的第一个值