Django Rest Framework - How to test ViewSet?

前端 未结 5 1727
萌比男神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:44

    I think I found the correct syntax, but not sure if it is conventional (still new to Django):

    def test_view_set(self):
        request = APIRequestFactory().get("")
        cat_detail = CatViewSet.as_view({'get': 'retrieve'})
        cat = Cat.objects.create(name="bob")
        response = cat_detail(request, pk=cat.pk)
        self.assertEqual(response.status_code, 200)
    

    So now this passes and I can assign request.user, which allows me to customize the retrieve method under CatViewSet to consider the user.

提交回复
热议问题