我在单元测试中使用Django Rest Framework API进行身份验证时遇到了问题。通过浏览器访问系统时,系统会按预期工作。但是,在向以下端点的以下类发送put请求时,我收到一个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)当打印response.data时,我收到:
{u'detail': u'Authentication credentials were not provided.'}client.login(...)方法返回true,但凭据似乎未附加到标头。我在IsAuthenticated权限类中的实验有一个request.user = AnonymousUser。在BasicAuthentication类中,auth = None。
关于在settings.py中使用BasicAuth,我是否遗漏了什么?或者甚至是在测试本身?
谢谢。
发布于 2017-07-19 15:31:23
首先,当您“提供”的凭证与模型不匹配时,就会发生{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
)发布于 2017-07-19 15:39:25
您可能需要使用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)https://stackoverflow.com/questions/37513050
复制相似问题