Skip to content

Commit 53f5276

Browse files
committed
Not allow to pass an empty actions to viewset.as_view(). Refs issue #2171
1 parent 81870b6 commit 53f5276

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

rest_framework/viewsets.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@ def as_view(cls, actions=None, **initkwargs):
4848
# eg. 'List' or 'Instance'.
4949
cls.suffix = None
5050

51+
# actions must not be empty
52+
if not actions:
53+
raise TypeError("The `actions` argument must be provided when "
54+
"calling `.as_view()` on a ViewSet. For example "
55+
"`.as_view({'get': 'list'})`")
56+
5157
# sanitize keyword arguments
5258
for key in initkwargs:
5359
if key in cls.http_method_names:

tests/test_viewsets.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from django.test import TestCase
2+
from rest_framework import status
3+
from rest_framework.response import Response
4+
from rest_framework.test import APIRequestFactory
5+
from rest_framework.viewsets import GenericViewSet
6+
7+
8+
factory = APIRequestFactory()
9+
10+
11+
class BasicViewSet(GenericViewSet):
12+
def list(self, request, *args, **kwargs):
13+
return Response({'ACTION': 'LIST'})
14+
15+
16+
class InitializeViewSetsTestCase(TestCase):
17+
def test_initialize_view_set_with_actions(self):
18+
request = factory.get('/', '', content_type='application/json')
19+
my_view = BasicViewSet.as_view(actions={
20+
'get': 'list',
21+
})
22+
23+
response = my_view(request)
24+
self.assertEqual(response.status_code, status.HTTP_200_OK)
25+
self.assertEqual(response.data, {'ACTION': 'LIST'})
26+
27+
def test_initialize_view_set_with_empty_actions(self):
28+
try:
29+
BasicViewSet.as_view()
30+
except TypeError as e:
31+
self.assertEqual(str(e), "The `actions` argument must be provided "
32+
"when calling `.as_view()` on a ViewSet. "
33+
"For example `.as_view({'get': 'list'})`")
34+
else:
35+
self.fail("actions must not be empty.")

0 commit comments

Comments
 (0)