Django Rest Framework - How to test ViewSet?
django, django-rest-framework, python
Solution
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.
Problem
I'm having trouble testing a ViewSet: ``` class ViewSetTest(TestCase): def test_view_set(self): factory = APIRequestFactory() view = CatViewSet.as_view() cat = Cat(name="bob") cat.save() request = factory.get(reverse('cat-detail', args=(cat.pk,))) response = view(request) ``` I'm trying to replicate the syntax here: http://www.django-rest-framework.org/api-guide/testing#forcing-authentication But I think their AccountDetail view is different from my ViewSet, so I'm getting this error from the last line: ``` AttributeError: 'NoneType' object has no attributes 'items' ``` Is there a correct syntax here or am I mixing up concepts? My APIClient tests work, but I'm using the factory here because I would eventually like to add "request.user = some_user". Thanks in advance! Oh and the client test works fine: ``` def test_client_view(self): response = APIClient().get(reverse('cat-detail', args=(cat.pk,))) self.assertEqual(response.status_code, 200) ```