Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework - How to test ViewSet?

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) 
like image 950
WBC Avatar asked Apr 15 '14 00:04

WBC


People also ask

How do you check Viewset in Django REST framework?

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. EDIT: You'll actually need to specify the required actions. Changed code and comments to reflect this. Show activity on this post.

What is Viewset in Django REST?

Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet . In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.

Should I use APIView or Viewset?

APIView allow us to define functions that match standard HTTP methods like GET, POST, PUT, PATCH, etc. Viewsets allow us to define functions that match to common API object actions like : LIST, CREATE, RETRIEVE, UPDATE, etc.

What is difference between View and Viewset in Django?

While regular views act as handlers for HTTP methods, viewsets give you actions, like create or list . The great thing about viewsets is how they make your code consistent and save you from repetition. Every time you write views that should do more than one thing, a viewset is the thing that you want to go for.


1 Answers

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.

like image 116
WBC Avatar answered Oct 01 '22 03:10

WBC