Django APIClient登录不起作用
问题描述:
我在单元单元测试中遇到了使用我的Django Rest Framework API进行身份验证的问题。系统通过浏览器访问时按预期工作。Django APIClient登录不起作用
class UserDetail(RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin, GenericViewSet):
authentication_classes = (BasicAuthentication, TokenAuthentication)
permission_classes = IsAuthenticated,
queryset = CustomUser.objects.all()
serializer_class = UserSerializer
试验下面如下:在下面的端点发送PUT请求发送到下面的类时,我然而收到一个401的HTTP状态
class AccountTests(APITestCase):
def setUp(self):
self.user = CustomUser.objects.create_user(email="[email protected]", password="password1", is_staff=True)
self.user.save()
self.user = CustomUser.objects.get(email="[email protected]")
self.client = APIClient()
def test_add_name(self):
self.client.login(email="[email protected]", password='password1')
url = reverse('customuser-detail', args=(self.user.id,))
data = {'first_name': 'test', 'last_name': 'user'}
self.client.login(email="[email protected]", 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的东西吗?甚至在测试本身?
谢谢。
答
首先,{u'detail': u'Authentication credentials were not provided.'}
发生在您“提供”的凭据与模型不匹配时。 (我认为是错误信息)
所以,你应该设置用户密码为set_password()
方法,因为加密。
self.user = CustomUser.objects.create_user(email="[email protected]", 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="[email protected]", 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)
你解决问题? – Ajax