Django Rest Framework API Authentication Test

2019-08-31 09:13发布

问题:

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

回答1:

The problem lies on this line: response = self.get(retrieve=entity.pk)

Since you are using client to login, you must continue to use it to send requests: response = client.get(retrieve=entity.pk)