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)
I needed to get this working with force authentication, and finally got it, here is what my test case looks like:
I'm using this with the django-nose test runner and it seems to be working well. Hope it helps those that have auth enabled on their viewsets.
I think it's your last line. You need to call the CatViewSet as_view(). I would go with:
given that you already defined
view = CatViewSet.as_view()
EDIT:
Can you show your
views.py
? Specifically, what kind ofViewSet
did you use? I'm digging through the DRF code and it looks like you may not have any actions mapped to your ViewSet, which is triggering the error.I found a way to do this without needing to manually create the right viewset and give it an action mapping:
I think I found the correct syntax, but not sure if it is conventional (still new to Django):
So now this passes and I can assign request.user, which allows me to customize the retrieve method under CatViewSet to consider the user.
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:
http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers
In your case you'll want {'get': 'retrieve'} Like so:
EDIT: You'll actually need to specify the required actions. Changed code and comments to reflect this.