| 1 |
import sys |
| 2 |
|
| 3 |
import pytest |
| 4 |
from django.core.exceptions import ImproperlyConfigured |
| 5 |
from django.test import TestCase |
| 6 |
|
| 7 |
from rest_framework import status |
| 8 |
from rest_framework.authentication import BasicAuthentication |
| 9 |
from rest_framework.decorators import ( |
| 10 |
action, api_view, authentication_classes, content_negotiation_class, |
| 11 |
metadata_class, parser_classes, permission_classes, renderer_classes, |
| 12 |
schema, throttle_classes, throttle_scope, versioning_class |
| 13 |
) |
| 14 |
from rest_framework.negotiation import BaseContentNegotiation |
| 15 |
from rest_framework.parsers import JSONParser |
| 16 |
from rest_framework.permissions import IsAuthenticated |
| 17 |
from rest_framework.renderers import JSONRenderer |
| 18 |
from rest_framework.response import Response |
| 19 |
from rest_framework.schemas import AutoSchema |
| 20 |
from rest_framework.test import APIRequestFactory |
| 21 |
from rest_framework.throttling import ScopedRateThrottle, UserRateThrottle |
| 22 |
from rest_framework.versioning import QueryParameterVersioning |
| 23 |
from rest_framework.views import APIView |
| 24 |
|
| 25 |
|
| 26 |
class DecoratorTestCase(TestCase): |
| 27 |
|
| 28 |
def setUp(self): |
| 29 |
self.factory = APIRequestFactory() |
| 30 |
|
| 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 |
|
| 53 |
def test_calling_method(self): |
| 54 |
|
| 55 |
@api_view(['GET']) |
| 56 |
def view(request): |
| 57 |
return Response({}) |
| 58 |
|
| 59 |
request = self.factory.get('/') |
| 60 |
response = view(request) |
| 61 |
assert response.status_code == status.HTTP_200_OK |
| 62 |
|
| 63 |
request = self.factory.post('/') |
| 64 |
response = view(request) |
| 65 |
assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED |
| 66 |
|
| 67 |
def test_calling_put_method(self): |
| 68 |
|
| 69 |
@api_view(['GET', 'PUT']) |
| 70 |
def view(request): |
| 71 |
return Response({}) |
| 72 |
|
| 73 |
request = self.factory.put('/') |
| 74 |
response = view(request) |
| 75 |
assert response.status_code == status.HTTP_200_OK |
| 76 |
|
| 77 |
request = self.factory.post('/') |
| 78 |
response = view(request) |
| 79 |
assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED |
| 80 |
|
| 81 |
def test_calling_patch_method(self): |
| 82 |
|
| 83 |
@api_view(['GET', 'PATCH']) |
| 84 |
def view(request): |
| 85 |
return Response({}) |
| 86 |
|
| 87 |
request = self.factory.patch('/') |
| 88 |
response = view(request) |
| 89 |
assert response.status_code == status.HTTP_200_OK |
| 90 |
|
| 91 |
request = self.factory.post('/') |
| 92 |
response = view(request) |
| 93 |
assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED |
| 94 |
|
| 95 |
def test_renderer_classes(self): |
| 96 |
|
| 97 |
@api_view(['GET']) |
| 98 |
@renderer_classes([JSONRenderer]) |
| 99 |
def view(request): |
| 100 |
return Response({}) |
| 101 |
|
| 102 |
request = self.factory.get('/') |
| 103 |
response = view(request) |
| 104 |
assert isinstance(response.accepted_renderer, JSONRenderer) |
| 105 |
|
| 106 |
def test_parser_classes(self): |
| 107 |
|
| 108 |
@api_view(['GET']) |
| 109 |
@parser_classes([JSONParser]) |
| 110 |
def view(request): |
| 111 |
assert len(request.parsers) == 1 |
| 112 |
assert isinstance(request.parsers[0], JSONParser) |
| 113 |
return Response({}) |
| 114 |
|
| 115 |
request = self.factory.get('/') |
| 116 |
view(request) |
| 117 |
|
| 118 |
def test_authentication_classes(self): |
| 119 |
|
| 120 |
@api_view(['GET']) |
| 121 |
@authentication_classes([BasicAuthentication]) |
| 122 |
def view(request): |
| 123 |
assert len(request.authenticators) == 1 |
| 124 |
assert isinstance(request.authenticators[0], BasicAuthentication) |
| 125 |
return Response({}) |
| 126 |
|
| 127 |
request = self.factory.get('/') |
| 128 |
view(request) |
| 129 |
|
| 130 |
def test_permission_classes(self): |
| 131 |
|
| 132 |
@api_view(['GET']) |
| 133 |
@permission_classes([IsAuthenticated]) |
| 134 |
def view(request): |
| 135 |
return Response({}) |
| 136 |
|
| 137 |
request = self.factory.get('/') |
| 138 |
response = view(request) |
| 139 |
assert response.status_code == status.HTTP_403_FORBIDDEN |
| 140 |
|
| 141 |
def test_throttle_classes(self): |
| 142 |
class OncePerDayUserThrottle(UserRateThrottle): |
| 143 |
rate = '1/day' |
| 144 |
|
| 145 |
@api_view(['GET']) |
| 146 |
@throttle_classes([OncePerDayUserThrottle]) |
| 147 |
def view(request): |
| 148 |
return Response({}) |
| 149 |
|
| 150 |
request = self.factory.get('/') |
| 151 |
response = view(request) |
| 152 |
assert response.status_code == status.HTTP_200_OK |
| 153 |
|
| 154 |
response = view(request) |
| 155 |
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS |
| 156 |
|
| 157 |
def test_throttle_scope(self): |
| 158 |
scope = "x" |
| 159 |
|
| 160 |
class OncePerDayScopedThrottle(ScopedRateThrottle): |
| 161 |
THROTTLE_RATES = {scope: "1/day"} |
| 162 |
|
| 163 |
@api_view(['GET']) |
| 164 |
@throttle_classes([OncePerDayScopedThrottle]) |
| 165 |
@throttle_scope(scope) |
| 166 |
def scoped_view_1(request): |
| 167 |
return Response({}) |
| 168 |
|
| 169 |
@api_view(['GET']) |
| 170 |
@throttle_classes([OncePerDayScopedThrottle]) |
| 171 |
@throttle_scope(scope) |
| 172 |
def scoped_view_2(request): |
| 173 |
return Response({}) |
| 174 |
|
| 175 |
@api_view(['GET']) |
| 176 |
@throttle_classes([OncePerDayScopedThrottle]) |
| 177 |
@throttle_scope(None) |
| 178 |
def unscoped_view(request): |
| 179 |
return Response({}) |
| 180 |
|
| 181 |
@api_view(['GET']) |
| 182 |
@throttle_classes([OncePerDayScopedThrottle]) |
| 183 |
@throttle_scope("invalid scope") |
| 184 |
def invalid_scope_view(request): |
| 185 |
return Response({}) |
| 186 |
|
| 187 |
request = self.factory.get('/') |
| 188 |
|
| 189 |
response = scoped_view_1(request) |
| 190 |
assert response.status_code == status.HTTP_200_OK |
| 191 |
|
| 192 |
response = scoped_view_2(request) |
| 193 |
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS |
| 194 |
|
| 195 |
response = unscoped_view(request) |
| 196 |
assert response.status_code == status.HTTP_200_OK |
| 197 |
|
| 198 |
with pytest.raises(ImproperlyConfigured): |
| 199 |
invalid_scope_view(request) |
| 200 |
|
| 201 |
def test_versioning_class(self): |
| 202 |
@api_view(["GET"]) |
| 203 |
@versioning_class(QueryParameterVersioning) |
| 204 |
def view(request): |
| 205 |
return Response({"version": request.version}) |
| 206 |
|
| 207 |
request = self.factory.get("/?version=1.2.3") |
| 208 |
response = view(request) |
| 209 |
assert response.data == {"version": "1.2.3"} |
| 210 |
|
| 211 |
def test_metadata_class(self): |
| 212 |
# From TestMetadata.test_none_metadata() |
| 213 |
@api_view() |
| 214 |
@metadata_class(None) |
| 215 |
def view(request): |
| 216 |
return Response({}) |
| 217 |
|
| 218 |
request = self.factory.options('/') |
| 219 |
response = view(request) |
| 220 |
assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED |
| 221 |
assert response.data == {'detail': 'Method "OPTIONS" not allowed.'} |
| 222 |
|
| 223 |
def test_content_negotiation(self): |
| 224 |
class CustomContentNegotiation(BaseContentNegotiation): |
| 225 |
def select_renderer(self, request, renderers, format_suffix): |
| 226 |
assert request.headers['accept'] == 'custom/type' |
| 227 |
return (renderers[0], renderers[0].media_type) |
| 228 |
|
| 229 |
@api_view(["GET"]) |
| 230 |
@content_negotiation_class(CustomContentNegotiation) |
| 231 |
def view(request): |
| 232 |
return Response({}) |
| 233 |
|
| 234 |
request = self.factory.get('/', HTTP_ACCEPT='custom/type') |
| 235 |
response = view(request) |
| 236 |
assert response.status_code == status.HTTP_200_OK |
| 237 |
|
| 238 |
def test_schema(self): |
| 239 |
""" |
| 240 |
Checks CustomSchema class is set on view |
| 241 |
""" |
| 242 |
class CustomSchema(AutoSchema): |
| 243 |
pass |
| 244 |
|
| 245 |
@api_view(['GET']) |
| 246 |
@schema(CustomSchema()) |
| 247 |
def view(request): |
| 248 |
return Response({}) |
| 249 |
|
| 250 |
assert isinstance(view.cls.schema, CustomSchema) |
| 251 |
|
| 252 |
def test_incorrect_decorator_order_permission_classes(self): |
| 253 |
""" |
| 254 |
If @permission_classes is applied after @api_view, we should raise a TypeError. |
| 255 |
""" |
| 256 |
with self.assertRaises(TypeError) as cm: |
| 257 |
@permission_classes([IsAuthenticated]) |
| 258 |
@api_view(['GET']) |
| 259 |
def view(request): |
| 260 |
return Response({}) |
| 261 |
|
| 262 |
assert '@permission_classes must come after (below) the @api_view decorator' in str(cm.exception) |
| 263 |
|
| 264 |
def test_incorrect_decorator_order_renderer_classes(self): |
| 265 |
""" |
| 266 |
If @renderer_classes is applied after @api_view, we should raise a TypeError. |
| 267 |
""" |
| 268 |
with self.assertRaises(TypeError) as cm: |
| 269 |
@renderer_classes([JSONRenderer]) |
| 270 |
@api_view(['GET']) |
| 271 |
def view(request): |
| 272 |
return Response({}) |
| 273 |
|
| 274 |
assert '@renderer_classes must come after (below) the @api_view decorator' in str(cm.exception) |
| 275 |
|
| 276 |
def test_incorrect_decorator_order_parser_classes(self): |
| 277 |
""" |
| 278 |
If @parser_classes is applied after @api_view, we should raise a TypeError. |
| 279 |
""" |
| 280 |
with self.assertRaises(TypeError) as cm: |
| 281 |
@parser_classes([JSONParser]) |
| 282 |
@api_view(['GET']) |
| 283 |
def view(request): |
| 284 |
return Response({}) |
| 285 |
|
| 286 |
assert '@parser_classes must come after (below) the @api_view decorator' in str(cm.exception) |
| 287 |
|
| 288 |
def test_incorrect_decorator_order_authentication_classes(self): |
| 289 |
""" |
| 290 |
If @authentication_classes is applied after @api_view, we should raise a TypeError. |
| 291 |
""" |
| 292 |
with self.assertRaises(TypeError) as cm: |
| 293 |
@authentication_classes([BasicAuthentication]) |
| 294 |
@api_view(['GET']) |
| 295 |
def view(request): |
| 296 |
return Response({}) |
| 297 |
|
| 298 |
assert '@authentication_classes must come after (below) the @api_view decorator' in str(cm.exception) |
| 299 |
|
| 300 |
def test_incorrect_decorator_order_throttle_classes(self): |
| 301 |
""" |
| 302 |
If @throttle_classes is applied after @api_view, we should raise a TypeError. |
| 303 |
""" |
| 304 |
class OncePerDayUserThrottle(UserRateThrottle): |
| 305 |
rate = '1/day' |
| 306 |
|
| 307 |
with self.assertRaises(TypeError) as cm: |
| 308 |
@throttle_classes([OncePerDayUserThrottle]) |
| 309 |
@api_view(['GET']) |
| 310 |
def view(request): |
| 311 |
return Response({}) |
| 312 |
|
| 313 |
assert '@throttle_classes must come after (below) the @api_view decorator' in str(cm.exception) |
| 314 |
|
| 315 |
def test_incorrect_decorator_order_versioning_class(self): |
| 316 |
""" |
| 317 |
If @versioning_class is applied after @api_view, we should raise a TypeError. |
| 318 |
""" |
| 319 |
with self.assertRaises(TypeError) as cm: |
| 320 |
@versioning_class(QueryParameterVersioning) |
| 321 |
@api_view(['GET']) |
| 322 |
def view(request): |
| 323 |
return Response({}) |
| 324 |
|
| 325 |
assert '@versioning_class must come after (below) the @api_view decorator' in str(cm.exception) |
| 326 |
|
| 327 |
def test_incorrect_decorator_order_metadata_class(self): |
| 328 |
""" |
| 329 |
If @metadata_class is applied after @api_view, we should raise a TypeError. |
| 330 |
""" |
| 331 |
with self.assertRaises(TypeError) as cm: |
| 332 |
@metadata_class(None) |
| 333 |
@api_view(['GET']) |
| 334 |
def view(request): |
| 335 |
return Response({}) |
| 336 |
|
| 337 |
assert '@metadata_class must come after (below) the @api_view decorator' in str(cm.exception) |
| 338 |
|
| 339 |
def test_incorrect_decorator_order_content_negotiation_class(self): |
| 340 |
""" |
| 341 |
If @content_negotiation_class is applied after @api_view, we should raise a TypeError. |
| 342 |
""" |
| 343 |
class CustomContentNegotiation(BaseContentNegotiation): |
| 344 |
def select_renderer(self, request, renderers, format_suffix): |
| 345 |
return (renderers[0], renderers[0].media_type) |
| 346 |
|
| 347 |
with self.assertRaises(TypeError) as cm: |
| 348 |
@content_negotiation_class(CustomContentNegotiation) |
| 349 |
@api_view(['GET']) |
| 350 |
def view(request): |
| 351 |
return Response({}) |
| 352 |
|
| 353 |
assert '@content_negotiation_class must come after (below) the @api_view decorator' in str(cm.exception) |
| 354 |
|
| 355 |
def test_incorrect_decorator_order_schema(self): |
| 356 |
""" |
| 357 |
If @schema is applied after @api_view, we should raise a TypeError. |
| 358 |
""" |
| 359 |
class CustomSchema(AutoSchema): |
| 360 |
pass |
| 361 |
|
| 362 |
with self.assertRaises(TypeError) as cm: |
| 363 |
@schema(CustomSchema()) |
| 364 |
@api_view(['GET']) |
| 365 |
def view(request): |
| 366 |
return Response({}) |
| 367 |
|
| 368 |
assert '@schema must come after (below) the @api_view decorator' in str(cm.exception) |
| 369 |
|
| 370 |
|
| 371 |
class ActionDecoratorTestCase(TestCase): |
| 372 |
|
| 373 |
def test_defaults(self): |
| 374 |
@action(detail=True) |
| 375 |
def test_action(request): |
| 376 |
"""Description""" |
| 377 |
|
| 378 |
assert test_action.mapping == {'get': 'test_action'} |
| 379 |
assert test_action.detail is True |
| 380 |
assert test_action.url_path == 'test_action' |
| 381 |
assert test_action.url_name == 'test-action' |
| 382 |
assert test_action.kwargs == { |
| 383 |
'name': 'Test action', |
| 384 |
'description': 'Description', |
| 385 |
} |
| 386 |
|
| 387 |
def test_detail_required(self): |
| 388 |
with pytest.raises(AssertionError) as excinfo: |
| 389 |
@action() |
| 390 |
def test_action(request): |
| 391 |
raise NotImplementedError |
| 392 |
|
| 393 |
assert str(excinfo.value) == "@action() missing required argument: 'detail'" |
| 394 |
|
| 395 |
@pytest.mark.skipif(sys.version_info < (3, 11), reason="HTTPMethod was added in Python 3.11") |
| 396 |
def test_method_mapping_http_method(self): |
| 397 |
from http import HTTPMethod |
| 398 |
|
| 399 |
method_names = [getattr(HTTPMethod, name.upper()) for name in APIView.http_method_names] |
| 400 |
|
| 401 |
@action(detail=False, methods=method_names) |
| 402 |
def test_action(): |
| 403 |
raise NotImplementedError |
| 404 |
|
| 405 |
expected_mapping = {name: test_action.__name__ for name in APIView.http_method_names} |
| 406 |
|
| 407 |
assert test_action.mapping == expected_mapping |
| 408 |
|
| 409 |
def test_method_mapping_http_methods(self): |
| 410 |
# All HTTP methods should be mappable |
| 411 |
@action(detail=False, methods=[]) |
| 412 |
def test_action(): |
| 413 |
raise NotImplementedError |
| 414 |
|
| 415 |
for name in APIView.http_method_names: |
| 416 |
def method(): |
| 417 |
raise NotImplementedError |
| 418 |
|
| 419 |
method.__name__ = name |
| 420 |
getattr(test_action.mapping, name)(method) |
| 421 |
|
| 422 |
# ensure the mapping returns the correct method name |
| 423 |
for name in APIView.http_method_names: |
| 424 |
assert test_action.mapping[name] == name |
| 425 |
|
| 426 |
def test_view_name_kwargs(self): |
| 427 |
""" |
| 428 |
'name' and 'suffix' are mutually exclusive kwargs used for generating |
| 429 |
a view's display name. |
| 430 |
""" |
| 431 |
# by default, generate name from method |
| 432 |
@action(detail=True) |
| 433 |
def test_action(request): |
| 434 |
raise NotImplementedError |
| 435 |
|
| 436 |
assert test_action.kwargs == { |
| 437 |
'description': None, |
| 438 |
'name': 'Test action', |
| 439 |
} |
| 440 |
|
| 441 |
# name kwarg supersedes name generation |
| 442 |
@action(detail=True, name='test name') |
| 443 |
def test_action(request): |
| 444 |
raise NotImplementedError |
| 445 |
|
| 446 |
assert test_action.kwargs == { |
| 447 |
'description': None, |
| 448 |
'name': 'test name', |
| 449 |
} |
| 450 |
|
| 451 |
# suffix kwarg supersedes name generation |
| 452 |
@action(detail=True, suffix='Suffix') |
| 453 |
def test_action(request): |
| 454 |
raise NotImplementedError |
| 455 |
|
| 456 |
assert test_action.kwargs == { |
| 457 |
'description': None, |
| 458 |
'suffix': 'Suffix', |
| 459 |
} |
| 460 |
|
| 461 |
# name + suffix is a conflict. |
| 462 |
with pytest.raises(TypeError) as excinfo: |
| 463 |
action(detail=True, name='test name', suffix='Suffix') |
| 464 |
|
| 465 |
assert str(excinfo.value) == "`name` and `suffix` are mutually exclusive arguments." |
| 466 |
|
| 467 |
def test_method_mapping(self): |
| 468 |
@action(detail=False) |
| 469 |
def test_action(request): |
| 470 |
raise NotImplementedError |
| 471 |
|
| 472 |
@test_action.mapping.post |
| 473 |
def test_action_post(request): |
| 474 |
raise NotImplementedError |
| 475 |
|
| 476 |
# The secondary handler methods should not have the action attributes |
| 477 |
for name in ['mapping', 'detail', 'url_path', 'url_name', 'kwargs']: |
| 478 |
assert hasattr(test_action, name) and not hasattr(test_action_post, name) |
| 479 |
|
| 480 |
def test_method_mapping_already_mapped(self): |
| 481 |
@action(detail=True) |
| 482 |
def test_action(request): |
| 483 |
raise NotImplementedError |
| 484 |
|
| 485 |
msg = "Method 'get' has already been mapped to '.test_action'." |
| 486 |
with self.assertRaisesMessage(AssertionError, msg): |
| 487 |
@test_action.mapping.get |
| 488 |
def test_action_get(request): |
| 489 |
raise NotImplementedError |
| 490 |
|
| 491 |
def test_method_mapping_overwrite(self): |
| 492 |
@action(detail=True) |
| 493 |
def test_action(): |
| 494 |
raise NotImplementedError |
| 495 |
|
| 496 |
msg = ("Method mapping does not behave like the property decorator. You " |
| 497 |
"cannot use the same method name for each mapping declaration.") |
| 498 |
with self.assertRaisesMessage(AssertionError, msg): |
| 499 |
@test_action.mapping.post |
| 500 |
def test_action(): |
| 501 |
raise NotImplementedError |