Home > database >  What unit tests could I build for a class like this?
What unit tests could I build for a class like this?

Time:07-05

I have several such classes in my views. And I need to test them all.

class ExampleViewSet(viewsets.ModelViewSet):
    serializer_class = ExampleSerializer
    queryset = Example.objects.all()
    filter_backends = (filters.DjangoFilterBackend,)
    filterset_class = ExampleFilter

All were created with the help of available Django Rest Framework libraries.

CodePudding user response:

ViewSet are basically REST Endpoints so if you have it registered in a URL you shoud be able to write test to all the CRUD operations:

router.register(r'examples', views.ExampleViewSet, basename='example')

This will generate the following:

  • example-list -> /examples -> GET
  • example-detail -> /examples/1 -> GET
  • example-list -> /examples -> POST
  • example-detail -> /examples/1 -> PUT
  • example-detail -> examples/1 -> DELETE

So you can test each endpoint to ensure that the expected logic is met for them.

Example of the tests:

class ExampleViewSetTestCase(APITestCase):
    @classmethod
    def setUpTestData(cls):
        # Example.objects.create(...)
        # cls.user = User.objects.create(...)

    def authenticate(self):
        self.client.force_login(self.user)

    def test_list_examples(self):
        self.authenticate()
        response = self.client.get(reverse('example-list'))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data['results']), 1)
        self.assertEqual(
            dict(response.data['results'][0]),
            {'id': '1', 'key': 'value'})
    # More test to Update, Create and Delete.
  • Related