2

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.

a13xg0
  • 387
  • 3
  • 11

1 Answers1

1

Try

response = view(request, switch_id=3)

Or

response = view(request, {"switch_id": 3})
Reza Heydari
  • 1,146
  • 1
  • 6
  • 10
  • Thank you, works fine! Can you explain why DRF didn't parse the URL passed in the factory method properly? I'm new with DRF and Django and don't understand why it didn't work as expected – a13xg0 Jul 09 '21 at 00:15
  • 1
    https://stackoverflow.com/a/48581361/12912476 check it, explains very well – Reza Heydari Jul 09 '21 at 00:19