Django Rest Framework - How to test ViewSet?

前端 未结 5 1719
萌比男神i
萌比男神i 2021-01-31 09:24

I\'m having trouble testing a ViewSet:

class ViewSetTest(TestCase):
    def test_view_set(self):
        factory = APIRequestFactory()
        view = CatViewSet.         


        
5条回答
  •  遥遥无期
    2021-01-31 09:51

    I had the same issue, and was able to find a solution.

    Looking at the source code, it looks like the view expects there to be an argument 'actions' that has a method items ( so, a dict ).

    https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/viewsets.py#L69

    This is where the error you're getting is coming from. You'll have to specify the argument actions with a dict containing the allowed actions for that viewset, and then you'll be able to test the viewset properly.

    The general mapping goes:

    {
        'get': 'retrieve',
        'put': 'update',
        'patch': 'partial_update',
        'delete': 'destroy'
    }
    

    http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers

    In your case you'll want {'get': 'retrieve'} Like so:

    class ViewSetTest(TestCase):
        def test_view_set(self):
            factory = APIRequestFactory()
            view = CatViewSet.as_view(actions={'get': 'retrieve'}) # <-- Changed line
            cat = Cat(name="bob")
            cat.save()
    
            request = factory.get(reverse('cat-detail', args=(cat.pk,)))
            response = view(request)
    

    EDIT: You'll actually need to specify the required actions. Changed code and comments to reflect this.

提交回复
热议问题