tests.py 14 KB

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