Debian Codegraph @

tests/decorators/tests.py

raw
1 import asyncio
2 from functools import update_wrapper, wraps
3 from unittest import TestCase
4
5 from asgiref.sync import iscoroutinefunction
6
7 from django.contrib.admin.views.decorators import staff_member_required
8 from django.contrib.auth.decorators import (
9 login_required,
10 permission_required,
11 user_passes_test,
12 )
13 from django.http import HttpResponse
14 from django.test import SimpleTestCase
15 from django.utils.decorators import method_decorator
16 from django.utils.functional import keep_lazy, keep_lazy_text, lazy
17 from django.utils.safestring import mark_safe
18 from django.views.decorators.cache import cache_control, cache_page, never_cache
19 from django.views.decorators.http import (
20 condition,
21 require_GET,
22 require_http_methods,
23 require_POST,
24 require_safe,
25 )
26 from django.views.decorators.vary import vary_on_cookie, vary_on_headers
27
28
29 def fully_decorated(request):
30 """Expected __doc__"""
31 return HttpResponse("<html><body>dummy</body></html>")
32
33
34 fully_decorated.anything = "Expected __dict__"
35
36
37 def compose(*functions):
38 # compose(f, g)(*args, **kwargs) == f(g(*args, **kwargs))
39 functions = list(reversed(functions))
40
41 def _inner(*args, **kwargs):
42 result = functions[0](*args, **kwargs)
43 for f in functions[1:]:
44 result = f(result)
45 return result
46
47 return _inner
48
49
50 full_decorator = compose(
51 # django.views.decorators.http
52 require_http_methods(["GET"]),
53 require_GET,
54 require_POST,
55 require_safe,
56 condition(lambda r: None, lambda r: None),
57 # django.views.decorators.vary
58 vary_on_headers("Accept-language"),
59 vary_on_cookie,
60 # django.views.decorators.cache
61 cache_page(60 * 15),
62 cache_control(private=True),
63 never_cache,
64 # django.contrib.auth.decorators
65 # Apply user_passes_test twice to check #9474
66 user_passes_test(lambda u: True),
67 login_required,
68 permission_required("change_world"),
69 # django.contrib.admin.views.decorators
70 staff_member_required,
71 # django.utils.functional
72 keep_lazy(HttpResponse),
73 keep_lazy_text,
74 lazy,
75 # django.utils.safestring
76 mark_safe,
77 )
78
79 fully_decorated = full_decorator(fully_decorated)
80
81
82 class DecoratorsTest(TestCase):
83 def test_attributes(self):
84 """
85 Built-in decorators set certain attributes of the wrapped function.
86 """
87 self.assertEqual(fully_decorated.__name__, "fully_decorated")
88 self.assertEqual(fully_decorated.__doc__, "Expected __doc__")
89 self.assertEqual(fully_decorated.__dict__["anything"], "Expected __dict__")
90
91 def test_user_passes_test_composition(self):
92 """
93 The user_passes_test decorator can be applied multiple times (#9474).
94 """
95
96 def test1(user):
97 user.decorators_applied.append("test1")
98 return True
99
100 def test2(user):
101 user.decorators_applied.append("test2")
102 return True
103
104 def callback(request):
105 return request.user.decorators_applied
106
107 callback = user_passes_test(test1)(callback)
108 callback = user_passes_test(test2)(callback)
109
110 class DummyUser:
111 pass
112
113 class DummyRequest:
114 pass
115
116 request = DummyRequest()
117 request.user = DummyUser()
118 request.user.decorators_applied = []
119 response = callback(request)
120
121 self.assertEqual(response, ["test2", "test1"])
122
123
124 # For testing method_decorator, a decorator that assumes a single argument.
125 # We will get type arguments if there is a mismatch in the number of arguments.
126 def simple_dec(func):
127 @wraps(func)
128 def wrapper(arg):
129 return func("test:" + arg)
130
131 return wrapper
132
133
134 simple_dec_m = method_decorator(simple_dec)
135
136
137 # For testing method_decorator, two decorators that add an attribute to the function
138 def myattr_dec(func):
139 def wrapper(*args, **kwargs):
140 return func(*args, **kwargs)
141
142 wrapper.myattr = True
143 return wrapper
144
145
146 myattr_dec_m = method_decorator(myattr_dec)
147
148
149 def myattr2_dec(func):
150 def wrapper(*args, **kwargs):
151 return func(*args, **kwargs)
152
153 wrapper.myattr2 = True
154 return wrapper
155
156
157 myattr2_dec_m = method_decorator(myattr2_dec)
158
159
160 class ClsDec:
161 def __init__(self, myattr):
162 self.myattr = myattr
163
164 def __call__(self, f):
165 def wrapper():
166 return f() and self.myattr
167
168 return update_wrapper(wrapper, f)
169
170
171 class MethodDecoratorTests(SimpleTestCase):
172 """
173 Tests for method_decorator
174 """
175
176 def test_preserve_signature(self):
177 class Test:
178 @simple_dec_m
179 def say(self, arg):
180 return arg
181
182 self.assertEqual("test:hello", Test().say("hello"))
183
184 def test_preserve_attributes(self):
185 # Sanity check myattr_dec and myattr2_dec
186 @myattr_dec
187 def func():
188 pass
189
190 self.assertIs(getattr(func, "myattr", False), True)
191
192 @myattr2_dec
193 def func():
194 pass
195
196 self.assertIs(getattr(func, "myattr2", False), True)
197
198 @myattr_dec
199 @myattr2_dec
200 def func():
201 pass
202
203 self.assertIs(getattr(func, "myattr", False), True)
204 self.assertIs(getattr(func, "myattr2", False), False)
205
206 # Decorate using method_decorator() on the method.
207 class TestPlain:
208 @myattr_dec_m
209 @myattr2_dec_m
210 def method(self):
211 "A method"
212 pass
213
214 # Decorate using method_decorator() on both the class and the method.
215 # The decorators applied to the methods are applied before the ones
216 # applied to the class.
217 @method_decorator(myattr_dec_m, "method")
218 class TestMethodAndClass:
219 @method_decorator(myattr2_dec_m)
220 def method(self):
221 "A method"
222 pass
223
224 # Decorate using an iterable of function decorators.
225 @method_decorator((myattr_dec, myattr2_dec), "method")
226 class TestFunctionIterable:
227 def method(self):
228 "A method"
229 pass
230
231 # Decorate using an iterable of method decorators.
232 decorators = (myattr_dec_m, myattr2_dec_m)
233
234 @method_decorator(decorators, "method")
235 class TestMethodIterable:
236 def method(self):
237 "A method"
238 pass
239
240 tests = (
241 TestPlain,
242 TestMethodAndClass,
243 TestFunctionIterable,
244 TestMethodIterable,
245 )
246 for Test in tests:
247 with self.subTest(Test=Test):
248 self.assertIs(getattr(Test().method, "myattr", False), True)
249 self.assertIs(getattr(Test().method, "myattr2", False), True)
250 self.assertIs(getattr(Test.method, "myattr", False), True)
251 self.assertIs(getattr(Test.method, "myattr2", False), True)
252 self.assertEqual(Test.method.__doc__, "A method")
253 self.assertEqual(Test.method.__name__, "method")
254
255 def test_new_attribute(self):
256 """A decorator that sets a new attribute on the method."""
257
258 def decorate(func):
259 func.x = 1
260 return func
261
262 class MyClass:
263 @method_decorator(decorate)
264 def method(self):
265 return True
266
267 obj = MyClass()
268 self.assertEqual(obj.method.x, 1)
269 self.assertIs(obj.method(), True)
270
271 def test_bad_iterable(self):
272 decorators = {myattr_dec_m, myattr2_dec_m}
273 msg = "'set' object is not subscriptable"
274 with self.assertRaisesMessage(TypeError, msg):
275
276 @method_decorator(decorators, "method")
277 class TestIterable:
278 def method(self):
279 "A method"
280 pass
281
282 # Test for argumented decorator
283 def test_argumented(self):
284 class Test:
285 @method_decorator(ClsDec(False))
286 def method(self):
287 return True
288
289 self.assertIs(Test().method(), False)
290
291 def test_descriptors(self):
292 def original_dec(wrapped):
293 def _wrapped(arg):
294 return wrapped(arg)
295
296 return _wrapped
297
298 method_dec = method_decorator(original_dec)
299
300 class bound_wrapper:
301 def __init__(self, wrapped):
302 self.wrapped = wrapped
303 self.__name__ = wrapped.__name__
304
305 def __call__(self, arg):
306 return self.wrapped(arg)
307
308 def __get__(self, instance, cls=None):
309 return self
310
311 class descriptor_wrapper:
312 def __init__(self, wrapped):
313 self.wrapped = wrapped
314 self.__name__ = wrapped.__name__
315
316 def __get__(self, instance, cls=None):
317 return bound_wrapper(self.wrapped.__get__(instance, cls))
318
319 class Test:
320 @method_dec
321 @descriptor_wrapper
322 def method(self, arg):
323 return arg
324
325 self.assertEqual(Test().method(1), 1)
326
327 def test_class_decoration(self):
328 """
329 @method_decorator can be used to decorate a class and its methods.
330 """
331
332 def deco(func):
333 def _wrapper(*args, **kwargs):
334 return True
335
336 return _wrapper
337
338 @method_decorator(deco, name="method")
339 class Test:
340 def method(self):
341 return False
342
343 self.assertTrue(Test().method())
344
345 def test_tuple_of_decorators(self):
346 """
347 @method_decorator can accept a tuple of decorators.
348 """
349
350 def add_question_mark(func):
351 def _wrapper(*args, **kwargs):
352 return func(*args, **kwargs) + "?"
353
354 return _wrapper
355
356 def add_exclamation_mark(func):
357 def _wrapper(*args, **kwargs):
358 return func(*args, **kwargs) + "!"
359
360 return _wrapper
361
362 # The order should be consistent with the usual order in which
363 # decorators are applied, e.g.
364 # @add_exclamation_mark
365 # @add_question_mark
366 # def func():
367 # ...
368 decorators = (add_exclamation_mark, add_question_mark)
369
370 @method_decorator(decorators, name="method")
371 class TestFirst:
372 def method(self):
373 return "hello world"
374
375 class TestSecond:
376 @method_decorator(decorators)
377 def method(self):
378 return "hello world"
379
380 self.assertEqual(TestFirst().method(), "hello world?!")
381 self.assertEqual(TestSecond().method(), "hello world?!")
382
383 def test_invalid_non_callable_attribute_decoration(self):
384 """
385 @method_decorator on a non-callable attribute raises an error.
386 """
387 msg = (
388 "Cannot decorate 'prop' as it isn't a callable attribute of "
389 "<class 'Test'> (1)"
390 )
391 with self.assertRaisesMessage(TypeError, msg):
392
393 @method_decorator(lambda: None, name="prop")
394 class Test:
395 prop = 1
396
397 @classmethod
398 def __module__(cls):
399 return "tests"
400
401 def test_invalid_method_name_to_decorate(self):
402 """
403 @method_decorator on a nonexistent method raises an error.
404 """
405 msg = (
406 "The keyword argument `name` must be the name of a method of the "
407 "decorated class: <class 'Test'>. Got 'nonexistent_method' instead"
408 )
409 with self.assertRaisesMessage(ValueError, msg):
410
411 @method_decorator(lambda: None, name="nonexistent_method")
412 class Test:
413 @classmethod
414 def __module__(cls):
415 return "tests"
416
417 def test_wrapper_assignments(self):
418 """@method_decorator preserves wrapper assignments."""
419 func_name = None
420 func_module = None
421
422 def decorator(func):
423 @wraps(func)
424 def inner(*args, **kwargs):
425 nonlocal func_name, func_module
426 func_name = getattr(func, "__name__", None)
427 func_module = getattr(func, "__module__", None)
428 return func(*args, **kwargs)
429
430 return inner
431
432 class Test:
433 @method_decorator(decorator)
434 def method(self):
435 return "tests"
436
437 Test().method()
438 self.assertEqual(func_name, "method")
439 self.assertIsNotNone(func_module)
440
441
442 def async_simple_dec(func):
443 @wraps(func)
444 async def wrapper(*args, **kwargs):
445 result = await func(*args, **kwargs)
446 return f"returned: {result}"
447
448 return wrapper
449
450
451 async_simple_dec_m = method_decorator(async_simple_dec)
452
453
454 class AsyncMethodDecoratorTests(SimpleTestCase):
455 """
456 Tests for async method_decorator
457 """
458
459 async def test_preserve_signature(self):
460 class Test:
461 @async_simple_dec_m
462 async def say(self, msg):
463 return f"Saying {msg}"
464
465 self.assertEqual(await Test().say("hello"), "returned: Saying hello")
466
467 def test_preserve_attributes(self):
468 async def func(*args, **kwargs):
469 await asyncio.sleep(0.01)
470 return args, kwargs
471
472 def myattr_dec(func):
473 async def wrapper(*args, **kwargs):
474 return await func(*args, **kwargs)
475
476 wrapper.myattr = True
477 return wrapper
478
479 def myattr2_dec(func):
480 async def wrapper(*args, **kwargs):
481 return await func(*args, **kwargs)
482
483 wrapper.myattr2 = True
484 return wrapper
485
486 # Sanity check myattr_dec and myattr2_dec
487 func = myattr_dec(func)
488
489 self.assertIs(getattr(func, "myattr", False), True)
490
491 func = myattr2_dec(func)
492 self.assertIs(getattr(func, "myattr2", False), True)
493
494 func = myattr_dec(myattr2_dec(func))
495 self.assertIs(getattr(func, "myattr", False), True)
496 self.assertIs(getattr(func, "myattr2", False), False)
497
498 myattr_dec_m = method_decorator(myattr_dec)
499 myattr2_dec_m = method_decorator(myattr2_dec)
500
501 # Decorate using method_decorator() on the async method.
502 class TestPlain:
503 @myattr_dec_m
504 @myattr2_dec_m
505 async def method(self):
506 "A method"
507
508 # Decorate using method_decorator() on both the class and the method.
509 # The decorators applied to the methods are applied before the ones
510 # applied to the class.
511 @method_decorator(myattr_dec_m, "method")
512 class TestMethodAndClass:
513 @method_decorator(myattr2_dec_m)
514 async def method(self):
515 "A method"
516
517 # Decorate using an iterable of function decorators.
518 @method_decorator((myattr_dec, myattr2_dec), "method")
519 class TestFunctionIterable:
520 async def method(self):
521 "A method"
522
523 # Decorate using an iterable of method decorators.
524 @method_decorator((myattr_dec_m, myattr2_dec_m), "method")
525 class TestMethodIterable:
526 async def method(self):
527 "A method"
528
529 tests = (
530 TestPlain,
531 TestMethodAndClass,
532 TestFunctionIterable,
533 TestMethodIterable,
534 )
535 for Test in tests:
536 with self.subTest(Test=Test):
537 self.assertIs(getattr(Test().method, "myattr", False), True)
538 self.assertIs(getattr(Test().method, "myattr2", False), True)
539 self.assertIs(getattr(Test.method, "myattr", False), True)
540 self.assertIs(getattr(Test.method, "myattr2", False), True)
541 self.assertEqual(Test.method.__doc__, "A method")
542 self.assertEqual(Test.method.__name__, "method")
543
544 async def test_new_attribute(self):
545 """A decorator that sets a new attribute on the method."""
546
547 def decorate(func):
548 func.x = 1
549 return func
550
551 class MyClass:
552 @method_decorator(decorate)
553 async def method(self):
554 return True
555
556 obj = MyClass()
557 self.assertEqual(obj.method.x, 1)
558 self.assertIs(await obj.method(), True)
559
560 def test_bad_iterable(self):
561 decorators = {async_simple_dec}
562 msg = "'set' object is not subscriptable"
563 with self.assertRaisesMessage(TypeError, msg):
564
565 @method_decorator(decorators, "method")
566 class TestIterable:
567 async def method(self):
568 await asyncio.sleep(0.01)
569
570 async def test_argumented(self):
571
572 class ClsDecAsync:
573 def __init__(self, myattr):
574 self.myattr = myattr
575
576 def __call__(self, f):
577 async def wrapper():
578 result = await f()
579 return f"{result} appending {self.myattr}"
580
581 return update_wrapper(wrapper, f)
582
583 class Test:
584 @method_decorator(ClsDecAsync(False))
585 async def method(self):
586 return True
587
588 self.assertEqual(await Test().method(), "True appending False")
589
590 async def test_descriptors(self):
591 class bound_wrapper:
592 def __init__(self, wrapped):
593 self.wrapped = wrapped
594 self.__name__ = wrapped.__name__
595
596 async def __call__(self, *args, **kwargs):
597 return await self.wrapped(*args, **kwargs)
598
599 def __get__(self, instance, cls=None):
600 return self
601
602 class descriptor_wrapper:
603 def __init__(self, wrapped):
604 self.wrapped = wrapped
605 self.__name__ = wrapped.__name__
606
607 def __get__(self, instance, cls=None):
608 return bound_wrapper(self.wrapped.__get__(instance, cls))
609
610 class Test:
611 @async_simple_dec_m
612 @descriptor_wrapper
613 async def method(self, arg):
614 return arg
615
616 self.assertEqual(await Test().method(1), "returned: 1")
617
618 async def test_class_decoration(self):
619 """
620 @method_decorator can be used to decorate a class and its methods.
621 """
622
623 @method_decorator(async_simple_dec, name="method")
624 class Test:
625 async def method(self):
626 return False
627
628 async def not_method(self):
629 return "a string"
630
631 self.assertEqual(await Test().method(), "returned: False")
632 self.assertEqual(await Test().not_method(), "a string")
633
634 async def test_tuple_of_decorators(self):
635 """
636 @method_decorator can accept a tuple of decorators.
637 """
638
639 def add_question_mark(func):
640 async def _wrapper(*args, **kwargs):
641 await asyncio.sleep(0.01)
642 return await func(*args, **kwargs) + "?"
643
644 return _wrapper
645
646 def add_exclamation_mark(func):
647 async def _wrapper(*args, **kwargs):
648 await asyncio.sleep(0.01)
649 return await func(*args, **kwargs) + "!"
650
651 return _wrapper
652
653 decorators = (add_exclamation_mark, add_question_mark)
654
655 @method_decorator(decorators, name="method")
656 class TestFirst:
657 async def method(self):
658 return "hello world"
659
660 class TestSecond:
661 @method_decorator(decorators)
662 async def method(self):
663 return "world hello"
664
665 self.assertEqual(await TestFirst().method(), "hello world?!")
666 self.assertEqual(await TestSecond().method(), "world hello?!")
667
668 async def test_wrapper_assignments(self):
669 """@method_decorator preserves wrapper assignments."""
670 func_data = {}
671
672 def decorator(func):
673 @wraps(func)
674 async def inner(*args, **kwargs):
675 func_data["func_name"] = getattr(func, "__name__", None)
676 func_data["func_module"] = getattr(func, "__module__", None)
677 return await func(*args, **kwargs)
678
679 return inner
680
681 class Test:
682 @method_decorator(decorator)
683 async def method(self):
684 return "tests"
685
686 await Test().method()
687 expected = {"func_name": "method", "func_module": "decorators.tests"}
688 self.assertEqual(func_data, expected)
689
690 async def test_markcoroutinefunction_applied(self):
691 class Test:
692 @async_simple_dec_m
693 async def method(self):
694 return "tests"
695
696 method = Test().method
697 self.assertIs(iscoroutinefunction(method), True)
698 self.assertEqual(await method(), "returned: tests")