tests.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. from functools import update_wrapper, wraps
  2. from unittest import TestCase
  3. from django.contrib.admin.views.decorators import staff_member_required
  4. from django.contrib.auth.decorators import (
  5. login_required, permission_required, user_passes_test,
  6. )
  7. from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed
  8. from django.middleware.clickjacking import XFrameOptionsMiddleware
  9. from django.test import SimpleTestCase
  10. from django.utils.decorators import method_decorator
  11. from django.utils.functional import keep_lazy, keep_lazy_text, lazy
  12. from django.utils.safestring import mark_safe
  13. from django.views.decorators.cache import (
  14. cache_control, cache_page, never_cache,
  15. )
  16. from django.views.decorators.clickjacking import (
  17. xframe_options_deny, xframe_options_exempt, xframe_options_sameorigin,
  18. )
  19. from django.views.decorators.http import (
  20. condition, require_GET, require_http_methods, require_POST, require_safe,
  21. )
  22. from django.views.decorators.vary import vary_on_cookie, vary_on_headers
  23. def fully_decorated(request):
  24. """Expected __doc__"""
  25. return HttpResponse('<html><body>dummy</body></html>')
  26. fully_decorated.anything = "Expected __dict__"
  27. def compose(*functions):
  28. # compose(f, g)(*args, **kwargs) == f(g(*args, **kwargs))
  29. functions = list(reversed(functions))
  30. def _inner(*args, **kwargs):
  31. result = functions[0](*args, **kwargs)
  32. for f in functions[1:]:
  33. result = f(result)
  34. return result
  35. return _inner
  36. full_decorator = compose(
  37. # django.views.decorators.http
  38. require_http_methods(["GET"]),
  39. require_GET,
  40. require_POST,
  41. require_safe,
  42. condition(lambda r: None, lambda r: None),
  43. # django.views.decorators.vary
  44. vary_on_headers('Accept-language'),
  45. vary_on_cookie,
  46. # django.views.decorators.cache
  47. cache_page(60 * 15),
  48. cache_control(private=True),
  49. never_cache,
  50. # django.contrib.auth.decorators
  51. # Apply user_passes_test twice to check #9474
  52. user_passes_test(lambda u: True),
  53. login_required,
  54. permission_required('change_world'),
  55. # django.contrib.admin.views.decorators
  56. staff_member_required,
  57. # django.utils.functional
  58. keep_lazy(HttpResponse),
  59. keep_lazy_text,
  60. lazy,
  61. # django.utils.safestring
  62. mark_safe,
  63. )
  64. fully_decorated = full_decorator(fully_decorated)
  65. class DecoratorsTest(TestCase):
  66. def test_attributes(self):
  67. """
  68. Built-in decorators set certain attributes of the wrapped function.
  69. """
  70. self.assertEqual(fully_decorated.__name__, 'fully_decorated')
  71. self.assertEqual(fully_decorated.__doc__, 'Expected __doc__')
  72. self.assertEqual(fully_decorated.__dict__['anything'], 'Expected __dict__')
  73. def test_user_passes_test_composition(self):
  74. """
  75. The user_passes_test decorator can be applied multiple times (#9474).
  76. """
  77. def test1(user):
  78. user.decorators_applied.append('test1')
  79. return True
  80. def test2(user):
  81. user.decorators_applied.append('test2')
  82. return True
  83. def callback(request):
  84. return request.user.decorators_applied
  85. callback = user_passes_test(test1)(callback)
  86. callback = user_passes_test(test2)(callback)
  87. class DummyUser:
  88. pass
  89. class DummyRequest:
  90. pass
  91. request = DummyRequest()
  92. request.user = DummyUser()
  93. request.user.decorators_applied = []
  94. response = callback(request)
  95. self.assertEqual(response, ['test2', 'test1'])
  96. def test_cache_page(self):
  97. def my_view(request):
  98. return "response"
  99. my_view_cached = cache_page(123)(my_view)
  100. self.assertEqual(my_view_cached(HttpRequest()), "response")
  101. my_view_cached2 = cache_page(123, key_prefix="test")(my_view)
  102. self.assertEqual(my_view_cached2(HttpRequest()), "response")
  103. def test_require_safe_accepts_only_safe_methods(self):
  104. """
  105. Test for the require_safe decorator.
  106. A view returns either a response or an exception.
  107. Refs #15637.
  108. """
  109. def my_view(request):
  110. return HttpResponse("OK")
  111. my_safe_view = require_safe(my_view)
  112. request = HttpRequest()
  113. request.method = 'GET'
  114. self.assertIsInstance(my_safe_view(request), HttpResponse)
  115. request.method = 'HEAD'
  116. self.assertIsInstance(my_safe_view(request), HttpResponse)
  117. request.method = 'POST'
  118. self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
  119. request.method = 'PUT'
  120. self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
  121. request.method = 'DELETE'
  122. self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
  123. # For testing method_decorator, a decorator that assumes a single argument.
  124. # We will get type arguments if there is a mismatch in the number of arguments.
  125. def simple_dec(func):
  126. def wrapper(arg):
  127. return func("test:" + arg)
  128. return wraps(func)(wrapper)
  129. simple_dec_m = method_decorator(simple_dec)
  130. # For testing method_decorator, two decorators that add an attribute to the function
  131. def myattr_dec(func):
  132. def wrapper(*args, **kwargs):
  133. return func(*args, **kwargs)
  134. wrapper.myattr = True
  135. return wraps(func)(wrapper)
  136. myattr_dec_m = method_decorator(myattr_dec)
  137. def myattr2_dec(func):
  138. def wrapper(*args, **kwargs):
  139. return func(*args, **kwargs)
  140. wrapper.myattr2 = True
  141. return wraps(func)(wrapper)
  142. myattr2_dec_m = method_decorator(myattr2_dec)
  143. class ClsDec:
  144. def __init__(self, myattr):
  145. self.myattr = myattr
  146. def __call__(self, f):
  147. def wrapped():
  148. return f() and self.myattr
  149. return update_wrapper(wrapped, f)
  150. class MethodDecoratorTests(SimpleTestCase):
  151. """
  152. Tests for method_decorator
  153. """
  154. def test_preserve_signature(self):
  155. class Test:
  156. @simple_dec_m
  157. def say(self, arg):
  158. return arg
  159. self.assertEqual("test:hello", Test().say("hello"))
  160. def test_preserve_attributes(self):
  161. # Sanity check myattr_dec and myattr2_dec
  162. @myattr_dec
  163. @myattr2_dec
  164. def func():
  165. pass
  166. self.assertIs(getattr(func, 'myattr', False), True)
  167. self.assertIs(getattr(func, 'myattr2', False), True)
  168. # Decorate using method_decorator() on the method.
  169. class TestPlain:
  170. @myattr_dec_m
  171. @myattr2_dec_m
  172. def method(self):
  173. "A method"
  174. pass
  175. # Decorate using method_decorator() on both the class and the method.
  176. # The decorators applied to the methods are applied before the ones
  177. # applied to the class.
  178. @method_decorator(myattr_dec_m, "method")
  179. class TestMethodAndClass:
  180. @method_decorator(myattr2_dec_m)
  181. def method(self):
  182. "A method"
  183. pass
  184. # Decorate using an iterable of decorators.
  185. decorators = (myattr_dec_m, myattr2_dec_m)
  186. @method_decorator(decorators, "method")
  187. class TestIterable:
  188. def method(self):
  189. "A method"
  190. pass
  191. for Test in (TestPlain, TestMethodAndClass, TestIterable):
  192. self.assertIs(getattr(Test().method, 'myattr', False), True)
  193. self.assertIs(getattr(Test().method, 'myattr2', False), True)
  194. self.assertIs(getattr(Test.method, 'myattr', False), True)
  195. self.assertIs(getattr(Test.method, 'myattr2', False), True)
  196. self.assertEqual(Test.method.__doc__, 'A method')
  197. self.assertEqual(Test.method.__name__, 'method')
  198. def test_bad_iterable(self):
  199. decorators = {myattr_dec_m, myattr2_dec_m}
  200. msg = "'set' object is not subscriptable"
  201. with self.assertRaisesMessage(TypeError, msg):
  202. @method_decorator(decorators, "method")
  203. class TestIterable:
  204. def method(self):
  205. "A method"
  206. pass
  207. # Test for argumented decorator
  208. def test_argumented(self):
  209. class Test:
  210. @method_decorator(ClsDec(False))
  211. def method(self):
  212. return True
  213. self.assertIs(Test().method(), False)
  214. def test_descriptors(self):
  215. def original_dec(wrapped):
  216. def _wrapped(arg):
  217. return wrapped(arg)
  218. return _wrapped
  219. method_dec = method_decorator(original_dec)
  220. class bound_wrapper:
  221. def __init__(self, wrapped):
  222. self.wrapped = wrapped
  223. self.__name__ = wrapped.__name__
  224. def __call__(self, arg):
  225. return self.wrapped(arg)
  226. def __get__(self, instance, cls=None):
  227. return self
  228. class descriptor_wrapper:
  229. def __init__(self, wrapped):
  230. self.wrapped = wrapped
  231. self.__name__ = wrapped.__name__
  232. def __get__(self, instance, cls=None):
  233. return bound_wrapper(self.wrapped.__get__(instance, cls))
  234. class Test:
  235. @method_dec
  236. @descriptor_wrapper
  237. def method(self, arg):
  238. return arg
  239. self.assertEqual(Test().method(1), 1)
  240. def test_class_decoration(self):
  241. """
  242. @method_decorator can be used to decorate a class and its methods.
  243. """
  244. def deco(func):
  245. def _wrapper(*args, **kwargs):
  246. return True
  247. return _wrapper
  248. @method_decorator(deco, name="method")
  249. class Test:
  250. def method(self):
  251. return False
  252. self.assertTrue(Test().method())
  253. def test_tuple_of_decorators(self):
  254. """
  255. @method_decorator can accept a tuple of decorators.
  256. """
  257. def add_question_mark(func):
  258. def _wrapper(*args, **kwargs):
  259. return func(*args, **kwargs) + "?"
  260. return _wrapper
  261. def add_exclamation_mark(func):
  262. def _wrapper(*args, **kwargs):
  263. return func(*args, **kwargs) + "!"
  264. return _wrapper
  265. # The order should be consistent with the usual order in which
  266. # decorators are applied, e.g.
  267. # @add_exclamation_mark
  268. # @add_question_mark
  269. # def func():
  270. # ...
  271. decorators = (add_exclamation_mark, add_question_mark)
  272. @method_decorator(decorators, name="method")
  273. class TestFirst:
  274. def method(self):
  275. return "hello world"
  276. class TestSecond:
  277. @method_decorator(decorators)
  278. def method(self):
  279. return "hello world"
  280. self.assertEqual(TestFirst().method(), "hello world?!")
  281. self.assertEqual(TestSecond().method(), "hello world?!")
  282. def test_invalid_non_callable_attribute_decoration(self):
  283. """
  284. @method_decorator on a non-callable attribute raises an error.
  285. """
  286. msg = (
  287. "Cannot decorate 'prop' as it isn't a callable attribute of "
  288. "<class 'Test'> (1)"
  289. )
  290. with self.assertRaisesMessage(TypeError, msg):
  291. @method_decorator(lambda: None, name="prop")
  292. class Test:
  293. prop = 1
  294. @classmethod
  295. def __module__(cls):
  296. return "tests"
  297. def test_invalid_method_name_to_decorate(self):
  298. """
  299. @method_decorator on a nonexistent method raises an error.
  300. """
  301. msg = (
  302. "The keyword argument `name` must be the name of a method of the "
  303. "decorated class: <class 'Test'>. Got 'nonexistent_method' instead"
  304. )
  305. with self.assertRaisesMessage(ValueError, msg):
  306. @method_decorator(lambda: None, name='nonexistent_method')
  307. class Test:
  308. @classmethod
  309. def __module__(cls):
  310. return "tests"
  311. class XFrameOptionsDecoratorsTests(TestCase):
  312. """
  313. Tests for the X-Frame-Options decorators.
  314. """
  315. def test_deny_decorator(self):
  316. """
  317. Ensures @xframe_options_deny properly sets the X-Frame-Options header.
  318. """
  319. @xframe_options_deny
  320. def a_view(request):
  321. return HttpResponse()
  322. r = a_view(HttpRequest())
  323. self.assertEqual(r['X-Frame-Options'], 'DENY')
  324. def test_sameorigin_decorator(self):
  325. """
  326. Ensures @xframe_options_sameorigin properly sets the X-Frame-Options
  327. header.
  328. """
  329. @xframe_options_sameorigin
  330. def a_view(request):
  331. return HttpResponse()
  332. r = a_view(HttpRequest())
  333. self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
  334. def test_exempt_decorator(self):
  335. """
  336. Ensures @xframe_options_exempt properly instructs the
  337. XFrameOptionsMiddleware to NOT set the header.
  338. """
  339. @xframe_options_exempt
  340. def a_view(request):
  341. return HttpResponse()
  342. req = HttpRequest()
  343. resp = a_view(req)
  344. self.assertIsNone(resp.get('X-Frame-Options', None))
  345. self.assertTrue(resp.xframe_options_exempt)
  346. # Since the real purpose of the exempt decorator is to suppress
  347. # the middleware's functionality, let's make sure it actually works...
  348. r = XFrameOptionsMiddleware().process_response(req, resp)
  349. self.assertIsNone(r.get('X-Frame-Options', None))
  350. class NeverCacheDecoratorTest(TestCase):
  351. def test_never_cache_decorator(self):
  352. @never_cache
  353. def a_view(request):
  354. return HttpResponse()
  355. r = a_view(HttpRequest())
  356. self.assertEqual(
  357. set(r['Cache-Control'].split(', ')),
  358. {'max-age=0', 'no-cache', 'no-store', 'must-revalidate'},
  359. )