【问题标题】:Django Rest Framework API Authentication TestDjango Rest Framework API 身份验证测试
【发布时间】: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


    【解决方案1】:

    问题出在这一行:response = self.get(retrieve=entity.pk)

    由于您使用client登录,您必须继续使用它发送请求:response = client.get(retrieve=entity.pk)

    【讨论】:

      猜你喜欢
      • 2015-06-01
      • 2013-12-29
      • 2015-06-04
      • 2017-08-15
      • 2019-01-01
      • 1970-01-01
      • 2013-05-03
      • 2015-09-25
      • 2021-09-09
      相关资源
      最近更新 更多