Django Rest Framework viewset mypy error: Missing positional argument

Here is a problem, when testing method from drf viewsets with @action() decorator, mypy gives error expecting additional argument (which is self param). Here it is:

# views.py


class UserViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet):
    serializer_class = UserSerializer
    queryset = User.objects.all()
    lookup_field = "username"

    def get_queryset(self, *args, **kwargs):
        assert isinstance(self.request.user.id, int)
        return self.queryset.filter(id=self.request.user.id)

    @action(detail=False)
    def me(self, request: WSGIRequest):
        serializer = UserSerializer(request.user, context={"request": request})
        return Response(status=status.HTTP_200_OK, data=serializer.data)

# test_views.py


def test_me(self, user: User, rf: RequestFactory):
        view = UserViewSet()
        request = Request(rf.get("/fake-url/"))
        request.user = user

        view.request = request

        response = view.me(request) # The problem is here

        assert response.data == {
            "username": user.username,
            "name": user.name,
            "url": f"http://testserver/api/users/{user.username}/",
        }

and the log is:

drf_project\users\tests\test_drf_views.py:25: error: Missing positional argument "request" in call to "me" of "UserViewSet"
drf_project\users\tests\test_drf_views.py:25: note: "__call__" is considered instance variable, to make it class variable use ClassVar[...]
drf_project\users\tests\test_drf_views.py:25: error: Argument 1 to "me" of "UserViewSet" has incompatible type "Request"; expected "UserViewSet"

How can I solve this except ignoring it with type: ignore[]?

The probem is that @action decorator in viewset changes the type of method, without it mypy is okay. However @action() ruins it. I need to overcome this, any suggestions?

Back to Top