Testing DRF GenericViewSet with parameters in url_path

Viewed 277

I'm trying to test DRF endpoint with unittest. View under the test:

class HwView(mixins.ListModelMixin, viewsets.GenericViewSet):

    @action(detail=False, methods=['get'], url_path='switch_state/(?P<switch_id>\d+)')
    def switch_state(self, request, switch_id):
        print(f'sw: {switch_id}')
        
        results = {"state": 'ok'}

        return Response(results)

Entry in the url.py

from rest_framework import routers
router = routers.DefaultRouter()

router.register(r'hw', hw_views.HwView, basename='HwModel')

And the test code

from rest_framework.test import APIRequestFactory, APITestCase


class TestCommandProcessor(APITestCase):
    def setUp(self):
        pass

    def test_switch_state(self):
        factory = APIRequestFactory()
        request = factory.get(
            '/api/hw/switch_state/3',
        )

        view = HwView.as_view({'get': 'switch_state'}, basename='HwModel')

        response = view(request)

        self.assertIn('state', response.data)
        self.assertEqual('ok', response.data['state'])

As I run the test I'm getting the error:

TypeError: switch_state() missing 1 required positional argument: 'switch_id'

Any other methods in this view (GET without parameters, POST with parameters) work fine with the same testing approach.

Can you help me find out why my view can't parse parameters in the URL? Or any advice on how can I rewrite my test to successfully test my code.

1 Answers

Try

response = view(request, switch_id=3)

Or

response = view(request, {"switch_id": 3})
Related