tests.py 21 KB

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