Raise_exception not working with token base authentication

I'm trying to run my tests on status codes while i'm not providing token on POST request

So viewset looking like this:

class TopicViewSet(viewsets.ModelViewSet):
    serializer_class = TopicSerializer
    permission_classes = (IsOwnerOrReadOnly, )
    pagination_class = TopicPagination

    def get_queryset(self):
        queryset = Topic.objects.all().select_related(
            'owner',
        )
        return queryset

Permission class i'm using:

class IsOwnerOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True

        return obj.owner == request.user

Test itself:

@pytest.mark.django_db
def test_topic_post_method_is_not_allowed_unauthenticated_user(api_client, topics_url):
    response = api_client.post(topics_url, data={'name': 'hello', 'slug': 'hello'})
    assert response.status_code == 401

So all i want is just a simple response like:

{
    "detail": "Authentication credentials were not provided."
}

But i'm getting html django generated page(screenshot from Postman): enter image description here

When you set new permission classes via the class attribute, the the view will ignore the default list in the settings.py file.

You probably need to compose the permission list with the IsAuthenticated. And the error you're getting is because of request.user is not returning a CustomUser instance, you may need to query that custom user if your auth system is not injecting its instance in your request.

You can try to change the permissions to:

permission_classes = (IsAuthenticated, IsOwnerOrReadOnly,)
# or
permission_classes = (IsAuthenticated & IsOwnerOrReadOnly,)
Back to Top