Skip to content

Commit 37d4942

Browse files
Raise assertion errors if @api_view decorator is applied incorrectly. Fixes encode#596.
1 parent af3fd09 commit 37d4942

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

rest_framework/decorators.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from rest_framework.views import APIView
2+
import types
23

34

45
def api_view(http_method_names):
@@ -23,6 +24,14 @@ def decorator(func):
2324
# pass
2425
# WrappedAPIView.__doc__ = func.doc <--- Not possible to do this
2526

27+
# api_view applied without (method_names)
28+
assert not(isinstance(http_method_names, types.FunctionType)), \
29+
'@api_view missing list of allowed HTTP methods'
30+
31+
# api_view applied with eg. string instead of list of strings
32+
assert isinstance(http_method_names, (list, tuple)), \
33+
'@api_view expected a list of strings, recieved %s' % type(http_method_names).__name__
34+
2635
allowed_methods = set(http_method_names) | set(('options',))
2736
WrappedAPIView.http_method_names = [method.lower() for method in allowed_methods]
2837

rest_framework/tests/decorators.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,28 @@ def _finalize_response(self, request, response, *args, **kwargs):
2828
response.request = request
2929
return APIView.finalize_response(self, request, response, *args, **kwargs)
3030

31+
def test_api_view_incorrect(self):
32+
"""
33+
If @api_view is not applied correct, we should raise an assertion.
34+
"""
35+
36+
@api_view
37+
def view(request):
38+
return Response()
39+
40+
request = self.factory.get('/')
41+
self.assertRaises(AssertionError, view, request)
42+
43+
def test_api_view_incorrect_arguments(self):
44+
"""
45+
If @api_view is missing arguments, we should raise an assertion.
46+
"""
47+
48+
with self.assertRaises(AssertionError):
49+
@api_view('GET')
50+
def view(request):
51+
return Response()
52+
3153
def test_calling_method(self):
3254

3355
@api_view(['GET'])

0 commit comments

Comments
 (0)