DEV Community

Ori Roza
Ori Roza

Posted on

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

Hi all! Iā€™m proud to share my new first open-source project drf-api-action, and Iā€™d be glad to receive your feedback!

https://github.com/Ori-Roza/drf-api-action

This project was built as a side project at work in which we had to tweak DRF for our own needs, this project was successful back then so I wanted to publish it to everyone

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 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)
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)