【发布时间】:2018-07-04 23:25:09
【问题描述】:
我正在编写测试来检查经过身份验证的用户是否可以访问 API 端点。
在我的测试设置中,我为 Rest Framework 身份验证和权限类设置了默认值。默认设置是每个人都必须经过身份验证才能访问 API。
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)}
这是失败的功能(以及所有其他功能)。在这里,我使用自定义 UserFactory 创建一个用户对象,该对象为每个创建的用户设置默认电子邮件和密码。然后我使用带有基本认证的APIClient登录。我关注的是官方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
【问题讨论】:
标签: django api django-rest-framework