我在单元单元测试中使用我的 Django Rest Framework API 进行身份验证时遇到问题。通过浏览器访问系统时,系统按预期工作。但是,在向以下端点的以下类发送放置请求时,我收到 401 HTTP 状态:
class UserDetail(RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin, GenericViewSet):
authentication_classes = (BasicAuthentication, TokenAuthentication)
permission_classes = IsAuthenticated,
queryset = CustomUser.objects.all()
serializer_class = UserSerializer
以下测试如下:
class AccountTests(APITestCase):
def setUp(self):
self.user = CustomUser.objects.create_user(email="user1@test.com", password="password1", is_staff=True)
self.user.save()
self.user = CustomUser.objects.get(email="user1@test.com")
self.client = APIClient()
def test_add_name(self):
self.client.login(email="user1@test.com", password='password1')
url = reverse('customuser-detail', args=(self.user.id,))
data = {'first_name': 'test', 'last_name': 'user'}
self.client.login(email="user1@test.com", password='password1')
response = self.client.put(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
打印响应数据时,我收到:
{u'detail': u'Authentication credentials were not provided.'}
client.login(...) 方法返回 true,但凭据似乎未附加到标头。我在IsAuthentication权限类中的实验有一个request.user = AnonymousUser。在基本身份验证类中,auth = None。
我是否缺少有关在 settings.py 中使用BasicAuth的内容?甚至在测试本身中?
谢谢。
,当您"提供"的凭据与模型不匹配时,会发生{u'detail': u'Authentication credentials were not provided.'}
。(我认为这是错误的错误消息)
因此,由于加密,您应该通过set_password()
方法设置用户的密码。
self.user = CustomUser.objects.create_user(email="user1@test.com", is_staff=True)
self.user.set_password("password1")
self.user.save()
或者,您可以使用force_login()
进行测试。
self.client.force_login(
user=User.objects.first(),
backend='django.contrib.auth.backends.ModelBackend' # one of your AUTHENTICATION_BACKENDS
)
使用force_authenticate()
方法登录,
def test_add_name(self):
self.client.force_authenticate(self.user)
........
你可以考虑重写你的测试用例,也许有点像这样,
class AccountTests(APITestCase):
def setUp(self):
self.user = CustomUser.objects.create_user(email="user1@test.com", password="password1", is_staff=True)
self.client = APIClient()
def test_add_name(self):
self.client.force_authenticate(self.user)
url = reverse('customuser-detail', args=(self.user.id,))
data = {'first_name': 'test', 'last_name': 'user'}
response = self.client.put(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)