| 1 |
from collections import namedtuple |
| 2 |
|
| 3 |
import pytest |
| 4 |
from django.core.exceptions import ImproperlyConfigured |
| 5 |
from django.db import models |
| 6 |
from django.test import TestCase, override_settings |
| 7 |
from django.urls import include, path, resolve, reverse |
| 8 |
|
| 9 |
from rest_framework import permissions, serializers, viewsets |
| 10 |
from rest_framework.decorators import action |
| 11 |
from rest_framework.response import Response |
| 12 |
from rest_framework.routers import DefaultRouter, SimpleRouter |
| 13 |
from rest_framework.test import ( |
| 14 |
APIClient, APIRequestFactory, URLPatternsTestCase |
| 15 |
) |
| 16 |
from rest_framework.utils import json |
| 17 |
|
| 18 |
factory = APIRequestFactory() |
| 19 |
|
| 20 |
|
| 21 |
class RouterTestModel(models.Model): |
| 22 |
uuid = models.CharField(max_length=20) |
| 23 |
text = models.CharField(max_length=200) |
| 24 |
|
| 25 |
|
| 26 |
class BasenameTestModel(models.Model): |
| 27 |
uuid = models.CharField(max_length=20) |
| 28 |
text = models.CharField(max_length=200) |
| 29 |
|
| 30 |
|
| 31 |
class NoteSerializer(serializers.HyperlinkedModelSerializer): |
| 32 |
url = serializers.HyperlinkedIdentityField(view_name='routertestmodel-detail', lookup_field='uuid') |
| 33 |
|
| 34 |
class Meta: |
| 35 |
model = RouterTestModel |
| 36 |
fields = ('url', 'uuid', 'text') |
| 37 |
|
| 38 |
|
| 39 |
class NoteViewSet(viewsets.ModelViewSet): |
| 40 |
queryset = RouterTestModel.objects.all() |
| 41 |
serializer_class = NoteSerializer |
| 42 |
lookup_field = 'uuid' |
| 43 |
|
| 44 |
|
| 45 |
class KWargedNoteViewSet(viewsets.ModelViewSet): |
| 46 |
queryset = RouterTestModel.objects.all() |
| 47 |
serializer_class = NoteSerializer |
| 48 |
lookup_field = 'text__contains' |
| 49 |
lookup_url_kwarg = 'text' |
| 50 |
|
| 51 |
|
| 52 |
class BasenameViewSet(viewsets.ModelViewSet): |
| 53 |
queryset = BasenameTestModel.objects.all() |
| 54 |
serializer_class = None |
| 55 |
|
| 56 |
|
| 57 |
class MockViewSet(viewsets.ModelViewSet): |
| 58 |
queryset = None |
| 59 |
serializer_class = None |
| 60 |
|
| 61 |
|
| 62 |
class EmptyPrefixSerializer(serializers.HyperlinkedModelSerializer): |
| 63 |
class Meta: |
| 64 |
model = RouterTestModel |
| 65 |
fields = ('uuid', 'text') |
| 66 |
|
| 67 |
|
| 68 |
class EmptyPrefixViewSet(viewsets.ModelViewSet): |
| 69 |
queryset = [RouterTestModel(id=1, uuid='111', text='First'), RouterTestModel(id=2, uuid='222', text='Second')] |
| 70 |
serializer_class = EmptyPrefixSerializer |
| 71 |
|
| 72 |
def get_object(self, *args, **kwargs): |
| 73 |
index = int(self.kwargs['pk']) - 1 |
| 74 |
return self.queryset[index] |
| 75 |
|
| 76 |
|
| 77 |
class RegexUrlPathViewSet(viewsets.ViewSet): |
| 78 |
@action(detail=False, url_path='list/(?P<kwarg>[0-9]{4})') |
| 79 |
def regex_url_path_list(self, request, *args, **kwargs): |
| 80 |
kwarg = self.kwargs.get('kwarg', '') |
| 81 |
return Response({'kwarg': kwarg}) |
| 82 |
|
| 83 |
@action(detail=True, url_path='detail/(?P<kwarg>[0-9]{4})') |
| 84 |
def regex_url_path_detail(self, request, *args, **kwargs): |
| 85 |
pk = self.kwargs.get('pk', '') |
| 86 |
kwarg = self.kwargs.get('kwarg', '') |
| 87 |
return Response({'pk': pk, 'kwarg': kwarg}) |
| 88 |
|
| 89 |
|
| 90 |
class UrlPathViewSet(viewsets.ViewSet): |
| 91 |
@action(detail=False, url_path='list/<int:kwarg>') |
| 92 |
def url_path_list(self, request, *args, **kwargs): |
| 93 |
kwarg = self.kwargs.get('kwarg', '') |
| 94 |
return Response({'kwarg': kwarg}) |
| 95 |
|
| 96 |
@action(detail=True, url_path='detail/<int:kwarg>') |
| 97 |
def url_path_detail(self, request, *args, **kwargs): |
| 98 |
pk = self.kwargs.get('pk', '') |
| 99 |
kwarg = self.kwargs.get('kwarg', '') |
| 100 |
return Response({'pk': pk, 'kwarg': kwarg}) |
| 101 |
|
| 102 |
@action(detail=True, url_path='detail/<int:kwarg>/detail/<int:param>') |
| 103 |
def url_path_detail_multiple_params(self, request, *args, **kwargs): |
| 104 |
pk = self.kwargs.get('pk', '') |
| 105 |
kwarg = self.kwargs.get('kwarg', '') |
| 106 |
param = self.kwargs.get('param', '') |
| 107 |
return Response({'pk': pk, 'kwarg': kwarg, 'param': param}) |
| 108 |
|
| 109 |
|
| 110 |
notes_router = SimpleRouter() |
| 111 |
notes_router.register(r'notes', NoteViewSet) |
| 112 |
|
| 113 |
notes_path_router = SimpleRouter(use_regex_path=False) |
| 114 |
notes_path_router.register('notes', NoteViewSet) |
| 115 |
|
| 116 |
notes_path_default_router = DefaultRouter(use_regex_path=False) |
| 117 |
notes_path_default_router.register('notes', NoteViewSet) |
| 118 |
|
| 119 |
kwarged_notes_router = SimpleRouter() |
| 120 |
kwarged_notes_router.register(r'notes', KWargedNoteViewSet) |
| 121 |
|
| 122 |
namespaced_router = DefaultRouter() |
| 123 |
namespaced_router.register(r'example', MockViewSet, basename='example') |
| 124 |
|
| 125 |
empty_prefix_router = SimpleRouter() |
| 126 |
empty_prefix_router.register(r'', EmptyPrefixViewSet, basename='empty_prefix') |
| 127 |
|
| 128 |
regex_url_path_router = SimpleRouter() |
| 129 |
regex_url_path_router.register(r'', RegexUrlPathViewSet, basename='regex') |
| 130 |
|
| 131 |
url_path_router = SimpleRouter(use_regex_path=False) |
| 132 |
url_path_router.register('', UrlPathViewSet, basename='path') |
| 133 |
|
| 134 |
|
| 135 |
class BasicViewSet(viewsets.ViewSet): |
| 136 |
def list(self, request, *args, **kwargs): |
| 137 |
return Response({'method': 'list'}) |
| 138 |
|
| 139 |
@action(methods=['post'], detail=True) |
| 140 |
def action1(self, request, *args, **kwargs): |
| 141 |
return Response({'method': 'action1'}) |
| 142 |
|
| 143 |
@action(methods=['post', 'delete'], detail=True) |
| 144 |
def action2(self, request, *args, **kwargs): |
| 145 |
return Response({'method': 'action2'}) |
| 146 |
|
| 147 |
@action(methods=['post'], detail=True) |
| 148 |
def action3(self, request, pk, *args, **kwargs): |
| 149 |
return Response({'post': pk}) |
| 150 |
|
| 151 |
@action3.mapping.delete |
| 152 |
def action3_delete(self, request, pk, *args, **kwargs): |
| 153 |
return Response({'delete': pk}) |
| 154 |
|
| 155 |
|
| 156 |
class TestSimpleRouter(URLPatternsTestCase, TestCase): |
| 157 |
router = SimpleRouter() |
| 158 |
router.register('basics', BasicViewSet, basename='basic') |
| 159 |
|
| 160 |
urlpatterns = [ |
| 161 |
path('api/', include(router.urls)), |
| 162 |
] |
| 163 |
|
| 164 |
def setUp(self): |
| 165 |
self.router = SimpleRouter() |
| 166 |
|
| 167 |
def test_action_routes(self): |
| 168 |
# Get action routes (first two are list/detail) |
| 169 |
routes = self.router.get_routes(BasicViewSet)[2:] |
| 170 |
|
| 171 |
assert routes[0].url == '^{prefix}/{lookup}/action1{trailing_slash}$' |
| 172 |
assert routes[0].mapping == { |
| 173 |
'post': 'action1', |
| 174 |
} |
| 175 |
|
| 176 |
assert routes[1].url == '^{prefix}/{lookup}/action2{trailing_slash}$' |
| 177 |
assert routes[1].mapping == { |
| 178 |
'post': 'action2', |
| 179 |
'delete': 'action2', |
| 180 |
} |
| 181 |
|
| 182 |
assert routes[2].url == '^{prefix}/{lookup}/action3{trailing_slash}$' |
| 183 |
assert routes[2].mapping == { |
| 184 |
'post': 'action3', |
| 185 |
'delete': 'action3_delete', |
| 186 |
} |
| 187 |
|
| 188 |
def test_multiple_action_handlers(self): |
| 189 |
# Standard action |
| 190 |
response = self.client.post(reverse('basic-action3', args=[1])) |
| 191 |
assert response.data == {'post': '1'} |
| 192 |
|
| 193 |
# Additional handler registered with MethodMapper |
| 194 |
response = self.client.delete(reverse('basic-action3', args=[1])) |
| 195 |
assert response.data == {'delete': '1'} |
| 196 |
|
| 197 |
def test_register_after_accessing_urls(self): |
| 198 |
self.router.register(r'notes', NoteViewSet) |
| 199 |
assert len(self.router.urls) == 2 # list and detail |
| 200 |
self.router.register(r'notes_bis', NoteViewSet, basename='notes_bis') |
| 201 |
assert len(self.router.urls) == 4 |
| 202 |
|
| 203 |
|
| 204 |
class TestRootView(URLPatternsTestCase, TestCase): |
| 205 |
urlpatterns = [ |
| 206 |
path('non-namespaced/', include(namespaced_router.urls)), |
| 207 |
path('namespaced/', include((namespaced_router.urls, 'namespaced'), namespace='namespaced')), |
| 208 |
] |
| 209 |
|
| 210 |
def test_retrieve_namespaced_root(self): |
| 211 |
response = self.client.get('/namespaced/') |
| 212 |
assert response.data == {"example": "http://testserver/namespaced/example/"} |
| 213 |
|
| 214 |
def test_retrieve_non_namespaced_root(self): |
| 215 |
response = self.client.get('/non-namespaced/') |
| 216 |
assert response.data == {"example": "http://testserver/non-namespaced/example/"} |
| 217 |
|
| 218 |
|
| 219 |
class TestCustomLookupFields(URLPatternsTestCase, TestCase): |
| 220 |
""" |
| 221 |
Ensure that custom lookup fields are correctly routed. |
| 222 |
""" |
| 223 |
urlpatterns = [ |
| 224 |
path('example/', include(notes_router.urls)), |
| 225 |
path('example2/', include(kwarged_notes_router.urls)), |
| 226 |
] |
| 227 |
|
| 228 |
def setUp(self): |
| 229 |
RouterTestModel.objects.create(uuid='123', text='foo bar') |
| 230 |
RouterTestModel.objects.create(uuid='a b', text='baz qux') |
| 231 |
|
| 232 |
def test_custom_lookup_field_route(self): |
| 233 |
detail_route = notes_router.urls[-1] |
| 234 |
assert '<uuid>' in detail_route.pattern.regex.pattern |
| 235 |
|
| 236 |
def test_retrieve_lookup_field_list_view(self): |
| 237 |
response = self.client.get('/example/notes/') |
| 238 |
assert response.data == [ |
| 239 |
{"url": "http://testserver/example/notes/123/", "uuid": "123", "text": "foo bar"}, |
| 240 |
{"url": "http://testserver/example/notes/a%20b/", "uuid": "a b", "text": "baz qux"}, |
| 241 |
] |
| 242 |
|
| 243 |
def test_retrieve_lookup_field_detail_view(self): |
| 244 |
response = self.client.get('/example/notes/123/') |
| 245 |
assert response.data == {"url": "http://testserver/example/notes/123/", "uuid": "123", "text": "foo bar"} |
| 246 |
|
| 247 |
def test_retrieve_lookup_field_url_encoded_detail_view_(self): |
| 248 |
response = self.client.get('/example/notes/a%20b/') |
| 249 |
assert response.data == {"url": "http://testserver/example/notes/a%20b/", "uuid": "a b", "text": "baz qux"} |
| 250 |
|
| 251 |
|
| 252 |
class TestLookupValueRegex(TestCase): |
| 253 |
""" |
| 254 |
Ensure the router honors lookup_value_regex when applied |
| 255 |
to the viewset. |
| 256 |
""" |
| 257 |
def setUp(self): |
| 258 |
class NoteViewSet(viewsets.ModelViewSet): |
| 259 |
queryset = RouterTestModel.objects.all() |
| 260 |
lookup_field = 'uuid' |
| 261 |
lookup_value_regex = '[0-9a-f]{32}' |
| 262 |
|
| 263 |
self.router = SimpleRouter() |
| 264 |
self.router.register(r'notes', NoteViewSet) |
| 265 |
self.urls = self.router.urls |
| 266 |
|
| 267 |
def test_urls_limited_by_lookup_value_regex(self): |
| 268 |
expected = ['^notes/$', '^notes/(?P<uuid>[0-9a-f]{32})/$'] |
| 269 |
for idx in range(len(expected)): |
| 270 |
assert expected[idx] == self.urls[idx].pattern.regex.pattern |
| 271 |
|
| 272 |
|
| 273 |
@override_settings(ROOT_URLCONF='tests.test_routers') |
| 274 |
class TestLookupUrlKwargs(URLPatternsTestCase, TestCase): |
| 275 |
""" |
| 276 |
Ensure the router honors lookup_url_kwarg. |
| 277 |
|
| 278 |
Setup a deep lookup_field, but map it to a simple URL kwarg. |
| 279 |
""" |
| 280 |
urlpatterns = [ |
| 281 |
path('example/', include(notes_router.urls)), |
| 282 |
path('example2/', include(kwarged_notes_router.urls)), |
| 283 |
] |
| 284 |
|
| 285 |
def setUp(self): |
| 286 |
RouterTestModel.objects.create(uuid='123', text='foo bar') |
| 287 |
|
| 288 |
def test_custom_lookup_url_kwarg_route(self): |
| 289 |
detail_route = kwarged_notes_router.urls[-1] |
| 290 |
assert '^notes/(?P<text>' in detail_route.pattern.regex.pattern |
| 291 |
|
| 292 |
def test_retrieve_lookup_url_kwarg_detail_view(self): |
| 293 |
response = self.client.get('/example2/notes/fo/') |
| 294 |
assert response.data == {"url": "http://testserver/example/notes/123/", "uuid": "123", "text": "foo bar"} |
| 295 |
|
| 296 |
def test_retrieve_lookup_url_encoded_kwarg_detail_view(self): |
| 297 |
response = self.client.get('/example2/notes/foo%20bar/') |
| 298 |
assert response.data == {"url": "http://testserver/example/notes/123/", "uuid": "123", "text": "foo bar"} |
| 299 |
|
| 300 |
|
| 301 |
class TestTrailingSlashIncluded(TestCase): |
| 302 |
def setUp(self): |
| 303 |
class NoteViewSet(viewsets.ModelViewSet): |
| 304 |
queryset = RouterTestModel.objects.all() |
| 305 |
|
| 306 |
self.router = SimpleRouter() |
| 307 |
self.router.register(r'notes', NoteViewSet) |
| 308 |
self.urls = self.router.urls |
| 309 |
|
| 310 |
def test_urls_have_trailing_slash_by_default(self): |
| 311 |
expected = ['^notes/$', '^notes/(?P<pk>[^/.]+)/$'] |
| 312 |
for idx in range(len(expected)): |
| 313 |
assert expected[idx] == self.urls[idx].pattern.regex.pattern |
| 314 |
|
| 315 |
|
| 316 |
class TestTrailingSlashRemoved(TestCase): |
| 317 |
def setUp(self): |
| 318 |
class NoteViewSet(viewsets.ModelViewSet): |
| 319 |
queryset = RouterTestModel.objects.all() |
| 320 |
|
| 321 |
self.router = SimpleRouter(trailing_slash=False) |
| 322 |
self.router.register(r'notes', NoteViewSet) |
| 323 |
self.urls = self.router.urls |
| 324 |
|
| 325 |
def test_urls_can_have_trailing_slash_removed(self): |
| 326 |
expected = ['^notes$', '^notes/(?P<pk>[^/.]+)$'] |
| 327 |
for idx in range(len(expected)): |
| 328 |
assert expected[idx] == self.urls[idx].pattern.regex.pattern |
| 329 |
|
| 330 |
|
| 331 |
class TestNameableRoot(TestCase): |
| 332 |
def setUp(self): |
| 333 |
class NoteViewSet(viewsets.ModelViewSet): |
| 334 |
queryset = RouterTestModel.objects.all() |
| 335 |
|
| 336 |
self.router = DefaultRouter() |
| 337 |
self.router.root_view_name = 'nameable-root' |
| 338 |
self.router.register(r'notes', NoteViewSet) |
| 339 |
self.urls = self.router.urls |
| 340 |
|
| 341 |
def test_router_has_custom_name(self): |
| 342 |
expected = 'nameable-root' |
| 343 |
assert expected == self.urls[-1].name |
| 344 |
|
| 345 |
|
| 346 |
class TestActionKeywordArgs(TestCase): |
| 347 |
""" |
| 348 |
Ensure keyword arguments passed in the `@action` decorator |
| 349 |
are properly handled. Refs #940. |
| 350 |
""" |
| 351 |
|
| 352 |
def setUp(self): |
| 353 |
class TestViewSet(viewsets.ModelViewSet): |
| 354 |
permission_classes = [] |
| 355 |
|
| 356 |
@action(methods=['post'], detail=True, permission_classes=[permissions.AllowAny]) |
| 357 |
def custom(self, request, *args, **kwargs): |
| 358 |
return Response({ |
| 359 |
'permission_classes': self.permission_classes |
| 360 |
}) |
| 361 |
|
| 362 |
self.router = SimpleRouter() |
| 363 |
self.router.register(r'test', TestViewSet, basename='test') |
| 364 |
self.view = self.router.urls[-1].callback |
| 365 |
|
| 366 |
def test_action_kwargs(self): |
| 367 |
request = factory.post('/test/0/custom/') |
| 368 |
response = self.view(request) |
| 369 |
assert response.data == {'permission_classes': [permissions.AllowAny]} |
| 370 |
|
| 371 |
|
| 372 |
class TestActionAppliedToExistingRoute(TestCase): |
| 373 |
""" |
| 374 |
Ensure `@action` decorator raises an except when applied |
| 375 |
to an existing route |
| 376 |
""" |
| 377 |
|
| 378 |
def test_exception_raised_when_action_applied_to_existing_route(self): |
| 379 |
class TestViewSet(viewsets.ModelViewSet): |
| 380 |
|
| 381 |
@action(methods=['post'], detail=True) |
| 382 |
def retrieve(self, request, *args, **kwargs): |
| 383 |
return Response({ |
| 384 |
'hello': 'world' |
| 385 |
}) |
| 386 |
|
| 387 |
self.router = SimpleRouter() |
| 388 |
self.router.register(r'test', TestViewSet, basename='test') |
| 389 |
|
| 390 |
with pytest.raises(ImproperlyConfigured): |
| 391 |
self.router.urls |
| 392 |
|
| 393 |
|
| 394 |
class DynamicListAndDetailViewSet(viewsets.ViewSet): |
| 395 |
def list(self, request, *args, **kwargs): |
| 396 |
return Response({'method': 'list'}) |
| 397 |
|
| 398 |
@action(methods=['post'], detail=False) |
| 399 |
def list_route_post(self, request, *args, **kwargs): |
| 400 |
return Response({'method': 'action1'}) |
| 401 |
|
| 402 |
@action(methods=['post'], detail=True) |
| 403 |
def detail_route_post(self, request, *args, **kwargs): |
| 404 |
return Response({'method': 'action2'}) |
| 405 |
|
| 406 |
@action(detail=False) |
| 407 |
def list_route_get(self, request, *args, **kwargs): |
| 408 |
return Response({'method': 'link1'}) |
| 409 |
|
| 410 |
@action(detail=True) |
| 411 |
def detail_route_get(self, request, *args, **kwargs): |
| 412 |
return Response({'method': 'link2'}) |
| 413 |
|
| 414 |
@action(detail=False, url_path="list_custom-route") |
| 415 |
def list_custom_route_get(self, request, *args, **kwargs): |
| 416 |
return Response({'method': 'link1'}) |
| 417 |
|
| 418 |
@action(detail=True, url_path="detail_custom-route") |
| 419 |
def detail_custom_route_get(self, request, *args, **kwargs): |
| 420 |
return Response({'method': 'link2'}) |
| 421 |
|
| 422 |
|
| 423 |
class SubDynamicListAndDetailViewSet(DynamicListAndDetailViewSet): |
| 424 |
pass |
| 425 |
|
| 426 |
|
| 427 |
class TestDynamicListAndDetailRouter(TestCase): |
| 428 |
def setUp(self): |
| 429 |
self.router = SimpleRouter() |
| 430 |
|
| 431 |
def _test_list_and_detail_route_decorators(self, viewset): |
| 432 |
routes = self.router.get_routes(viewset) |
| 433 |
decorator_routes = [r for r in routes if not (r.name.endswith('-list') or r.name.endswith('-detail'))] |
| 434 |
|
| 435 |
MethodNamesMap = namedtuple('MethodNamesMap', 'method_name url_path') |
| 436 |
# Make sure all these endpoints exist and none have been clobbered |
| 437 |
for i, endpoint in enumerate([MethodNamesMap('list_custom_route_get', 'list_custom-route'), |
| 438 |
MethodNamesMap('list_route_get', 'list_route_get'), |
| 439 |
MethodNamesMap('list_route_post', 'list_route_post'), |
| 440 |
MethodNamesMap('detail_custom_route_get', 'detail_custom-route'), |
| 441 |
MethodNamesMap('detail_route_get', 'detail_route_get'), |
| 442 |
MethodNamesMap('detail_route_post', 'detail_route_post') |
| 443 |
]): |
| 444 |
route = decorator_routes[i] |
| 445 |
# check url listing |
| 446 |
method_name = endpoint.method_name |
| 447 |
url_path = endpoint.url_path |
| 448 |
|
| 449 |
if method_name.startswith('list_'): |
| 450 |
assert route.url == f'^{{prefix}}/{url_path}{{trailing_slash}}$' |
| 451 |
else: |
| 452 |
assert route.url == f'^{{prefix}}/{{lookup}}/{url_path}{{trailing_slash}}$' |
| 453 |
# check method to function mapping |
| 454 |
if method_name.endswith('_post'): |
| 455 |
method_map = 'post' |
| 456 |
else: |
| 457 |
method_map = 'get' |
| 458 |
assert route.mapping[method_map] == method_name |
| 459 |
|
| 460 |
def test_list_and_detail_route_decorators(self): |
| 461 |
self._test_list_and_detail_route_decorators(DynamicListAndDetailViewSet) |
| 462 |
|
| 463 |
def test_inherited_list_and_detail_route_decorators(self): |
| 464 |
self._test_list_and_detail_route_decorators(SubDynamicListAndDetailViewSet) |
| 465 |
|
| 466 |
|
| 467 |
class TestEmptyPrefix(URLPatternsTestCase, TestCase): |
| 468 |
urlpatterns = [ |
| 469 |
path('empty-prefix/', include(empty_prefix_router.urls)), |
| 470 |
] |
| 471 |
|
| 472 |
def test_empty_prefix_list(self): |
| 473 |
response = self.client.get('/empty-prefix/') |
| 474 |
assert response.status_code == 200 |
| 475 |
assert json.loads(response.content.decode()) == [{'uuid': '111', 'text': 'First'}, |
| 476 |
{'uuid': '222', 'text': 'Second'}] |
| 477 |
|
| 478 |
def test_empty_prefix_detail(self): |
| 479 |
response = self.client.get('/empty-prefix/1/') |
| 480 |
assert response.status_code == 200 |
| 481 |
assert json.loads(response.content.decode()) == {'uuid': '111', 'text': 'First'} |
| 482 |
|
| 483 |
|
| 484 |
class TestRegexUrlPath(URLPatternsTestCase, TestCase): |
| 485 |
urlpatterns = [ |
| 486 |
path('regex/', include(regex_url_path_router.urls)), |
| 487 |
] |
| 488 |
|
| 489 |
def test_regex_url_path_list(self): |
| 490 |
kwarg = '1234' |
| 491 |
response = self.client.get(f'/regex/list/{kwarg}/') |
| 492 |
assert response.status_code == 200 |
| 493 |
assert json.loads(response.content.decode()) == {'kwarg': kwarg} |
| 494 |
|
| 495 |
def test_regex_url_path_detail(self): |
| 496 |
pk = '1' |
| 497 |
kwarg = '1234' |
| 498 |
response = self.client.get(f'/regex/{pk}/detail/{kwarg}/') |
| 499 |
assert response.status_code == 200 |
| 500 |
assert json.loads(response.content.decode()) == {'pk': pk, 'kwarg': kwarg} |
| 501 |
|
| 502 |
|
| 503 |
class TestUrlPath(URLPatternsTestCase, TestCase): |
| 504 |
client_class = APIClient |
| 505 |
urlpatterns = [ |
| 506 |
path('path/', include(url_path_router.urls)), |
| 507 |
path('default/', include(notes_path_default_router.urls)), |
| 508 |
path('example/', include(notes_path_router.urls)), |
| 509 |
] |
| 510 |
|
| 511 |
def setUp(self): |
| 512 |
RouterTestModel.objects.create(uuid='123', text='foo bar') |
| 513 |
RouterTestModel.objects.create(uuid='a b', text='baz qux') |
| 514 |
|
| 515 |
def test_create(self): |
| 516 |
new_note = { |
| 517 |
'uuid': 'foo', |
| 518 |
'text': 'example' |
| 519 |
} |
| 520 |
response = self.client.post('/example/notes/', data=new_note) |
| 521 |
assert response.status_code == 201 |
| 522 |
assert response['location'] == 'http://testserver/example/notes/foo/' |
| 523 |
assert response.data == {"url": "http://testserver/example/notes/foo/", "uuid": "foo", "text": "example"} |
| 524 |
assert RouterTestModel.objects.filter(uuid='foo').exists() |
| 525 |
|
| 526 |
def test_retrieve(self): |
| 527 |
for url in ('/example/notes/123/', '/default/notes/123/'): |
| 528 |
with self.subTest(url=url): |
| 529 |
response = self.client.get(url) |
| 530 |
assert response.status_code == 200 |
| 531 |
# only gets example path since was the last to be registered |
| 532 |
assert response.data == {"url": "http://testserver/example/notes/123/", "uuid": "123", "text": "foo bar"} |
| 533 |
|
| 534 |
def test_list(self): |
| 535 |
for url in ('/example/notes/', '/default/notes/'): |
| 536 |
with self.subTest(url=url): |
| 537 |
response = self.client.get(url) |
| 538 |
assert response.status_code == 200 |
| 539 |
# only gets example path since was the last to be registered |
| 540 |
assert response.data == [ |
| 541 |
{"url": "http://testserver/example/notes/123/", "uuid": "123", "text": "foo bar"}, |
| 542 |
{"url": "http://testserver/example/notes/a%20b/", "uuid": "a b", "text": "baz qux"}, |
| 543 |
] |
| 544 |
|
| 545 |
def test_update(self): |
| 546 |
updated_note = { |
| 547 |
'text': 'foo bar example' |
| 548 |
} |
| 549 |
response = self.client.patch('/example/notes/123/', data=updated_note) |
| 550 |
assert response.status_code == 200 |
| 551 |
assert response.data == {"url": "http://testserver/example/notes/123/", "uuid": "123", "text": "foo bar example"} |
| 552 |
|
| 553 |
def test_delete(self): |
| 554 |
response = self.client.delete('/example/notes/123/') |
| 555 |
assert response.status_code == 204 |
| 556 |
assert not RouterTestModel.objects.filter(uuid='123').exists() |
| 557 |
|
| 558 |
def test_list_extra_action(self): |
| 559 |
kwarg = 1234 |
| 560 |
response = self.client.get(f'/path/list/{kwarg}/') |
| 561 |
assert response.status_code == 200 |
| 562 |
assert json.loads(response.content.decode()) == {'kwarg': kwarg} |
| 563 |
|
| 564 |
def test_detail_extra_action(self): |
| 565 |
pk = '1' |
| 566 |
kwarg = 1234 |
| 567 |
response = self.client.get(f'/path/{pk}/detail/{kwarg}/') |
| 568 |
assert response.status_code == 200 |
| 569 |
assert json.loads(response.content.decode()) == {'pk': pk, 'kwarg': kwarg} |
| 570 |
|
| 571 |
def test_detail_extra_other_action(self): |
| 572 |
# this to assure that ambiguous patterns are interpreted correctly |
| 573 |
# using the `path` converters this URL is recognized to match the pattern |
| 574 |
# of `UrlPathViewSet.url_path_detail` when it should match |
| 575 |
# `UrlPathViewSet.url_path_detail_multiple_params` |
| 576 |
pk = '1' |
| 577 |
kwarg = 1234 |
| 578 |
param = 2 |
| 579 |
response = self.client.get('/path/1/detail/1234/detail/2/') |
| 580 |
assert response.status_code == 200 |
| 581 |
assert json.loads(response.content.decode()) == {'pk': pk, 'kwarg': kwarg, 'param': param} |
| 582 |
|
| 583 |
def test_defaultrouter_root(self): |
| 584 |
response = self.client.get('/default/') |
| 585 |
assert response.status_code == 200 |
| 586 |
# only gets example path since was the last to be registered |
| 587 |
assert response.data == {"notes": "http://testserver/example/notes/"} |
| 588 |
|
| 589 |
|
| 590 |
class TestViewInitkwargs(URLPatternsTestCase, TestCase): |
| 591 |
urlpatterns = [ |
| 592 |
path('example/', include(notes_router.urls)), |
| 593 |
] |
| 594 |
|
| 595 |
def test_suffix(self): |
| 596 |
match = resolve('/example/notes/') |
| 597 |
initkwargs = match.func.initkwargs |
| 598 |
|
| 599 |
assert initkwargs['suffix'] == 'List' |
| 600 |
|
| 601 |
def test_detail(self): |
| 602 |
match = resolve('/example/notes/') |
| 603 |
initkwargs = match.func.initkwargs |
| 604 |
|
| 605 |
assert not initkwargs['detail'] |
| 606 |
|
| 607 |
def test_basename(self): |
| 608 |
match = resolve('/example/notes/') |
| 609 |
initkwargs = match.func.initkwargs |
| 610 |
|
| 611 |
assert initkwargs['basename'] == 'routertestmodel' |
| 612 |
|
| 613 |
|
| 614 |
class BasenameTestCase: |
| 615 |
def test_conflicting_autogenerated_basenames(self): |
| 616 |
""" |
| 617 |
Ensure 2 routers with the same model, and no basename specified |
| 618 |
throws an ImproperlyConfigured exception |
| 619 |
""" |
| 620 |
self.router.register(r'notes', NoteViewSet) |
| 621 |
|
| 622 |
with pytest.raises(ImproperlyConfigured): |
| 623 |
self.router.register(r'notes_kwduplicate', KWargedNoteViewSet) |
| 624 |
|
| 625 |
with pytest.raises(ImproperlyConfigured): |
| 626 |
self.router.register(r'notes_duplicate', NoteViewSet) |
| 627 |
|
| 628 |
def test_conflicting_mixed_basenames(self): |
| 629 |
""" |
| 630 |
Ensure 2 routers with the same model, and no basename specified on 1 |
| 631 |
throws an ImproperlyConfigured exception |
| 632 |
""" |
| 633 |
self.router.register(r'notes', NoteViewSet) |
| 634 |
|
| 635 |
with pytest.raises(ImproperlyConfigured): |
| 636 |
self.router.register(r'notes_kwduplicate', KWargedNoteViewSet, basename='routertestmodel') |
| 637 |
|
| 638 |
with pytest.raises(ImproperlyConfigured): |
| 639 |
self.router.register(r'notes_duplicate', NoteViewSet, basename='routertestmodel') |
| 640 |
|
| 641 |
def test_nonconflicting_mixed_basenames(self): |
| 642 |
""" |
| 643 |
Ensure 2 routers with the same model, and a distinct basename |
| 644 |
specified on the second router does not fail |
| 645 |
""" |
| 646 |
self.router.register(r'notes', NoteViewSet) |
| 647 |
self.router.register(r'notes_kwduplicate', KWargedNoteViewSet, basename='routertestmodel_kwduplicate') |
| 648 |
self.router.register(r'notes_duplicate', NoteViewSet, basename='routertestmodel_duplicate') |
| 649 |
|
| 650 |
def test_conflicting_specified_basename(self): |
| 651 |
""" |
| 652 |
Ensure 2 routers with the same model, and the same basename specified |
| 653 |
on both throws an ImproperlyConfigured exception |
| 654 |
""" |
| 655 |
self.router.register(r'notes', NoteViewSet, basename='notes') |
| 656 |
|
| 657 |
with pytest.raises(ImproperlyConfigured): |
| 658 |
self.router.register(r'notes_kwduplicate', KWargedNoteViewSet, basename='notes') |
| 659 |
|
| 660 |
with pytest.raises(ImproperlyConfigured): |
| 661 |
self.router.register(r'notes_duplicate', KWargedNoteViewSet, basename='notes') |
| 662 |
|
| 663 |
def test_nonconflicting_specified_basename(self): |
| 664 |
""" |
| 665 |
Ensure 2 routers with the same model, and a distinct basename specified |
| 666 |
on each does not throw an exception |
| 667 |
""" |
| 668 |
self.router.register(r'notes', NoteViewSet, basename='notes') |
| 669 |
self.router.register(r'notes_kwduplicate', KWargedNoteViewSet, basename='notes_kwduplicate') |
| 670 |
self.router.register(r'notes_duplicate', NoteViewSet, basename='notes_duplicate') |
| 671 |
|
| 672 |
def test_nonconflicting_specified_basename_different_models(self): |
| 673 |
""" |
| 674 |
Ensure 2 routers with different models, and a distinct basename specified |
| 675 |
on each does not throw an exception |
| 676 |
""" |
| 677 |
self.router.register(r'notes', NoteViewSet, basename='notes') |
| 678 |
self.router.register(r'notes_basename', BasenameViewSet, basename='notes_basename') |
| 679 |
|
| 680 |
def test_conflicting_specified_basename_different_models(self): |
| 681 |
""" |
| 682 |
Ensure 2 routers with different models, and a conflicting basename specified |
| 683 |
throws an exception |
| 684 |
""" |
| 685 |
self.router.register(r'notes', NoteViewSet) |
| 686 |
with pytest.raises(ImproperlyConfigured): |
| 687 |
self.router.register(r'notes_basename', BasenameViewSet, basename='routertestmodel') |
| 688 |
|
| 689 |
def test_nonconflicting_autogenerated_basename_different_models(self): |
| 690 |
""" |
| 691 |
Ensure 2 routers with different models, and a distinct basename specified |
| 692 |
on each does not throw an exception |
| 693 |
""" |
| 694 |
self.router.register(r'notes', NoteViewSet) |
| 695 |
self.router.register(r'notes_basename', BasenameViewSet) |
| 696 |
|
| 697 |
|
| 698 |
class TestDuplicateBasenameSimpleRouter(BasenameTestCase, TestCase): |
| 699 |
def setUp(self): |
| 700 |
self.router = SimpleRouter(trailing_slash=False) |
| 701 |
|
| 702 |
|
| 703 |
class TestDuplicateBasenameDefaultRouter(BasenameTestCase, TestCase): |
| 704 |
def setUp(self): |
| 705 |
self.router = DefaultRouter() |
| 706 |
|
| 707 |
|
| 708 |
class TestDuplicateBasenameDefaultRouterRootViewName(BasenameTestCase, TestCase): |
| 709 |
def setUp(self): |
| 710 |
self.router = DefaultRouter() |
| 711 |
self.router.root_view_name = 'nameable-root' |