我在单元测试中使用我的 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)
打印 response.data 时,我收到:
{u'detail': u'Authentication credentials were not provided.'}
client.login(...) 方法返回 true,但凭据似乎没有附加到 header 。我在 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="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
)
关于Django APIClient 登录不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37513050/