Django Rest Framework API 认证测试 [英] Django Rest Framework API Authentication Test
问题描述
我正在编写测试以检查经过身份验证的用户是否有权访问 API 端点.
I'm writing tests to check if the Authenticated users have access to the API Endpoints.
在我的测试设置中,我为 Rest Framework 身份验证和权限类设置了默认值.默认设置是每个人都必须通过身份验证才能访问 API.
On my test settings, I have set the defaults for Rest Framework Authentication and Permissions Classes. The default setting is that everyone has to be authenticated to access the API.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)}
这是失败的功能(以及所有其他功能).在这里,我创建了一个带有自定义 UserFactory 的用户对象,该对象为每个创建的用户设置默认电子邮件和密码.然后我使用带有基本身份验证的 APIClient 登录.我正在关注官方 Django Rest 框架文档
This is the function which is failing (and all others). Here, I create a user object with a custom UserFactory which is setting a default email and password for each user created. Then I use the APIClient with basic authentication to log in. I'm following the official Django Rest Framework Documentation
def test_retrieve(self):
user = UserFactory.create()
client = APIClient()
client.login(email=user.email, password=user.password)
entity = AttributeChoiceFactory.create()
response = self.get(retrieve=entity.pk)
self.assertEqual(response.status_code, status.HTTP_200_OK)
item = json.loads(response.content)
self.assertEqual(type(item), dict)
self.assertEqual(item['pk'], entity.pk)
self.assertItemsEqual(AttributeChoiceSerializer.Meta.fields, item.keys())
测试失败并显示未授权状态代码 AssertionError: 401 != 200
The test fails with Not Authorized Status Code AssertionError: 401 != 200
推荐答案
问题出在这一行:response = self.get(retrieve=entity.pk)
既然是使用client
登录,那么必须继续使用它来发送请求:response = client.get(retrieve=entity.pk)
Since you are using client
to login, you must continue to use it to send requests: response = client.get(retrieve=entity.pk)
这篇关于Django Rest Framework API 认证测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!