I'm writing tests to check if the Authenticated users have access to the API Endpoints.
On my test settings, I have set the defaults for Rest Framework Authentication and Permissions Classes. The default setting is that everyone has to be authenticated to access the API.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)}
This is the function which is failing (and all others). Here, I create a user object with a custom UserFactory which is setting a default email and password for each user created. Then I use the APIClient with basic authentication to log in. I'm following the official 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())
The test fails with Not Authorized Status Code AssertionError: 401 != 200
答案 0 :(得分:1)
问题在于这一行:response = self.get(retrieve=entity.pk)
由于您使用client
登录,因此您必须继续使用它来发送请求:response = client.get(retrieve=entity.pk)