test_custom.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. import os
  2. from django.template import Context, Engine, TemplateSyntaxError
  3. from django.template.base import Node
  4. from django.template.library import InvalidTemplateLibrary
  5. from django.test import SimpleTestCase
  6. from django.test.utils import extend_sys_path
  7. from .templatetags import custom, inclusion
  8. from .utils import ROOT
  9. LIBRARIES = {
  10. 'custom': 'template_tests.templatetags.custom',
  11. 'inclusion': 'template_tests.templatetags.inclusion',
  12. }
  13. class CustomFilterTests(SimpleTestCase):
  14. def test_filter(self):
  15. engine = Engine(libraries=LIBRARIES)
  16. t = engine.from_string("{% load custom %}{{ string|trim:5 }}")
  17. self.assertEqual(
  18. t.render(Context({"string": "abcdefghijklmnopqrstuvwxyz"})),
  19. "abcde"
  20. )
  21. class TagTestCase(SimpleTestCase):
  22. @classmethod
  23. def setUpClass(cls):
  24. cls.engine = Engine(app_dirs=True, libraries=LIBRARIES)
  25. super(TagTestCase, cls).setUpClass()
  26. def verify_tag(self, tag, name):
  27. self.assertEqual(tag.__name__, name)
  28. self.assertEqual(tag.__doc__, 'Expected %s __doc__' % name)
  29. self.assertEqual(tag.__dict__['anything'], 'Expected %s __dict__' % name)
  30. class SimpleTagTests(TagTestCase):
  31. def test_simple_tags(self):
  32. c = Context({'value': 42})
  33. templates = [
  34. ('{% load custom %}{% no_params %}', 'no_params - Expected result'),
  35. ('{% load custom %}{% one_param 37 %}', 'one_param - Expected result: 37'),
  36. ('{% load custom %}{% explicit_no_context 37 %}', 'explicit_no_context - Expected result: 37'),
  37. ('{% load custom %}{% no_params_with_context %}',
  38. 'no_params_with_context - Expected result (context value: 42)'),
  39. ('{% load custom %}{% params_and_context 37 %}',
  40. 'params_and_context - Expected result (context value: 42): 37'),
  41. ('{% load custom %}{% simple_two_params 37 42 %}', 'simple_two_params - Expected result: 37, 42'),
  42. ('{% load custom %}{% simple_one_default 37 %}', 'simple_one_default - Expected result: 37, hi'),
  43. ('{% load custom %}{% simple_one_default 37 two="hello" %}',
  44. 'simple_one_default - Expected result: 37, hello'),
  45. ('{% load custom %}{% simple_one_default one=99 two="hello" %}',
  46. 'simple_one_default - Expected result: 99, hello'),
  47. ('{% load custom %}{% simple_one_default 37 42 %}',
  48. 'simple_one_default - Expected result: 37, 42'),
  49. ('{% load custom %}{% simple_unlimited_args 37 %}', 'simple_unlimited_args - Expected result: 37, hi'),
  50. ('{% load custom %}{% simple_unlimited_args 37 42 56 89 %}',
  51. 'simple_unlimited_args - Expected result: 37, 42, 56, 89'),
  52. ('{% load custom %}{% simple_only_unlimited_args %}', 'simple_only_unlimited_args - Expected result: '),
  53. ('{% load custom %}{% simple_only_unlimited_args 37 42 56 89 %}',
  54. 'simple_only_unlimited_args - Expected result: 37, 42, 56, 89'),
  55. ('{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}',
  56. 'simple_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4'),
  57. ]
  58. for entry in templates:
  59. t = self.engine.from_string(entry[0])
  60. self.assertEqual(t.render(c), entry[1])
  61. for entry in templates:
  62. t = self.engine.from_string("%s as var %%}Result: {{ var }}" % entry[0][0:-2])
  63. self.assertEqual(t.render(c), "Result: %s" % entry[1])
  64. def test_simple_tag_errors(self):
  65. errors = [
  66. ("'simple_one_default' received unexpected keyword argument 'three'",
  67. '{% load custom %}{% simple_one_default 99 two="hello" three="foo" %}'),
  68. ("'simple_two_params' received too many positional arguments",
  69. '{% load custom %}{% simple_two_params 37 42 56 %}'),
  70. ("'simple_one_default' received too many positional arguments",
  71. '{% load custom %}{% simple_one_default 37 42 56 %}'),
  72. ("'simple_unlimited_args_kwargs' received some positional argument(s) after some keyword argument(s)",
  73. '{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 %}'),
  74. ("'simple_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'",
  75. '{% load custom %}{% simple_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}'),
  76. ]
  77. for entry in errors:
  78. with self.assertRaisesMessage(TemplateSyntaxError, entry[0]):
  79. self.engine.from_string(entry[1])
  80. for entry in errors:
  81. with self.assertRaisesMessage(TemplateSyntaxError, entry[0]):
  82. self.engine.from_string("%s as var %%}" % entry[1][0:-2])
  83. def test_simple_tag_escaping_autoescape_off(self):
  84. c = Context({'name': "Jack & Jill"}, autoescape=False)
  85. t = self.engine.from_string("{% load custom %}{% escape_naive %}")
  86. self.assertEqual(t.render(c), "Hello Jack & Jill!")
  87. def test_simple_tag_naive_escaping(self):
  88. c = Context({'name': "Jack & Jill"})
  89. t = self.engine.from_string("{% load custom %}{% escape_naive %}")
  90. self.assertEqual(t.render(c), "Hello Jack & Jill!")
  91. def test_simple_tag_explicit_escaping(self):
  92. # Check we don't double escape
  93. c = Context({'name': "Jack & Jill"})
  94. t = self.engine.from_string("{% load custom %}{% escape_explicit %}")
  95. self.assertEqual(t.render(c), "Hello Jack & Jill!")
  96. def test_simple_tag_format_html_escaping(self):
  97. # Check we don't double escape
  98. c = Context({'name': "Jack & Jill"})
  99. t = self.engine.from_string("{% load custom %}{% escape_format_html %}")
  100. self.assertEqual(t.render(c), "Hello Jack & Jill!")
  101. def test_simple_tag_registration(self):
  102. # The decorators preserve the decorated function's docstring, name,
  103. # and attributes.
  104. self.verify_tag(custom.no_params, 'no_params')
  105. self.verify_tag(custom.one_param, 'one_param')
  106. self.verify_tag(custom.explicit_no_context, 'explicit_no_context')
  107. self.verify_tag(custom.no_params_with_context, 'no_params_with_context')
  108. self.verify_tag(custom.params_and_context, 'params_and_context')
  109. self.verify_tag(custom.simple_unlimited_args_kwargs, 'simple_unlimited_args_kwargs')
  110. self.verify_tag(custom.simple_tag_without_context_parameter, 'simple_tag_without_context_parameter')
  111. def test_simple_tag_missing_context(self):
  112. # The 'context' parameter must be present when takes_context is True
  113. msg = (
  114. "'simple_tag_without_context_parameter' is decorated with "
  115. "takes_context=True so it must have a first argument of 'context'"
  116. )
  117. with self.assertRaisesMessage(TemplateSyntaxError, msg):
  118. self.engine.from_string('{% load custom %}{% simple_tag_without_context_parameter 123 %}')
  119. class InclusionTagTests(TagTestCase):
  120. def test_inclusion_tags(self):
  121. c = Context({'value': 42})
  122. templates = [
  123. ('{% load inclusion %}{% inclusion_no_params %}', 'inclusion_no_params - Expected result\n'),
  124. ('{% load inclusion %}{% inclusion_one_param 37 %}', 'inclusion_one_param - Expected result: 37\n'),
  125. ('{% load inclusion %}{% inclusion_explicit_no_context 37 %}',
  126. 'inclusion_explicit_no_context - Expected result: 37\n'),
  127. ('{% load inclusion %}{% inclusion_no_params_with_context %}',
  128. 'inclusion_no_params_with_context - Expected result (context value: 42)\n'),
  129. ('{% load inclusion %}{% inclusion_params_and_context 37 %}',
  130. 'inclusion_params_and_context - Expected result (context value: 42): 37\n'),
  131. ('{% load inclusion %}{% inclusion_two_params 37 42 %}',
  132. 'inclusion_two_params - Expected result: 37, 42\n'),
  133. (
  134. '{% load inclusion %}{% inclusion_one_default 37 %}',
  135. 'inclusion_one_default - Expected result: 37, hi\n'
  136. ),
  137. ('{% load inclusion %}{% inclusion_one_default 37 two="hello" %}',
  138. 'inclusion_one_default - Expected result: 37, hello\n'),
  139. ('{% load inclusion %}{% inclusion_one_default one=99 two="hello" %}',
  140. 'inclusion_one_default - Expected result: 99, hello\n'),
  141. ('{% load inclusion %}{% inclusion_one_default 37 42 %}',
  142. 'inclusion_one_default - Expected result: 37, 42\n'),
  143. ('{% load inclusion %}{% inclusion_unlimited_args 37 %}',
  144. 'inclusion_unlimited_args - Expected result: 37, hi\n'),
  145. ('{% load inclusion %}{% inclusion_unlimited_args 37 42 56 89 %}',
  146. 'inclusion_unlimited_args - Expected result: 37, 42, 56, 89\n'),
  147. ('{% load inclusion %}{% inclusion_only_unlimited_args %}',
  148. 'inclusion_only_unlimited_args - Expected result: \n'),
  149. ('{% load inclusion %}{% inclusion_only_unlimited_args 37 42 56 89 %}',
  150. 'inclusion_only_unlimited_args - Expected result: 37, 42, 56, 89\n'),
  151. ('{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}',
  152. 'inclusion_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4\n'),
  153. ]
  154. for entry in templates:
  155. t = self.engine.from_string(entry[0])
  156. self.assertEqual(t.render(c), entry[1])
  157. def test_inclusion_tag_errors(self):
  158. errors = [
  159. ("'inclusion_one_default' received unexpected keyword argument 'three'",
  160. '{% load inclusion %}{% inclusion_one_default 99 two="hello" three="foo" %}'),
  161. ("'inclusion_two_params' received too many positional arguments",
  162. '{% load inclusion %}{% inclusion_two_params 37 42 56 %}'),
  163. ("'inclusion_one_default' received too many positional arguments",
  164. '{% load inclusion %}{% inclusion_one_default 37 42 56 %}'),
  165. ("'inclusion_one_default' did not receive value(s) for the argument(s): 'one'",
  166. '{% load inclusion %}{% inclusion_one_default %}'),
  167. ("'inclusion_unlimited_args' did not receive value(s) for the argument(s): 'one'",
  168. '{% load inclusion %}{% inclusion_unlimited_args %}'),
  169. (
  170. "'inclusion_unlimited_args_kwargs' received some positional argument(s) "
  171. "after some keyword argument(s)",
  172. '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 40|add:2 eggs="boiled" 56 four=1|add:3 %}',
  173. ),
  174. ("'inclusion_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'",
  175. '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}'),
  176. ]
  177. for entry in errors:
  178. with self.assertRaisesMessage(TemplateSyntaxError, entry[0]):
  179. self.engine.from_string(entry[1])
  180. def test_include_tag_missing_context(self):
  181. # The 'context' parameter must be present when takes_context is True
  182. msg = (
  183. "'inclusion_tag_without_context_parameter' is decorated with "
  184. "takes_context=True so it must have a first argument of 'context'"
  185. )
  186. with self.assertRaisesMessage(TemplateSyntaxError, msg):
  187. self.engine.from_string('{% load inclusion %}{% inclusion_tag_without_context_parameter 123 %}')
  188. def test_inclusion_tags_from_template(self):
  189. c = Context({'value': 42})
  190. templates = [
  191. ('{% load inclusion %}{% inclusion_no_params_from_template %}',
  192. 'inclusion_no_params_from_template - Expected result\n'),
  193. ('{% load inclusion %}{% inclusion_one_param_from_template 37 %}',
  194. 'inclusion_one_param_from_template - Expected result: 37\n'),
  195. ('{% load inclusion %}{% inclusion_explicit_no_context_from_template 37 %}',
  196. 'inclusion_explicit_no_context_from_template - Expected result: 37\n'),
  197. ('{% load inclusion %}{% inclusion_no_params_with_context_from_template %}',
  198. 'inclusion_no_params_with_context_from_template - Expected result (context value: 42)\n'),
  199. ('{% load inclusion %}{% inclusion_params_and_context_from_template 37 %}',
  200. 'inclusion_params_and_context_from_template - Expected result (context value: 42): 37\n'),
  201. ('{% load inclusion %}{% inclusion_two_params_from_template 37 42 %}',
  202. 'inclusion_two_params_from_template - Expected result: 37, 42\n'),
  203. ('{% load inclusion %}{% inclusion_one_default_from_template 37 %}',
  204. 'inclusion_one_default_from_template - Expected result: 37, hi\n'),
  205. ('{% load inclusion %}{% inclusion_one_default_from_template 37 42 %}',
  206. 'inclusion_one_default_from_template - Expected result: 37, 42\n'),
  207. ('{% load inclusion %}{% inclusion_unlimited_args_from_template 37 %}',
  208. 'inclusion_unlimited_args_from_template - Expected result: 37, hi\n'),
  209. ('{% load inclusion %}{% inclusion_unlimited_args_from_template 37 42 56 89 %}',
  210. 'inclusion_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n'),
  211. ('{% load inclusion %}{% inclusion_only_unlimited_args_from_template %}',
  212. 'inclusion_only_unlimited_args_from_template - Expected result: \n'),
  213. ('{% load inclusion %}{% inclusion_only_unlimited_args_from_template 37 42 56 89 %}',
  214. 'inclusion_only_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n'),
  215. ]
  216. for entry in templates:
  217. t = self.engine.from_string(entry[0])
  218. self.assertEqual(t.render(c), entry[1])
  219. def test_inclusion_tag_registration(self):
  220. # The decorators preserve the decorated function's docstring, name,
  221. # and attributes.
  222. self.verify_tag(inclusion.inclusion_no_params, 'inclusion_no_params')
  223. self.verify_tag(inclusion.inclusion_one_param, 'inclusion_one_param')
  224. self.verify_tag(inclusion.inclusion_explicit_no_context, 'inclusion_explicit_no_context')
  225. self.verify_tag(inclusion.inclusion_no_params_with_context, 'inclusion_no_params_with_context')
  226. self.verify_tag(inclusion.inclusion_params_and_context, 'inclusion_params_and_context')
  227. self.verify_tag(inclusion.inclusion_two_params, 'inclusion_two_params')
  228. self.verify_tag(inclusion.inclusion_one_default, 'inclusion_one_default')
  229. self.verify_tag(inclusion.inclusion_unlimited_args, 'inclusion_unlimited_args')
  230. self.verify_tag(inclusion.inclusion_only_unlimited_args, 'inclusion_only_unlimited_args')
  231. self.verify_tag(inclusion.inclusion_tag_without_context_parameter, 'inclusion_tag_without_context_parameter')
  232. self.verify_tag(inclusion.inclusion_tag_use_l10n, 'inclusion_tag_use_l10n')
  233. self.verify_tag(inclusion.inclusion_unlimited_args_kwargs, 'inclusion_unlimited_args_kwargs')
  234. def test_15070_use_l10n(self):
  235. """
  236. Inclusion tag passes down `use_l10n` of context to the
  237. Context of the included/rendered template as well.
  238. """
  239. c = Context({})
  240. t = self.engine.from_string('{% load inclusion %}{% inclusion_tag_use_l10n %}')
  241. self.assertEqual(t.render(c).strip(), 'None')
  242. c.use_l10n = True
  243. self.assertEqual(t.render(c).strip(), 'True')
  244. def test_no_render_side_effect(self):
  245. """
  246. #23441 -- InclusionNode shouldn't modify its nodelist at render time.
  247. """
  248. engine = Engine(app_dirs=True, libraries=LIBRARIES)
  249. template = engine.from_string('{% load inclusion %}{% inclusion_no_params %}')
  250. count = template.nodelist.get_nodes_by_type(Node)
  251. template.render(Context({}))
  252. self.assertEqual(template.nodelist.get_nodes_by_type(Node), count)
  253. def test_render_context_is_cleared(self):
  254. """
  255. #24555 -- InclusionNode should push and pop the render_context stack
  256. when rendering. Otherwise, leftover values such as blocks from
  257. extending can interfere with subsequent rendering.
  258. """
  259. engine = Engine(app_dirs=True, libraries=LIBRARIES)
  260. template = engine.from_string('{% load inclusion %}{% inclusion_extends1 %}{% inclusion_extends2 %}')
  261. self.assertEqual(template.render(Context({})).strip(), 'one\ntwo')
  262. class TemplateTagLoadingTests(SimpleTestCase):
  263. @classmethod
  264. def setUpClass(cls):
  265. cls.egg_dir = os.path.join(ROOT, 'eggs')
  266. super(TemplateTagLoadingTests, cls).setUpClass()
  267. def test_load_error(self):
  268. msg = (
  269. "Invalid template library specified. ImportError raised when "
  270. "trying to load 'template_tests.broken_tag': cannot import name "
  271. "'Xtemplate'"
  272. )
  273. with self.assertRaisesMessage(InvalidTemplateLibrary, msg):
  274. Engine(libraries={'broken_tag': 'template_tests.broken_tag'})
  275. def test_load_error_egg(self):
  276. egg_name = '%s/tagsegg.egg' % self.egg_dir
  277. msg = (
  278. "Invalid template library specified. ImportError raised when "
  279. "trying to load 'tagsegg.templatetags.broken_egg': cannot "
  280. "import name 'Xtemplate'"
  281. )
  282. with extend_sys_path(egg_name):
  283. with self.assertRaisesMessage(InvalidTemplateLibrary, msg):
  284. Engine(libraries={'broken_egg': 'tagsegg.templatetags.broken_egg'})
  285. def test_load_working_egg(self):
  286. ttext = "{% load working_egg %}"
  287. egg_name = '%s/tagsegg.egg' % self.egg_dir
  288. with extend_sys_path(egg_name):
  289. engine = Engine(libraries={
  290. 'working_egg': 'tagsegg.templatetags.working_egg',
  291. })
  292. engine.from_string(ttext)
  293. def test_load_annotated_function(self):
  294. Engine(libraries={
  295. 'annotated_tag_function': 'template_tests.annotated_tag_function',
  296. })