| 1 |
from functools import wraps |
| 2 |
|
| 3 |
import pytest |
| 4 |
from django.db import models |
| 5 |
from django.test import TestCase, override_settings |
| 6 |
from django.urls import include, path |
| 7 |
|
| 8 |
from rest_framework import status |
| 9 |
from rest_framework.decorators import action |
| 10 |
from rest_framework.response import Response |
| 11 |
from rest_framework.routers import SimpleRouter |
| 12 |
from rest_framework.test import APIRequestFactory |
| 13 |
from rest_framework.viewsets import GenericViewSet |
| 14 |
|
| 15 |
factory = APIRequestFactory() |
| 16 |
|
| 17 |
|
| 18 |
class BasicViewSet(GenericViewSet): |
| 19 |
def list(self, request, *args, **kwargs): |
| 20 |
return Response({'ACTION': 'LIST'}) |
| 21 |
|
| 22 |
|
| 23 |
class InstanceViewSet(GenericViewSet): |
| 24 |
|
| 25 |
def dispatch(self, request, *args, **kwargs): |
| 26 |
return self.dummy(request, *args, **kwargs) |
| 27 |
|
| 28 |
def dummy(self, request, *args, **kwargs): |
| 29 |
return Response({'view': self}) |
| 30 |
|
| 31 |
|
| 32 |
class Action(models.Model): |
| 33 |
pass |
| 34 |
|
| 35 |
|
| 36 |
def decorate(fn): |
| 37 |
@wraps(fn) |
| 38 |
def wrapper(self, request, *args, **kwargs): |
| 39 |
return fn(self, request, *args, **kwargs) |
| 40 |
return wrapper |
| 41 |
|
| 42 |
|
| 43 |
class ActionViewSet(GenericViewSet): |
| 44 |
queryset = Action.objects.all() |
| 45 |
|
| 46 |
def list(self, request, *args, **kwargs): |
| 47 |
response = Response() |
| 48 |
response.view = self |
| 49 |
return response |
| 50 |
|
| 51 |
def retrieve(self, request, *args, **kwargs): |
| 52 |
response = Response() |
| 53 |
response.view = self |
| 54 |
return response |
| 55 |
|
| 56 |
@action(detail=False) |
| 57 |
def list_action(self, request, *args, **kwargs): |
| 58 |
response = Response() |
| 59 |
response.view = self |
| 60 |
return response |
| 61 |
|
| 62 |
@action(detail=False, url_name='list-custom') |
| 63 |
def custom_list_action(self, request, *args, **kwargs): |
| 64 |
raise NotImplementedError |
| 65 |
|
| 66 |
@action(detail=True) |
| 67 |
def detail_action(self, request, *args, **kwargs): |
| 68 |
raise NotImplementedError |
| 69 |
|
| 70 |
@action(detail=True, url_name='detail-custom') |
| 71 |
def custom_detail_action(self, request, *args, **kwargs): |
| 72 |
raise NotImplementedError |
| 73 |
|
| 74 |
@action(detail=True, url_path=r'unresolvable/(?P<arg>\w+)', url_name='unresolvable') |
| 75 |
def unresolvable_detail_action(self, request, *args, **kwargs): |
| 76 |
raise NotImplementedError |
| 77 |
|
| 78 |
@action(detail=False) |
| 79 |
@decorate |
| 80 |
def wrapped_list_action(self, request, *args, **kwargs): |
| 81 |
raise NotImplementedError |
| 82 |
|
| 83 |
@action(detail=True) |
| 84 |
@decorate |
| 85 |
def wrapped_detail_action(self, request, *args, **kwargs): |
| 86 |
raise NotImplementedError |
| 87 |
|
| 88 |
|
| 89 |
class ActionNamesViewSet(GenericViewSet): |
| 90 |
|
| 91 |
def retrieve(self, request, *args, **kwargs): |
| 92 |
response = Response() |
| 93 |
response.view = self |
| 94 |
return response |
| 95 |
|
| 96 |
@action(detail=True) |
| 97 |
def unnamed_action(self, request, *args, **kwargs): |
| 98 |
raise NotImplementedError |
| 99 |
|
| 100 |
@action(detail=True, name='Custom Name') |
| 101 |
def named_action(self, request, *args, **kwargs): |
| 102 |
raise NotImplementedError |
| 103 |
|
| 104 |
@action(detail=True, suffix='Custom Suffix') |
| 105 |
def suffixed_action(self, request, *args, **kwargs): |
| 106 |
raise NotImplementedError |
| 107 |
|
| 108 |
|
| 109 |
class ThingWithMapping: |
| 110 |
def __init__(self): |
| 111 |
self.mapping = {} |
| 112 |
|
| 113 |
|
| 114 |
class ActionViewSetWithMapping(ActionViewSet): |
| 115 |
mapper = ThingWithMapping() |
| 116 |
|
| 117 |
|
| 118 |
router = SimpleRouter() |
| 119 |
router.register(r'actions', ActionViewSet) |
| 120 |
router.register(r'actions-alt', ActionViewSet, basename='actions-alt') |
| 121 |
router.register(r'names', ActionNamesViewSet, basename='names') |
| 122 |
router.register(r'mapping', ActionViewSetWithMapping, basename='mapping') |
| 123 |
|
| 124 |
|
| 125 |
urlpatterns = [ |
| 126 |
path('api/', include(router.urls)), |
| 127 |
] |
| 128 |
|
| 129 |
|
| 130 |
class InitializeViewSetsTestCase(TestCase): |
| 131 |
def test_initialize_view_set_with_actions(self): |
| 132 |
request = factory.get('/', '', content_type='application/json') |
| 133 |
my_view = BasicViewSet.as_view(actions={ |
| 134 |
'get': 'list', |
| 135 |
}) |
| 136 |
|
| 137 |
response = my_view(request) |
| 138 |
assert response.status_code == status.HTTP_200_OK |
| 139 |
assert response.data == {'ACTION': 'LIST'} |
| 140 |
|
| 141 |
def test_head_request_against_viewset(self): |
| 142 |
request = factory.head('/', '', content_type='application/json') |
| 143 |
my_view = BasicViewSet.as_view(actions={ |
| 144 |
'get': 'list', |
| 145 |
}) |
| 146 |
|
| 147 |
response = my_view(request) |
| 148 |
assert response.status_code == status.HTTP_200_OK |
| 149 |
|
| 150 |
def test_initialize_view_set_with_empty_actions(self): |
| 151 |
with pytest.raises(TypeError) as excinfo: |
| 152 |
BasicViewSet.as_view() |
| 153 |
|
| 154 |
assert str(excinfo.value) == ( |
| 155 |
"The `actions` argument must be provided " |
| 156 |
"when calling `.as_view()` on a ViewSet. " |
| 157 |
"For example `.as_view({'get': 'list'})`") |
| 158 |
|
| 159 |
def test_initialize_view_set_with_both_name_and_suffix(self): |
| 160 |
with pytest.raises(TypeError) as excinfo: |
| 161 |
BasicViewSet.as_view(name='', suffix='', actions={ |
| 162 |
'get': 'list', |
| 163 |
}) |
| 164 |
|
| 165 |
assert str(excinfo.value) == ( |
| 166 |
"BasicViewSet() received both `name` and `suffix`, " |
| 167 |
"which are mutually exclusive arguments.") |
| 168 |
|
| 169 |
def test_args_kwargs_request_action_map_on_self(self): |
| 170 |
""" |
| 171 |
Test a view only has args, kwargs, request, action_map |
| 172 |
once `as_view` has been called. |
| 173 |
""" |
| 174 |
bare_view = InstanceViewSet() |
| 175 |
view = InstanceViewSet.as_view(actions={ |
| 176 |
'get': 'dummy', |
| 177 |
})(factory.get('/')).data['view'] |
| 178 |
|
| 179 |
for attribute in ('args', 'kwargs', 'request', 'action_map'): |
| 180 |
self.assertNotIn(attribute, dir(bare_view)) |
| 181 |
self.assertIn(attribute, dir(view)) |
| 182 |
|
| 183 |
def test_viewset_action_attr(self): |
| 184 |
view = ActionViewSet.as_view(actions={'get': 'list'}) |
| 185 |
|
| 186 |
get = view(factory.get('/')) |
| 187 |
head = view(factory.head('/')) |
| 188 |
assert get.view.action == 'list' |
| 189 |
assert head.view.action == 'list' |
| 190 |
|
| 191 |
def test_viewset_action_attr_for_extra_action(self): |
| 192 |
view = ActionViewSet.as_view(actions=dict(ActionViewSet.list_action.mapping)) |
| 193 |
|
| 194 |
get = view(factory.get('/')) |
| 195 |
head = view(factory.head('/')) |
| 196 |
assert get.view.action == 'list_action' |
| 197 |
assert head.view.action == 'list_action' |
| 198 |
|
| 199 |
def test_login_required_middleware_compat(self): |
| 200 |
view = ActionViewSet.as_view(actions={'get': 'list'}) |
| 201 |
assert view.login_required is False |
| 202 |
|
| 203 |
|
| 204 |
class GetExtraActionsTests(TestCase): |
| 205 |
|
| 206 |
def test_extra_actions(self): |
| 207 |
view = ActionViewSet() |
| 208 |
actual = [action.__name__ for action in view.get_extra_actions()] |
| 209 |
expected = [ |
| 210 |
'custom_detail_action', |
| 211 |
'custom_list_action', |
| 212 |
'detail_action', |
| 213 |
'list_action', |
| 214 |
'unresolvable_detail_action', |
| 215 |
'wrapped_detail_action', |
| 216 |
'wrapped_list_action', |
| 217 |
] |
| 218 |
|
| 219 |
self.assertEqual(actual, expected) |
| 220 |
|
| 221 |
def test_should_only_return_decorated_methods(self): |
| 222 |
view = ActionViewSetWithMapping() |
| 223 |
actual = [action.__name__ for action in view.get_extra_actions()] |
| 224 |
expected = [ |
| 225 |
'custom_detail_action', |
| 226 |
'custom_list_action', |
| 227 |
'detail_action', |
| 228 |
'list_action', |
| 229 |
'unresolvable_detail_action', |
| 230 |
'wrapped_detail_action', |
| 231 |
'wrapped_list_action', |
| 232 |
] |
| 233 |
self.assertEqual(actual, expected) |
| 234 |
|
| 235 |
def test_attr_name_check(self): |
| 236 |
def decorate(fn): |
| 237 |
def wrapper(self, request, *args, **kwargs): |
| 238 |
return fn(self, request, *args, **kwargs) |
| 239 |
return wrapper |
| 240 |
|
| 241 |
class ActionViewSet(GenericViewSet): |
| 242 |
queryset = Action.objects.all() |
| 243 |
|
| 244 |
@action(detail=False) |
| 245 |
@decorate |
| 246 |
def wrapped_list_action(self, request, *args, **kwargs): |
| 247 |
raise NotImplementedError |
| 248 |
|
| 249 |
view = ActionViewSet() |
| 250 |
with pytest.raises(AssertionError) as excinfo: |
| 251 |
view.get_extra_actions() |
| 252 |
|
| 253 |
assert str(excinfo.value) == ( |
| 254 |
'Expected function (`wrapper`) to match its attribute name ' |
| 255 |
'(`wrapped_list_action`). If using a decorator, ensure the inner ' |
| 256 |
'function is decorated with `functools.wraps`, or that ' |
| 257 |
'`wrapper.__name__` is otherwise set to `wrapped_list_action`.') |
| 258 |
|
| 259 |
|
| 260 |
@override_settings(ROOT_URLCONF='tests.test_viewsets') |
| 261 |
class GetExtraActionUrlMapTests(TestCase): |
| 262 |
|
| 263 |
def test_list_view(self): |
| 264 |
response = self.client.get('/api/actions/') |
| 265 |
view = response.view |
| 266 |
|
| 267 |
expected = { |
| 268 |
'Custom list action': 'http://testserver/api/actions/custom_list_action/', |
| 269 |
'List action': 'http://testserver/api/actions/list_action/', |
| 270 |
'Wrapped list action': 'http://testserver/api/actions/wrapped_list_action/', |
| 271 |
} |
| 272 |
|
| 273 |
self.assertEqual(view.get_extra_action_url_map(), expected) |
| 274 |
|
| 275 |
def test_detail_view(self): |
| 276 |
response = self.client.get('/api/actions/1/') |
| 277 |
view = response.view |
| 278 |
|
| 279 |
expected = { |
| 280 |
'Custom detail action': 'http://testserver/api/actions/1/custom_detail_action/', |
| 281 |
'Detail action': 'http://testserver/api/actions/1/detail_action/', |
| 282 |
'Wrapped detail action': 'http://testserver/api/actions/1/wrapped_detail_action/', |
| 283 |
# "Unresolvable detail action" excluded, since it's not resolvable |
| 284 |
} |
| 285 |
|
| 286 |
self.assertEqual(view.get_extra_action_url_map(), expected) |
| 287 |
|
| 288 |
def test_uninitialized_view(self): |
| 289 |
self.assertEqual(ActionViewSet().get_extra_action_url_map(), {}) |
| 290 |
|
| 291 |
def test_action_names(self): |
| 292 |
# Action 'name' and 'suffix' kwargs should be respected |
| 293 |
response = self.client.get('/api/names/1/') |
| 294 |
view = response.view |
| 295 |
|
| 296 |
expected = { |
| 297 |
'Custom Name': 'http://testserver/api/names/1/named_action/', |
| 298 |
'Action Names Custom Suffix': 'http://testserver/api/names/1/suffixed_action/', |
| 299 |
'Unnamed action': 'http://testserver/api/names/1/unnamed_action/', |
| 300 |
} |
| 301 |
|
| 302 |
self.assertEqual(view.get_extra_action_url_map(), expected) |
| 303 |
|
| 304 |
|
| 305 |
@override_settings(ROOT_URLCONF='tests.test_viewsets') |
| 306 |
class ReverseActionTests(TestCase): |
| 307 |
def test_default_basename(self): |
| 308 |
view = ActionViewSet() |
| 309 |
view.basename = router.get_default_basename(ActionViewSet) |
| 310 |
view.request = None |
| 311 |
|
| 312 |
assert view.reverse_action('list') == '/api/actions/' |
| 313 |
assert view.reverse_action('list-action') == '/api/actions/list_action/' |
| 314 |
assert view.reverse_action('list-custom') == '/api/actions/custom_list_action/' |
| 315 |
|
| 316 |
assert view.reverse_action('detail', args=['1']) == '/api/actions/1/' |
| 317 |
assert view.reverse_action('detail-action', args=['1']) == '/api/actions/1/detail_action/' |
| 318 |
assert view.reverse_action('detail-custom', args=['1']) == '/api/actions/1/custom_detail_action/' |
| 319 |
|
| 320 |
def test_custom_basename(self): |
| 321 |
view = ActionViewSet() |
| 322 |
view.basename = 'actions-alt' |
| 323 |
view.request = None |
| 324 |
|
| 325 |
assert view.reverse_action('list') == '/api/actions-alt/' |
| 326 |
assert view.reverse_action('list-action') == '/api/actions-alt/list_action/' |
| 327 |
assert view.reverse_action('list-custom') == '/api/actions-alt/custom_list_action/' |
| 328 |
|
| 329 |
assert view.reverse_action('detail', args=['1']) == '/api/actions-alt/1/' |
| 330 |
assert view.reverse_action('detail-action', args=['1']) == '/api/actions-alt/1/detail_action/' |
| 331 |
assert view.reverse_action('detail-custom', args=['1']) == '/api/actions-alt/1/custom_detail_action/' |
| 332 |
|
| 333 |
def test_request_passing(self): |
| 334 |
view = ActionViewSet() |
| 335 |
view.basename = router.get_default_basename(ActionViewSet) |
| 336 |
view.request = factory.get('/') |
| 337 |
|
| 338 |
# Passing the view's request object should result in an absolute URL. |
| 339 |
assert view.reverse_action('list') == 'http://testserver/api/actions/' |
| 340 |
|
| 341 |
# Users should be able to explicitly not pass the view's request. |
| 342 |
assert view.reverse_action('list', request=None) == '/api/actions/' |