Home > Blockchain >  How to Use Viewsets and Serializers in pytest==7.0.1 Parametrize in Testing djangorestframework==3.1
How to Use Viewsets and Serializers in pytest==7.0.1 Parametrize in Testing djangorestframework==3.1

Time:02-26

I am using a Django Project Template from here. I am testing my serializers and permission in every viewset my app has. I want to use parametrize from pytest to reduce the lines I need to write tests to each serializers and viewset. I have 10 serializers and viewset that I need to test which has a pattern as shown bellow.

test_drf_viewsets.py

    @pytest.mark.parametrize(
        ("app_url", "app_viewset", "serializer"),
        [
            (
                "api:mv-signup-list",
                viewset.UserSignUpMaterializedViewSet,
                serializers.UserSignUpMaterializedViewSerializer,
            ),
            (
                "api:mv-total-list",
                viewset.TotalMaterializedViewSet,
                serializers.TotalMaterializedViewSerializer,
            ),
        ],
    )
    def test_get_serializer(
        self,
        admin_user: User,
        app_url: str,
        app_viewset,
        serializer,
        rf: RequestFactory,
    ):
       
        viewsets = app_viewset

        request = rf.get(reverse(app_url))
        request.user = admin_user

        viewsets.request = Request(request)
        viewsets.format_kwarg = None

        assert isinstance(viewsets.get_serializer(), serializer)

However, when I run the code above, it shows this error

TypeError: GenericAPIView.get_serializer() missing 1 required positional argument: 'self'
  • The code presented above is omitted for brevity.

CodePudding user response:

I found a minimal solution that works for my use case.

Instead of using these:

assert isinstance(viewsets.get_serializer(), serializer)

Change it to these:

assert viewsets.serializer_class == serializer

Same with get_permission:

assert viewsets.permission_classes[0] == IsAuthenticated

The code above works when these are changed.

  • Related