How can I properly test swagger_auto_schema for methods, request_body, and responses in drf-yasg with pytest?

I’m working on testing a Django REST Framework (DRF) CartViewSet using pytest, and I need to verify the swagger_auto_schema properties like the HTTP method, request body, and responses for different actions (e.g., add, remove, clear).

I have the following code in my CartViewSet:

class CartViewSet(GenericViewSet, RetrieveModelMixin, ListModelMixin):
    # Other viewset code...

    @swagger_auto_schema(
        method="post",
        request_body=AddToCartSerializer,
        responses={
            201: openapi.Response(description="Item added successfully."),
            400: openapi.Response(description="Invalid input data"),
        },
    )
    @action(detail=False, methods=["post"], url_path="add")
    def add(self, request):
        # Logic for adding an item to the cart
        pass

Now, I want to write a pytest unit test to check the following for the add method:

  1. HTTP Method: Ensure the swagger_auto_schema method is POST.
  2. Request Body: Ensure the correct serializer (AddToCartSerializer) is set for the request body.
  3. Responses: Verify that the response status codes (201 and 400) and their descriptions are properly set.

Could someone guide me on how to properly test the swagger_auto_schema properties for method, request body, and responses in pytest?

Any help or insights would be greatly appreciated!

Вернуться на верх