Python – How to write unit tests for django-rest-framework api’s

djangodjango-rest-frameworkmockingpythonunit-testing

I have exposed my database model using Django-rest-framework view sets and routers, and I am trying to write the unit tests for it.

Here are my API and test code

Viewsets.py

class Model1ViewSet(viewsets.ReadOnlyModelViewSet):

    model = Model1
    serializer_class = Model1Serializer
    filter_class = Model1Filter
    filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter)
    ordering = ('id', 'cl1')

Serializer.py

class Model1Serializer(serializers.HyperlinkedModelSerializer):
    chip = serializers.HyperlinkedRelatedField(view_name="some-detail")

    class Meta:
        model = Model1
        fields = ('url', 'id', 'cl1', 'cl2', 'cl3', 'cl4')
        depth = 1

Unit-tests

from rest_framework.test import APIClient

class TestModel1Api(unittest.TestCase):

    def setUp(self):
        self.client = APIClient()

    def test_Model1_list(self):
        response = self.client.get(reverse('Model1-list'))
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_Model1_detail(self):
        mm_objs = Model1.objects.all()
        if mm_objs:
            response = self.client.get(reverse('Model1-detail', args=[mm_objs[0].id]))
            self.assertEqual(response.status_code, status.HTTP_200_OK)

I don't want to connect to the database for unit testing because it falls under integration tests.

Is there any way to mock the database? I know how to apply mocking for standard view functions but here mocking is not working.

  1. How to write the unit tests for my REST-API?
  2. How to mock the database in my unit-tests?

Best Solution

When you run manage.py test then the base of your database will be created but it contains no data. To do that you can simply create the necessary objects yourself or use something like FactoryBoy

Just keep in mind that the database is cleaned of data from previous test methods when starting a new one.

Related Question