The project that will make you enjoy writing tests for your Django app

The drf-api-action Python package is designed to elevate your testing experience for Django Rest Framework (DRF) REST endpoints by treating REST endpoints as a regular functions!

Features:

  • Simplified Testing: Testing DRF REST endpoints using the api-action decorator, treating them like regular functions.
  • Seamless Integration: Replacing DRF’s action decorator with api-action in your WebViewSet seamlessly or using it as a pytest fixture.
  • Clear Traceback: Instead of getting a response with error code, get the real traceback that led to the error.
  • Pagination Support: Paginating easily through pages by a single kwarg.

Here’s a snippet with new pytest fixture addition:

from .models import DummyModel
from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.serializers import IntegerField, ModelSerializer, Serializer


class DummySerializer(ModelSerializer):
    dummy_int = IntegerField()

    class Meta:
        model = DummyModel
        fields = "__all__"

class DummyViewSetFixture(ModelViewSet):
    queryset = DummyModel.objects.all()
    serializer_class = DummySerializer

    @action(detail=True, methods=["get"], serializer_class=DummySerializer)
    def api_dummy(self, request, **kwargs):
        serializer = self.get_serializer(instance=self.get_object())
        return Response(data=serializer.data, status=status.HTTP_200_OK)

tests.py

import pytest
from tests.test_app.models import DummyModel
from tests.test_app.views import DummyViewSetFixture
from drf_api_action.fixtures import action_api

@pytest.mark.action_api(view_set_class=DummyViewSetFixture)
def test_call_as_api_fixture(db, action_api):
    dummy_model = DummyModel()
    dummy_model.dummy_int = 1
    dummy_model.save()
    res = action_api.api_dummy(pk=1)
    assert res["dummy_int"] == 1

Please let me know what you think, Your feedback means a lot to me!