tests.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import os
  4. import sys
  5. import unittest
  6. from django import template
  7. from django.contrib.auth.models import Group
  8. from django.core import urlresolvers
  9. from django.template import (base as template_base, loader,
  10. Context, RequestContext, Template, TemplateSyntaxError)
  11. from django.template.engine import Engine
  12. from django.template.loaders import app_directories, filesystem
  13. from django.test import RequestFactory, SimpleTestCase
  14. from django.test.utils import override_settings, extend_sys_path
  15. from django.utils._os import upath
  16. class TemplateLoaderTests(SimpleTestCase):
  17. def test_loaders_security(self):
  18. ad_loader = app_directories.Loader(Engine.get_default())
  19. fs_loader = filesystem.Loader(Engine.get_default())
  20. def test_template_sources(path, template_dirs, expected_sources):
  21. if isinstance(expected_sources, list):
  22. # Fix expected sources so they are abspathed
  23. expected_sources = [os.path.abspath(s) for s in expected_sources]
  24. # Test the two loaders (app_directores and filesystem).
  25. func1 = lambda p, t: list(ad_loader.get_template_sources(p, t))
  26. func2 = lambda p, t: list(fs_loader.get_template_sources(p, t))
  27. for func in (func1, func2):
  28. if isinstance(expected_sources, list):
  29. self.assertEqual(func(path, template_dirs), expected_sources)
  30. else:
  31. self.assertRaises(expected_sources, func, path, template_dirs)
  32. template_dirs = ['/dir1', '/dir2']
  33. test_template_sources('index.html', template_dirs,
  34. ['/dir1/index.html', '/dir2/index.html'])
  35. test_template_sources('/etc/passwd', template_dirs, [])
  36. test_template_sources('etc/passwd', template_dirs,
  37. ['/dir1/etc/passwd', '/dir2/etc/passwd'])
  38. test_template_sources('../etc/passwd', template_dirs, [])
  39. test_template_sources('../../../etc/passwd', template_dirs, [])
  40. test_template_sources('/dir1/index.html', template_dirs,
  41. ['/dir1/index.html'])
  42. test_template_sources('../dir2/index.html', template_dirs,
  43. ['/dir2/index.html'])
  44. test_template_sources('/dir1blah', template_dirs, [])
  45. test_template_sources('../dir1blah', template_dirs, [])
  46. # UTF-8 bytestrings are permitted.
  47. test_template_sources(b'\xc3\x85ngstr\xc3\xb6m', template_dirs,
  48. ['/dir1/Ångström', '/dir2/Ångström'])
  49. # Unicode strings are permitted.
  50. test_template_sources('Ångström', template_dirs,
  51. ['/dir1/Ångström', '/dir2/Ångström'])
  52. test_template_sources('Ångström', [b'/Stra\xc3\x9fe'], ['/Straße/Ångström'])
  53. test_template_sources(b'\xc3\x85ngstr\xc3\xb6m', [b'/Stra\xc3\x9fe'],
  54. ['/Straße/Ångström'])
  55. # Invalid UTF-8 encoding in bytestrings is not. Should raise a
  56. # semi-useful error message.
  57. test_template_sources(b'\xc3\xc3', template_dirs, UnicodeDecodeError)
  58. # Case insensitive tests (for win32). Not run unless we're on
  59. # a case insensitive operating system.
  60. if os.path.normcase('/TEST') == os.path.normpath('/test'):
  61. template_dirs = ['/dir1', '/DIR2']
  62. test_template_sources('index.html', template_dirs,
  63. ['/dir1/index.html', '/DIR2/index.html'])
  64. test_template_sources('/DIR1/index.HTML', template_dirs,
  65. ['/DIR1/index.HTML'])
  66. @override_settings(TEMPLATE_LOADERS=['django.template.loaders.filesystem.Loader'])
  67. # Turn TEMPLATE_DEBUG on, so that the origin file name will be kept with
  68. # the compiled templates.
  69. @override_settings(TEMPLATE_DEBUG=True)
  70. def test_loader_debug_origin(self):
  71. # We rely on the fact that runtests.py sets up TEMPLATE_DIRS to
  72. # point to a directory containing a login.html file.
  73. load_name = 'login.html'
  74. # We also rely on the fact the file system and app directories loaders
  75. # both inherit the load_template method from the base Loader class, so
  76. # we only need to test one of them.
  77. template = loader.get_template(load_name).template
  78. template_name = template.nodelist[0].source[0].name
  79. self.assertTrue(template_name.endswith(load_name),
  80. 'Template loaded by filesystem loader has incorrect name for debug page: %s' % template_name)
  81. @override_settings(TEMPLATE_LOADERS=[
  82. ('django.template.loaders.cached.Loader',
  83. ['django.template.loaders.filesystem.Loader']),
  84. ])
  85. @override_settings(TEMPLATE_DEBUG=True)
  86. def test_cached_loader_debug_origin(self):
  87. # Same comment as in test_loader_debug_origin.
  88. load_name = 'login.html'
  89. # Test the cached loader separately since it overrides load_template.
  90. template = loader.get_template(load_name).template
  91. template_name = template.nodelist[0].source[0].name
  92. self.assertTrue(template_name.endswith(load_name),
  93. 'Template loaded through cached loader has incorrect name for debug page: %s' % template_name)
  94. template = loader.get_template(load_name).template
  95. template_name = template.nodelist[0].source[0].name
  96. self.assertTrue(template_name.endswith(load_name),
  97. 'Cached template loaded through cached loader has incorrect name for debug page: %s' % template_name)
  98. @override_settings(TEMPLATE_DEBUG=True)
  99. def test_loader_origin(self):
  100. template = loader.get_template('login.html')
  101. self.assertEqual(template.origin.loadname, 'login.html')
  102. @override_settings(TEMPLATE_DEBUG=True)
  103. def test_string_origin(self):
  104. template = Template('string template')
  105. self.assertEqual(template.origin.source, 'string template')
  106. def test_debug_false_origin(self):
  107. template = loader.get_template('login.html')
  108. self.assertEqual(template.origin, None)
  109. # TEMPLATE_DEBUG must be true, otherwise the exception raised
  110. # during {% include %} processing will be suppressed.
  111. @override_settings(TEMPLATE_DEBUG=True)
  112. # Test the base loader class via the app loader. load_template
  113. # from base is used by all shipped loaders excepting cached,
  114. # which has its own test.
  115. @override_settings(TEMPLATE_LOADERS=['django.template.loaders.app_directories.Loader'])
  116. def test_include_missing_template(self):
  117. """
  118. Tests that the correct template is identified as not existing
  119. when {% include %} specifies a template that does not exist.
  120. """
  121. load_name = 'test_include_error.html'
  122. r = None
  123. try:
  124. tmpl = loader.select_template([load_name])
  125. r = tmpl.render(template.Context({}))
  126. except template.TemplateDoesNotExist as e:
  127. self.assertEqual(e.args[0], 'missing.html')
  128. self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
  129. # TEMPLATE_DEBUG must be true, otherwise the exception raised
  130. # during {% include %} processing will be suppressed.
  131. @override_settings(TEMPLATE_DEBUG=True)
  132. # Test the base loader class via the app loader. load_template
  133. # from base is used by all shipped loaders excepting cached,
  134. # which has its own test.
  135. @override_settings(TEMPLATE_LOADERS=['django.template.loaders.app_directories.Loader'])
  136. def test_extends_include_missing_baseloader(self):
  137. """
  138. Tests that the correct template is identified as not existing
  139. when {% extends %} specifies a template that does exist, but
  140. that template has an {% include %} of something that does not
  141. exist. See #12787.
  142. """
  143. load_name = 'test_extends_error.html'
  144. tmpl = loader.get_template(load_name)
  145. r = None
  146. try:
  147. r = tmpl.render(template.Context({}))
  148. except template.TemplateDoesNotExist as e:
  149. self.assertEqual(e.args[0], 'missing.html')
  150. self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
  151. @override_settings(TEMPLATE_DEBUG=True)
  152. def test_extends_include_missing_cachedloader(self):
  153. """
  154. Same as test_extends_include_missing_baseloader, only tests
  155. behavior of the cached loader instead of base loader.
  156. """
  157. with override_settings(TEMPLATE_LOADERS=[
  158. ('django.template.loaders.cached.Loader', [
  159. 'django.template.loaders.app_directories.Loader',
  160. ]),
  161. ]):
  162. load_name = 'test_extends_error.html'
  163. tmpl = loader.get_template(load_name)
  164. r = None
  165. try:
  166. r = tmpl.render(template.Context({}))
  167. except template.TemplateDoesNotExist as e:
  168. self.assertEqual(e.args[0], 'missing.html')
  169. self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
  170. # For the cached loader, repeat the test, to ensure the first attempt did not cache a
  171. # result that behaves incorrectly on subsequent attempts.
  172. tmpl = loader.get_template(load_name)
  173. try:
  174. tmpl.render(template.Context({}))
  175. except template.TemplateDoesNotExist as e:
  176. self.assertEqual(e.args[0], 'missing.html')
  177. self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
  178. def test_include_template_argument(self):
  179. """
  180. Support any render() supporting object
  181. """
  182. ctx = Context({
  183. 'tmpl': Template('This worked!'),
  184. })
  185. outer_tmpl = Template('{% include tmpl %}')
  186. output = outer_tmpl.render(ctx)
  187. self.assertEqual(output, 'This worked!')
  188. @override_settings(TEMPLATE_DEBUG=True)
  189. def test_include_immediate_missing(self):
  190. """
  191. Regression test for #16417 -- {% include %} tag raises TemplateDoesNotExist at compile time if TEMPLATE_DEBUG is True
  192. Test that an {% include %} tag with a literal string referencing a
  193. template that does not exist does not raise an exception at parse
  194. time.
  195. """
  196. tmpl = Template('{% include "this_does_not_exist.html" %}')
  197. self.assertIsInstance(tmpl, Template)
  198. @override_settings(TEMPLATE_DEBUG=True)
  199. def test_include_recursive(self):
  200. comments = [
  201. {
  202. 'comment': 'A1',
  203. 'children': [
  204. {'comment': 'B1', 'children': []},
  205. {'comment': 'B2', 'children': []},
  206. {'comment': 'B3', 'children': [
  207. {'comment': 'C1', 'children': []}
  208. ]},
  209. ]
  210. }
  211. ]
  212. t = loader.get_template('recursive_include.html')
  213. self.assertEqual(
  214. "Recursion! A1 Recursion! B1 B2 B3 Recursion! C1",
  215. t.render(Context({'comments': comments})).replace(' ', '').replace('\n', ' ').strip(),
  216. )
  217. class TemplateRegressionTests(SimpleTestCase):
  218. def test_token_smart_split(self):
  219. # Regression test for #7027
  220. token = template_base.Token(template_base.TOKEN_BLOCK, 'sometag _("Page not found") value|yesno:_("yes,no")')
  221. split = token.split_contents()
  222. self.assertEqual(split, ["sometag", '_("Page not found")', 'value|yesno:_("yes,no")'])
  223. @override_settings(SETTINGS_MODULE=None, TEMPLATE_DEBUG=True)
  224. def test_url_reverse_no_settings_module(self):
  225. # Regression test for #9005
  226. t = Template('{% url will_not_match %}')
  227. c = Context()
  228. with self.assertRaises(urlresolvers.NoReverseMatch):
  229. t.render(c)
  230. @override_settings(TEMPLATE_STRING_IF_INVALID='%s is invalid', SETTINGS_MODULE='also_something')
  231. def test_url_reverse_view_name(self):
  232. # Regression test for #19827
  233. t = Template('{% url will_not_match %}')
  234. c = Context()
  235. try:
  236. t.render(c)
  237. except urlresolvers.NoReverseMatch:
  238. tb = sys.exc_info()[2]
  239. depth = 0
  240. while tb.tb_next is not None:
  241. tb = tb.tb_next
  242. depth += 1
  243. self.assertGreater(depth, 5,
  244. "The traceback context was lost when reraising the traceback. See #19827")
  245. @override_settings(DEBUG=True, TEMPLATE_DEBUG=True)
  246. def test_no_wrapped_exception(self):
  247. """
  248. The template system doesn't wrap exceptions, but annotates them.
  249. Refs #16770
  250. """
  251. c = Context({"coconuts": lambda: 42 / 0})
  252. t = Template("{{ coconuts }}")
  253. with self.assertRaises(ZeroDivisionError) as cm:
  254. t.render(c)
  255. self.assertEqual(cm.exception.django_template_source[1], (0, 14))
  256. def test_invalid_block_suggestion(self):
  257. # See #7876
  258. try:
  259. Template("{% if 1 %}lala{% endblock %}{% endif %}")
  260. except TemplateSyntaxError as e:
  261. self.assertEqual(e.args[0], "Invalid block tag: 'endblock', expected 'elif', 'else' or 'endif'")
  262. def test_ifchanged_concurrency(self):
  263. # Tests for #15849
  264. template = Template('[0{% for x in foo %},{% with var=get_value %}{% ifchanged %}{{ var }}{% endifchanged %}{% endwith %}{% endfor %}]')
  265. # Using generator to mimic concurrency.
  266. # The generator is not passed to the 'for' loop, because it does a list(values)
  267. # instead, call gen.next() in the template to control the generator.
  268. def gen():
  269. yield 1
  270. yield 2
  271. # Simulate that another thread is now rendering.
  272. # When the IfChangeNode stores state at 'self' it stays at '3' and skip the last yielded value below.
  273. iter2 = iter([1, 2, 3])
  274. output2 = template.render(Context({'foo': range(3), 'get_value': lambda: next(iter2)}))
  275. self.assertEqual(output2, '[0,1,2,3]', 'Expected [0,1,2,3] in second parallel template, got {}'.format(output2))
  276. yield 3
  277. gen1 = gen()
  278. output1 = template.render(Context({'foo': range(3), 'get_value': lambda: next(gen1)}))
  279. self.assertEqual(output1, '[0,1,2,3]', 'Expected [0,1,2,3] in first template, got {}'.format(output1))
  280. def test_cache_regression_20130(self):
  281. t = Template('{% load cache %}{% cache 1 regression_20130 %}foo{% endcache %}')
  282. cachenode = t.nodelist[1]
  283. self.assertEqual(cachenode.fragment_name, 'regression_20130')
  284. @override_settings(CACHES={
  285. 'default': {
  286. 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
  287. 'LOCATION': 'default',
  288. },
  289. 'template_fragments': {
  290. 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
  291. 'LOCATION': 'fragments',
  292. },
  293. })
  294. def test_cache_fragment_cache(self):
  295. """
  296. When a cache called "template_fragments" is present, the cache tag
  297. will use it in preference to 'default'
  298. """
  299. t1 = Template('{% load cache %}{% cache 1 fragment %}foo{% endcache %}')
  300. t2 = Template('{% load cache %}{% cache 1 fragment using="default" %}bar{% endcache %}')
  301. ctx = Context()
  302. o1 = t1.render(ctx)
  303. o2 = t2.render(ctx)
  304. self.assertEqual(o1, 'foo')
  305. self.assertEqual(o2, 'bar')
  306. def test_cache_missing_backend(self):
  307. """
  308. When a cache that doesn't exist is specified, the cache tag will
  309. raise a TemplateSyntaxError
  310. '"""
  311. t = Template('{% load cache %}{% cache 1 backend using="unknown" %}bar{% endcache %}')
  312. ctx = Context()
  313. with self.assertRaises(TemplateSyntaxError):
  314. t.render(ctx)
  315. def test_ifchanged_render_once(self):
  316. """ Test for ticket #19890. The content of ifchanged template tag was
  317. rendered twice."""
  318. template = Template('{% ifchanged %}{% cycle "1st time" "2nd time" %}{% endifchanged %}')
  319. output = template.render(Context({}))
  320. self.assertEqual(output, '1st time')
  321. def test_super_errors(self):
  322. """
  323. Test behavior of the raise errors into included blocks.
  324. See #18169
  325. """
  326. t = loader.get_template('included_content.html')
  327. with self.assertRaises(urlresolvers.NoReverseMatch):
  328. t.render(Context({}))
  329. def test_debug_tag_non_ascii(self):
  330. """
  331. Test non-ASCII model representation in debug output (#23060).
  332. """
  333. Group.objects.create(name="清風")
  334. c1 = Context({"objs": Group.objects.all()})
  335. t1 = Template('{% debug %}')
  336. self.assertIn("清風", t1.render(c1))
  337. class TemplateTagLoading(SimpleTestCase):
  338. def setUp(self):
  339. self.egg_dir = '%s/eggs' % os.path.dirname(upath(__file__))
  340. def test_load_error(self):
  341. ttext = "{% load broken_tag %}"
  342. self.assertRaises(template.TemplateSyntaxError, template.Template, ttext)
  343. try:
  344. template.Template(ttext)
  345. except template.TemplateSyntaxError as e:
  346. self.assertIn('ImportError', e.args[0])
  347. self.assertIn('Xtemplate', e.args[0])
  348. def test_load_error_egg(self):
  349. ttext = "{% load broken_egg %}"
  350. egg_name = '%s/tagsegg.egg' % self.egg_dir
  351. with extend_sys_path(egg_name):
  352. with self.assertRaises(template.TemplateSyntaxError):
  353. with self.settings(INSTALLED_APPS=['tagsegg']):
  354. template.Template(ttext)
  355. try:
  356. with self.settings(INSTALLED_APPS=['tagsegg']):
  357. template.Template(ttext)
  358. except template.TemplateSyntaxError as e:
  359. self.assertIn('ImportError', e.args[0])
  360. self.assertIn('Xtemplate', e.args[0])
  361. def test_load_working_egg(self):
  362. ttext = "{% load working_egg %}"
  363. egg_name = '%s/tagsegg.egg' % self.egg_dir
  364. with extend_sys_path(egg_name):
  365. with self.settings(INSTALLED_APPS=['tagsegg']):
  366. template.Template(ttext)
  367. class RequestContextTests(unittest.TestCase):
  368. def setUp(self):
  369. self.fake_request = RequestFactory().get('/')
  370. @override_settings(TEMPLATE_LOADERS=[
  371. ('django.template.loaders.locmem.Loader', {
  372. 'child': '{{ var|default:"none" }}',
  373. }),
  374. ])
  375. def test_include_only(self):
  376. """
  377. Regression test for #15721, ``{% include %}`` and ``RequestContext``
  378. not playing together nicely.
  379. """
  380. ctx = RequestContext(self.fake_request, {'var': 'parent'})
  381. self.assertEqual(
  382. template.Template('{% include "child" %}').render(ctx),
  383. 'parent'
  384. )
  385. self.assertEqual(
  386. template.Template('{% include "child" only %}').render(ctx),
  387. 'none'
  388. )
  389. def test_stack_size(self):
  390. """
  391. Regression test for #7116, Optimize RequetsContext construction
  392. """
  393. ctx = RequestContext(self.fake_request, {})
  394. # The stack should now contain 3 items:
  395. # [builtins, supplied context, context processor]
  396. self.assertEqual(len(ctx.dicts), 3)
  397. @override_settings(TEMPLATE_CONTEXT_PROCESSORS=())
  398. def test_context_comparable(self):
  399. test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}}
  400. # test comparing RequestContext to prevent problems if somebody
  401. # adds __eq__ in the future
  402. request = RequestFactory().get('/')
  403. self.assertEqual(
  404. RequestContext(request, dict_=test_data),
  405. RequestContext(request, dict_=test_data)
  406. )
  407. class SSITests(SimpleTestCase):
  408. def setUp(self):
  409. self.this_dir = os.path.dirname(os.path.abspath(upath(__file__)))
  410. self.ssi_dir = os.path.join(self.this_dir, "templates", "first")
  411. self.engine = Engine(allowed_include_roots=(self.ssi_dir,))
  412. def render_ssi(self, path):
  413. # the path must exist for the test to be reliable
  414. self.assertTrue(os.path.exists(path))
  415. return self.engine.from_string('{%% ssi "%s" %%}' % path).render(Context({}))
  416. def test_allowed_paths(self):
  417. acceptable_path = os.path.join(self.ssi_dir, "..", "first", "test.html")
  418. self.assertEqual(self.render_ssi(acceptable_path), 'First template\n')
  419. def test_relative_include_exploit(self):
  420. """
  421. May not bypass allowed_include_roots with relative paths
  422. e.g. if allowed_include_roots = ("/var/www",), it should not be
  423. possible to do {% ssi "/var/www/../../etc/passwd" %}
  424. """
  425. disallowed_paths = [
  426. os.path.join(self.ssi_dir, "..", "ssi_include.html"),
  427. os.path.join(self.ssi_dir, "..", "second", "test.html"),
  428. ]
  429. for disallowed_path in disallowed_paths:
  430. self.assertEqual(self.render_ssi(disallowed_path), '')