tests.py 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from django.conf import settings
  4. if __name__ == '__main__':
  5. # When running this file in isolation, we need to set up the configuration
  6. # before importing 'template'.
  7. settings.configure()
  8. from datetime import date, datetime
  9. import os
  10. import sys
  11. import traceback
  12. import unittest
  13. import warnings
  14. from django import template
  15. from django.core import urlresolvers
  16. from django.template import (base as template_base, loader, Context,
  17. RequestContext, Template, TemplateSyntaxError)
  18. from django.template.loaders import app_directories, filesystem, cached
  19. from django.test import RequestFactory, TestCase
  20. from django.test.utils import (setup_test_template_loader,
  21. restore_template_loaders, override_settings, TransRealMixin)
  22. from django.utils.encoding import python_2_unicode_compatible
  23. from django.utils.formats import date_format
  24. from django.utils._os import upath
  25. from django.utils.translation import activate, deactivate
  26. from django.utils.safestring import mark_safe
  27. from django.utils import six
  28. from django.utils.six.moves.urllib.parse import urljoin
  29. # NumPy installed?
  30. try:
  31. import numpy
  32. except ImportError:
  33. numpy = False
  34. from . import filters
  35. #################################
  36. # Custom template tag for tests #
  37. #################################
  38. register = template.Library()
  39. class EchoNode(template.Node):
  40. def __init__(self, contents):
  41. self.contents = contents
  42. def render(self, context):
  43. return " ".join(self.contents)
  44. def do_echo(parser, token):
  45. return EchoNode(token.contents.split()[1:])
  46. def do_upper(value):
  47. return value.upper()
  48. register.tag("echo", do_echo)
  49. register.tag("other_echo", do_echo)
  50. register.filter("upper", do_upper)
  51. template.libraries['testtags'] = register
  52. #####################################
  53. # Helper objects for template tests #
  54. #####################################
  55. class SomeException(Exception):
  56. silent_variable_failure = True
  57. class SomeOtherException(Exception):
  58. pass
  59. class ContextStackException(Exception):
  60. pass
  61. class ShouldNotExecuteException(Exception):
  62. pass
  63. class SomeClass:
  64. def __init__(self):
  65. self.otherclass = OtherClass()
  66. def method(self):
  67. return "SomeClass.method"
  68. def method2(self, o):
  69. return o
  70. def method3(self):
  71. raise SomeException
  72. def method4(self):
  73. raise SomeOtherException
  74. def method5(self):
  75. raise TypeError
  76. def __getitem__(self, key):
  77. if key == 'silent_fail_key':
  78. raise SomeException
  79. elif key == 'noisy_fail_key':
  80. raise SomeOtherException
  81. raise KeyError
  82. def silent_fail_attribute(self):
  83. raise SomeException
  84. silent_fail_attribute = property(silent_fail_attribute)
  85. def noisy_fail_attribute(self):
  86. raise SomeOtherException
  87. noisy_fail_attribute = property(noisy_fail_attribute)
  88. class OtherClass:
  89. def method(self):
  90. return "OtherClass.method"
  91. class TestObj(object):
  92. def is_true(self):
  93. return True
  94. def is_false(self):
  95. return False
  96. def is_bad(self):
  97. raise ShouldNotExecuteException()
  98. class SilentGetItemClass(object):
  99. def __getitem__(self, key):
  100. raise SomeException
  101. class SilentAttrClass(object):
  102. def b(self):
  103. raise SomeException
  104. b = property(b)
  105. @python_2_unicode_compatible
  106. class UTF8Class:
  107. "Class whose __str__ returns non-ASCII data on Python 2"
  108. def __str__(self):
  109. return 'ŠĐĆŽćžšđ'
  110. class TemplateLoaderTests(TestCase):
  111. def test_loaders_security(self):
  112. ad_loader = app_directories.Loader()
  113. fs_loader = filesystem.Loader()
  114. def test_template_sources(path, template_dirs, expected_sources):
  115. if isinstance(expected_sources, list):
  116. # Fix expected sources so they are abspathed
  117. expected_sources = [os.path.abspath(s) for s in expected_sources]
  118. # Test the two loaders (app_directores and filesystem).
  119. func1 = lambda p, t: list(ad_loader.get_template_sources(p, t))
  120. func2 = lambda p, t: list(fs_loader.get_template_sources(p, t))
  121. for func in (func1, func2):
  122. if isinstance(expected_sources, list):
  123. self.assertEqual(func(path, template_dirs), expected_sources)
  124. else:
  125. self.assertRaises(expected_sources, func, path, template_dirs)
  126. template_dirs = ['/dir1', '/dir2']
  127. test_template_sources('index.html', template_dirs,
  128. ['/dir1/index.html', '/dir2/index.html'])
  129. test_template_sources('/etc/passwd', template_dirs, [])
  130. test_template_sources('etc/passwd', template_dirs,
  131. ['/dir1/etc/passwd', '/dir2/etc/passwd'])
  132. test_template_sources('../etc/passwd', template_dirs, [])
  133. test_template_sources('../../../etc/passwd', template_dirs, [])
  134. test_template_sources('/dir1/index.html', template_dirs,
  135. ['/dir1/index.html'])
  136. test_template_sources('../dir2/index.html', template_dirs,
  137. ['/dir2/index.html'])
  138. test_template_sources('/dir1blah', template_dirs, [])
  139. test_template_sources('../dir1blah', template_dirs, [])
  140. # UTF-8 bytestrings are permitted.
  141. test_template_sources(b'\xc3\x85ngstr\xc3\xb6m', template_dirs,
  142. ['/dir1/Ångström', '/dir2/Ångström'])
  143. # Unicode strings are permitted.
  144. test_template_sources('Ångström', template_dirs,
  145. ['/dir1/Ångström', '/dir2/Ångström'])
  146. test_template_sources('Ångström', [b'/Stra\xc3\x9fe'], ['/Straße/Ångström'])
  147. test_template_sources(b'\xc3\x85ngstr\xc3\xb6m', [b'/Stra\xc3\x9fe'],
  148. ['/Straße/Ångström'])
  149. # Invalid UTF-8 encoding in bytestrings is not. Should raise a
  150. # semi-useful error message.
  151. test_template_sources(b'\xc3\xc3', template_dirs, UnicodeDecodeError)
  152. # Case insensitive tests (for win32). Not run unless we're on
  153. # a case insensitive operating system.
  154. if os.path.normcase('/TEST') == os.path.normpath('/test'):
  155. template_dirs = ['/dir1', '/DIR2']
  156. test_template_sources('index.html', template_dirs,
  157. ['/dir1/index.html', '/DIR2/index.html'])
  158. test_template_sources('/DIR1/index.HTML', template_dirs,
  159. ['/DIR1/index.HTML'])
  160. # Turn TEMPLATE_DEBUG on, so that the origin file name will be kept with
  161. # the compiled templates.
  162. @override_settings(TEMPLATE_DEBUG=True)
  163. def test_loader_debug_origin(self):
  164. old_loaders = loader.template_source_loaders
  165. try:
  166. loader.template_source_loaders = (filesystem.Loader(),)
  167. # We rely on the fact that runtests.py sets up TEMPLATE_DIRS to
  168. # point to a directory containing a login.html file. Also that
  169. # the file system and app directories loaders both inherit the
  170. # load_template method from the BaseLoader class, so we only need
  171. # to test one of them.
  172. load_name = 'login.html'
  173. template = loader.get_template(load_name)
  174. template_name = template.nodelist[0].source[0].name
  175. self.assertTrue(template_name.endswith(load_name),
  176. 'Template loaded by filesystem loader has incorrect name for debug page: %s' % template_name)
  177. # Aso test the cached loader, since it overrides load_template
  178. cache_loader = cached.Loader(('',))
  179. cache_loader._cached_loaders = loader.template_source_loaders
  180. loader.template_source_loaders = (cache_loader,)
  181. template = loader.get_template(load_name)
  182. template_name = template.nodelist[0].source[0].name
  183. self.assertTrue(template_name.endswith(load_name),
  184. 'Template loaded through cached loader has incorrect name for debug page: %s' % template_name)
  185. template = loader.get_template(load_name)
  186. template_name = template.nodelist[0].source[0].name
  187. self.assertTrue(template_name.endswith(load_name),
  188. 'Cached template loaded through cached loader has incorrect name for debug page: %s' % template_name)
  189. finally:
  190. loader.template_source_loaders = old_loaders
  191. def test_loader_origin(self):
  192. with self.settings(TEMPLATE_DEBUG=True):
  193. template = loader.get_template('login.html')
  194. self.assertEqual(template.origin.loadname, 'login.html')
  195. def test_string_origin(self):
  196. with self.settings(TEMPLATE_DEBUG=True):
  197. template = Template('string template')
  198. self.assertEqual(template.origin.source, 'string template')
  199. def test_debug_false_origin(self):
  200. template = loader.get_template('login.html')
  201. self.assertEqual(template.origin, None)
  202. # TEMPLATE_DEBUG must be true, otherwise the exception raised
  203. # during {% include %} processing will be suppressed.
  204. @override_settings(TEMPLATE_DEBUG=True)
  205. def test_include_missing_template(self):
  206. """
  207. Tests that the correct template is identified as not existing
  208. when {% include %} specifies a template that does not exist.
  209. """
  210. old_loaders = loader.template_source_loaders
  211. try:
  212. # Test the base loader class via the app loader. load_template
  213. # from base is used by all shipped loaders excepting cached,
  214. # which has its own test.
  215. loader.template_source_loaders = (app_directories.Loader(),)
  216. load_name = 'test_include_error.html'
  217. r = None
  218. try:
  219. tmpl = loader.select_template([load_name])
  220. r = tmpl.render(template.Context({}))
  221. except template.TemplateDoesNotExist as e:
  222. self.assertEqual(e.args[0], 'missing.html')
  223. self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
  224. finally:
  225. loader.template_source_loaders = old_loaders
  226. # TEMPLATE_DEBUG must be true, otherwise the exception raised
  227. # during {% include %} processing will be suppressed.
  228. @override_settings(TEMPLATE_DEBUG=True)
  229. def test_extends_include_missing_baseloader(self):
  230. """
  231. Tests that the correct template is identified as not existing
  232. when {% extends %} specifies a template that does exist, but
  233. that template has an {% include %} of something that does not
  234. exist. See #12787.
  235. """
  236. old_loaders = loader.template_source_loaders
  237. try:
  238. # Test the base loader class via the app loader. load_template
  239. # from base is used by all shipped loaders excepting cached,
  240. # which has its own test.
  241. loader.template_source_loaders = (app_directories.Loader(),)
  242. load_name = 'test_extends_error.html'
  243. tmpl = loader.get_template(load_name)
  244. r = None
  245. try:
  246. r = tmpl.render(template.Context({}))
  247. except template.TemplateDoesNotExist as e:
  248. self.assertEqual(e.args[0], 'missing.html')
  249. self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
  250. finally:
  251. loader.template_source_loaders = old_loaders
  252. @override_settings(TEMPLATE_DEBUG=True)
  253. def test_extends_include_missing_cachedloader(self):
  254. """
  255. Same as test_extends_include_missing_baseloader, only tests
  256. behavior of the cached loader instead of BaseLoader.
  257. """
  258. old_loaders = loader.template_source_loaders
  259. try:
  260. cache_loader = cached.Loader(('',))
  261. cache_loader._cached_loaders = (app_directories.Loader(),)
  262. loader.template_source_loaders = (cache_loader,)
  263. load_name = 'test_extends_error.html'
  264. tmpl = loader.get_template(load_name)
  265. r = None
  266. try:
  267. r = tmpl.render(template.Context({}))
  268. except template.TemplateDoesNotExist as e:
  269. self.assertEqual(e.args[0], 'missing.html')
  270. self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
  271. # For the cached loader, repeat the test, to ensure the first attempt did not cache a
  272. # result that behaves incorrectly on subsequent attempts.
  273. tmpl = loader.get_template(load_name)
  274. try:
  275. tmpl.render(template.Context({}))
  276. except template.TemplateDoesNotExist as e:
  277. self.assertEqual(e.args[0], 'missing.html')
  278. self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
  279. finally:
  280. loader.template_source_loaders = old_loaders
  281. def test_include_template_argument(self):
  282. """
  283. Support any render() supporting object
  284. """
  285. ctx = Context({
  286. 'tmpl': Template('This worked!'),
  287. })
  288. outer_tmpl = Template('{% include tmpl %}')
  289. output = outer_tmpl.render(ctx)
  290. self.assertEqual(output, 'This worked!')
  291. @override_settings(TEMPLATE_DEBUG=True)
  292. def test_include_immediate_missing(self):
  293. """
  294. Regression test for #16417 -- {% include %} tag raises TemplateDoesNotExist at compile time if TEMPLATE_DEBUG is True
  295. Test that an {% include %} tag with a literal string referencing a
  296. template that does not exist does not raise an exception at parse
  297. time.
  298. """
  299. tmpl = Template('{% include "this_does_not_exist.html" %}')
  300. self.assertIsInstance(tmpl, Template)
  301. @override_settings(TEMPLATE_DEBUG=True)
  302. def test_include_recursive(self):
  303. comments = [
  304. {
  305. 'comment': 'A1',
  306. 'children': [
  307. {'comment': 'B1', 'children': []},
  308. {'comment': 'B2', 'children': []},
  309. {'comment': 'B3', 'children': [
  310. {'comment': 'C1', 'children': []}
  311. ]},
  312. ]
  313. }
  314. ]
  315. t = loader.get_template('recursive_include.html')
  316. self.assertEqual(
  317. "Recursion! A1 Recursion! B1 B2 B3 Recursion! C1",
  318. t.render(Context({'comments': comments})).replace(' ', '').replace('\n', ' ').strip(),
  319. )
  320. class TemplateRegressionTests(TestCase):
  321. def test_token_smart_split(self):
  322. # Regression test for #7027
  323. token = template.Token(template.TOKEN_BLOCK, 'sometag _("Page not found") value|yesno:_("yes,no")')
  324. split = token.split_contents()
  325. self.assertEqual(split, ["sometag", '_("Page not found")', 'value|yesno:_("yes,no")'])
  326. @override_settings(SETTINGS_MODULE=None, TEMPLATE_DEBUG=True)
  327. def test_url_reverse_no_settings_module(self):
  328. # Regression test for #9005
  329. t = Template('{% url will_not_match %}')
  330. c = Context()
  331. with self.assertRaises(urlresolvers.NoReverseMatch):
  332. t.render(c)
  333. @override_settings(TEMPLATE_STRING_IF_INVALID='%s is invalid', SETTINGS_MODULE='also_something')
  334. def test_url_reverse_view_name(self):
  335. # Regression test for #19827
  336. t = Template('{% url will_not_match %}')
  337. c = Context()
  338. try:
  339. t.render(c)
  340. except urlresolvers.NoReverseMatch:
  341. tb = sys.exc_info()[2]
  342. depth = 0
  343. while tb.tb_next is not None:
  344. tb = tb.tb_next
  345. depth += 1
  346. self.assertTrue(depth > 5,
  347. "The traceback context was lost when reraising the traceback. See #19827")
  348. def test_url_explicit_exception_for_old_syntax_at_run_time(self):
  349. # Regression test for #19280
  350. t = Template('{% url path.to.view %}') # not quoted = old syntax
  351. c = Context()
  352. with six.assertRaisesRegex(self, urlresolvers.NoReverseMatch,
  353. "The syntax changed in Django 1.5, see the docs."):
  354. t.render(c)
  355. def test_url_explicit_exception_for_old_syntax_at_compile_time(self):
  356. # Regression test for #19392
  357. with six.assertRaisesRegex(self, template.TemplateSyntaxError,
  358. "The syntax of 'url' changed in Django 1.5, see the docs."):
  359. Template('{% url my-view %}') # not a variable = old syntax
  360. @override_settings(DEBUG=True, TEMPLATE_DEBUG=True)
  361. def test_no_wrapped_exception(self):
  362. """
  363. The template system doesn't wrap exceptions, but annotates them.
  364. Refs #16770
  365. """
  366. c = Context({"coconuts": lambda: 42 / 0})
  367. t = Template("{{ coconuts }}")
  368. with self.assertRaises(ZeroDivisionError) as cm:
  369. t.render(c)
  370. self.assertEqual(cm.exception.django_template_source[1], (0, 14))
  371. def test_invalid_block_suggestion(self):
  372. # See #7876
  373. try:
  374. Template("{% if 1 %}lala{% endblock %}{% endif %}")
  375. except TemplateSyntaxError as e:
  376. self.assertEqual(e.args[0], "Invalid block tag: 'endblock', expected 'elif', 'else' or 'endif'")
  377. def test_ifchanged_concurrency(self):
  378. # Tests for #15849
  379. template = Template('[0{% for x in foo %},{% with var=get_value %}{% ifchanged %}{{ var }}{% endifchanged %}{% endwith %}{% endfor %}]')
  380. # Using generator to mimic concurrency.
  381. # The generator is not passed to the 'for' loop, because it does a list(values)
  382. # instead, call gen.next() in the template to control the generator.
  383. def gen():
  384. yield 1
  385. yield 2
  386. # Simulate that another thread is now rendering.
  387. # When the IfChangeNode stores state at 'self' it stays at '3' and skip the last yielded value below.
  388. iter2 = iter([1, 2, 3])
  389. output2 = template.render(Context({'foo': range(3), 'get_value': lambda: next(iter2)}))
  390. self.assertEqual(output2, '[0,1,2,3]', 'Expected [0,1,2,3] in second parallel template, got {0}'.format(output2))
  391. yield 3
  392. gen1 = gen()
  393. output1 = template.render(Context({'foo': range(3), 'get_value': lambda: next(gen1)}))
  394. self.assertEqual(output1, '[0,1,2,3]', 'Expected [0,1,2,3] in first template, got {0}'.format(output1))
  395. def test_cache_regression_20130(self):
  396. t = Template('{% load cache %}{% cache 1 regression_20130 %}foo{% endcache %}')
  397. cachenode = t.nodelist[1]
  398. self.assertEqual(cachenode.fragment_name, 'regression_20130')
  399. @override_settings(CACHES={
  400. 'default': {
  401. 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
  402. 'LOCATION': 'default',
  403. },
  404. 'template_fragments': {
  405. 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
  406. 'LOCATION': 'fragments',
  407. },
  408. })
  409. def test_cache_fragment_cache(self):
  410. """
  411. When a cache called "template_fragments" is present, the cache tag
  412. will use it in preference to 'default'
  413. """
  414. t1 = Template('{% load cache %}{% cache 1 fragment %}foo{% endcache %}')
  415. t2 = Template('{% load cache %}{% cache 1 fragment using="default" %}bar{% endcache %}')
  416. ctx = Context()
  417. o1 = t1.render(ctx)
  418. o2 = t2.render(ctx)
  419. self.assertEqual(o1, 'foo')
  420. self.assertNotEqual(o1, o2)
  421. def test_cache_missing_backend(self):
  422. """
  423. When a cache that doesn't exist is specified, the cache tag will
  424. raise a TemplateSyntaxError
  425. '"""
  426. t = Template('{% load cache %}{% cache 1 backend using="unknown" %}bar{% endcache %}')
  427. ctx = Context()
  428. with self.assertRaises(TemplateSyntaxError):
  429. t.render(ctx)
  430. def test_ifchanged_render_once(self):
  431. """ Test for ticket #19890. The content of ifchanged template tag was
  432. rendered twice."""
  433. template = Template('{% load cycle from future %}{% ifchanged %}{% cycle "1st time" "2nd time" %}{% endifchanged %}')
  434. output = template.render(Context({}))
  435. self.assertEqual(output, '1st time')
  436. def test_super_errors(self):
  437. """
  438. Test behavior of the raise errors into included blocks.
  439. See #18169
  440. """
  441. t = loader.get_template('included_content.html')
  442. with self.assertRaises(urlresolvers.NoReverseMatch):
  443. t.render(Context({}))
  444. @override_settings(MEDIA_URL="/media/", STATIC_URL="/static/")
  445. class TemplateTests(TransRealMixin, TestCase):
  446. def test_templates(self):
  447. template_tests = self.get_template_tests()
  448. filter_tests = filters.get_filter_tests()
  449. # Quickly check that we aren't accidentally using a name in both
  450. # template and filter tests.
  451. overlapping_names = [name for name in filter_tests if name in template_tests]
  452. assert not overlapping_names, 'Duplicate test name(s): %s' % ', '.join(overlapping_names)
  453. template_tests.update(filter_tests)
  454. cache_loader = setup_test_template_loader(
  455. dict((name, t[0]) for name, t in six.iteritems(template_tests)),
  456. use_cached_loader=True,
  457. )
  458. failures = []
  459. tests = sorted(template_tests.items())
  460. # Turn TEMPLATE_DEBUG off, because tests assume that.
  461. old_td, settings.TEMPLATE_DEBUG = settings.TEMPLATE_DEBUG, False
  462. # Set TEMPLATE_STRING_IF_INVALID to a known string.
  463. old_invalid = settings.TEMPLATE_STRING_IF_INVALID
  464. expected_invalid_str = 'INVALID'
  465. # Set ALLOWED_INCLUDE_ROOTS so that ssi works.
  466. old_allowed_include_roots = settings.ALLOWED_INCLUDE_ROOTS
  467. settings.ALLOWED_INCLUDE_ROOTS = (
  468. os.path.dirname(os.path.abspath(upath(__file__))),
  469. )
  470. # Warm the URL reversing cache. This ensures we don't pay the cost
  471. # warming the cache during one of the tests.
  472. urlresolvers.reverse('template_tests.views.client_action',
  473. kwargs={'id': 0, 'action': "update"})
  474. for name, vals in tests:
  475. if isinstance(vals[2], tuple):
  476. normal_string_result = vals[2][0]
  477. invalid_string_result = vals[2][1]
  478. if isinstance(invalid_string_result, tuple):
  479. expected_invalid_str = 'INVALID %s'
  480. invalid_string_result = invalid_string_result[0] % invalid_string_result[1]
  481. template_base.invalid_var_format_string = True
  482. try:
  483. template_debug_result = vals[2][2]
  484. except IndexError:
  485. template_debug_result = normal_string_result
  486. else:
  487. normal_string_result = vals[2]
  488. invalid_string_result = vals[2]
  489. template_debug_result = vals[2]
  490. if 'LANGUAGE_CODE' in vals[1]:
  491. activate(vals[1]['LANGUAGE_CODE'])
  492. else:
  493. activate('en-us')
  494. for invalid_str, template_debug, result in [
  495. ('', False, normal_string_result),
  496. (expected_invalid_str, False, invalid_string_result),
  497. ('', True, template_debug_result)
  498. ]:
  499. settings.TEMPLATE_STRING_IF_INVALID = invalid_str
  500. settings.TEMPLATE_DEBUG = template_debug
  501. for is_cached in (False, True):
  502. try:
  503. try:
  504. with warnings.catch_warnings():
  505. # Ignore pending deprecations of the old syntax of the 'cycle' and 'firstof' tags.
  506. warnings.filterwarnings("ignore", category=DeprecationWarning, module='django.template.base')
  507. test_template = loader.get_template(name)
  508. except ShouldNotExecuteException:
  509. failures.append("Template test (Cached='%s', TEMPLATE_STRING_IF_INVALID='%s', TEMPLATE_DEBUG=%s): %s -- FAILED. Template loading invoked method that shouldn't have been invoked." % (is_cached, invalid_str, template_debug, name))
  510. try:
  511. output = self.render(test_template, vals)
  512. except ShouldNotExecuteException:
  513. failures.append("Template test (Cached='%s', TEMPLATE_STRING_IF_INVALID='%s', TEMPLATE_DEBUG=%s): %s -- FAILED. Template rendering invoked method that shouldn't have been invoked." % (is_cached, invalid_str, template_debug, name))
  514. except ContextStackException:
  515. failures.append("Template test (Cached='%s', TEMPLATE_STRING_IF_INVALID='%s', TEMPLATE_DEBUG=%s): %s -- FAILED. Context stack was left imbalanced" % (is_cached, invalid_str, template_debug, name))
  516. continue
  517. except Exception:
  518. exc_type, exc_value, exc_tb = sys.exc_info()
  519. if exc_type != result:
  520. tb = '\n'.join(traceback.format_exception(exc_type, exc_value, exc_tb))
  521. failures.append("Template test (Cached='%s', TEMPLATE_STRING_IF_INVALID='%s', TEMPLATE_DEBUG=%s): %s -- FAILED. Got %s, exception: %s\n%s" % (is_cached, invalid_str, template_debug, name, exc_type, exc_value, tb))
  522. continue
  523. if output != result:
  524. failures.append("Template test (Cached='%s', TEMPLATE_STRING_IF_INVALID='%s', TEMPLATE_DEBUG=%s): %s -- FAILED. Expected %r, got %r" % (is_cached, invalid_str, template_debug, name, result, output))
  525. cache_loader.reset()
  526. if 'LANGUAGE_CODE' in vals[1]:
  527. deactivate()
  528. if template_base.invalid_var_format_string:
  529. expected_invalid_str = 'INVALID'
  530. template_base.invalid_var_format_string = False
  531. restore_template_loaders()
  532. deactivate()
  533. settings.TEMPLATE_DEBUG = old_td
  534. settings.TEMPLATE_STRING_IF_INVALID = old_invalid
  535. settings.ALLOWED_INCLUDE_ROOTS = old_allowed_include_roots
  536. self.assertEqual(failures, [], "Tests failed:\n%s\n%s" %
  537. ('-'*70, ("\n%s\n" % ('-'*70)).join(failures)))
  538. def render(self, test_template, vals):
  539. context = template.Context(vals[1])
  540. before_stack_size = len(context.dicts)
  541. output = test_template.render(context)
  542. if len(context.dicts) != before_stack_size:
  543. raise ContextStackException
  544. return output
  545. def get_template_tests(self):
  546. # SYNTAX --
  547. # 'template_name': ('template contents', 'context dict', 'expected string output' or Exception class)
  548. basedir = os.path.dirname(os.path.abspath(upath(__file__)))
  549. tests = {
  550. ### BASIC SYNTAX ################################################
  551. # Plain text should go through the template parser untouched
  552. 'basic-syntax01': ("something cool", {}, "something cool"),
  553. # Variables should be replaced with their value in the current
  554. # context
  555. 'basic-syntax02': ("{{ headline }}", {'headline': 'Success'}, "Success"),
  556. # More than one replacement variable is allowed in a template
  557. 'basic-syntax03': ("{{ first }} --- {{ second }}", {"first": 1, "second": 2}, "1 --- 2"),
  558. # Fail silently when a variable is not found in the current context
  559. 'basic-syntax04': ("as{{ missing }}df", {}, ("asdf", "asINVALIDdf")),
  560. # A variable may not contain more than one word
  561. 'basic-syntax06': ("{{ multi word variable }}", {}, template.TemplateSyntaxError),
  562. # Raise TemplateSyntaxError for empty variable tags
  563. 'basic-syntax07': ("{{ }}", {}, template.TemplateSyntaxError),
  564. 'basic-syntax08': ("{{ }}", {}, template.TemplateSyntaxError),
  565. # Attribute syntax allows a template to call an object's attribute
  566. 'basic-syntax09': ("{{ var.method }}", {"var": SomeClass()}, "SomeClass.method"),
  567. # Multiple levels of attribute access are allowed
  568. 'basic-syntax10': ("{{ var.otherclass.method }}", {"var": SomeClass()}, "OtherClass.method"),
  569. # Fail silently when a variable's attribute isn't found
  570. 'basic-syntax11': ("{{ var.blech }}", {"var": SomeClass()}, ("", "INVALID")),
  571. # Raise TemplateSyntaxError when trying to access a variable beginning with an underscore
  572. 'basic-syntax12': ("{{ var.__dict__ }}", {"var": SomeClass()}, template.TemplateSyntaxError),
  573. # Raise TemplateSyntaxError when trying to access a variable containing an illegal character
  574. 'basic-syntax13': ("{{ va>r }}", {}, template.TemplateSyntaxError),
  575. 'basic-syntax14': ("{{ (var.r) }}", {}, template.TemplateSyntaxError),
  576. 'basic-syntax15': ("{{ sp%am }}", {}, template.TemplateSyntaxError),
  577. 'basic-syntax16': ("{{ eggs! }}", {}, template.TemplateSyntaxError),
  578. 'basic-syntax17': ("{{ moo? }}", {}, template.TemplateSyntaxError),
  579. # Attribute syntax allows a template to call a dictionary key's value
  580. 'basic-syntax18': ("{{ foo.bar }}", {"foo": {"bar": "baz"}}, "baz"),
  581. # Fail silently when a variable's dictionary key isn't found
  582. 'basic-syntax19': ("{{ foo.spam }}", {"foo": {"bar": "baz"}}, ("", "INVALID")),
  583. # Fail silently when accessing a non-simple method
  584. 'basic-syntax20': ("{{ var.method2 }}", {"var": SomeClass()}, ("", "INVALID")),
  585. # Don't silence a TypeError if it was raised inside a callable
  586. 'basic-syntax20b': ("{{ var.method5 }}", {"var": SomeClass()}, TypeError),
  587. # Don't get confused when parsing something that is almost, but not
  588. # quite, a template tag.
  589. 'basic-syntax21': ("a {{ moo %} b", {}, "a {{ moo %} b"),
  590. 'basic-syntax22': ("{{ moo #}", {}, "{{ moo #}"),
  591. # Will try to treat "moo #} {{ cow" as the variable. Not ideal, but
  592. # costly to work around, so this triggers an error.
  593. 'basic-syntax23': ("{{ moo #} {{ cow }}", {"cow": "cow"}, template.TemplateSyntaxError),
  594. # Embedded newlines make it not-a-tag.
  595. 'basic-syntax24': ("{{ moo\n }}", {}, "{{ moo\n }}"),
  596. # Literal strings are permitted inside variables, mostly for i18n
  597. # purposes.
  598. 'basic-syntax25': ('{{ "fred" }}', {}, "fred"),
  599. 'basic-syntax26': (r'{{ "\"fred\"" }}', {}, "\"fred\""),
  600. 'basic-syntax27': (r'{{ _("\"fred\"") }}', {}, "\"fred\""),
  601. # regression test for ticket #12554
  602. # make sure a silent_variable_failure Exception is supressed
  603. # on dictionary and attribute lookup
  604. 'basic-syntax28': ("{{ a.b }}", {'a': SilentGetItemClass()}, ('', 'INVALID')),
  605. 'basic-syntax29': ("{{ a.b }}", {'a': SilentAttrClass()}, ('', 'INVALID')),
  606. # Something that starts like a number but has an extra lookup works as a lookup.
  607. 'basic-syntax30': ("{{ 1.2.3 }}", {"1": {"2": {"3": "d"}}}, "d"),
  608. 'basic-syntax31': ("{{ 1.2.3 }}", {"1": {"2": ("a", "b", "c", "d")}}, "d"),
  609. 'basic-syntax32': ("{{ 1.2.3 }}", {"1": (("x", "x", "x", "x"), ("y", "y", "y", "y"), ("a", "b", "c", "d"))}, "d"),
  610. 'basic-syntax33': ("{{ 1.2.3 }}", {"1": ("xxxx", "yyyy", "abcd")}, "d"),
  611. 'basic-syntax34': ("{{ 1.2.3 }}", {"1": ({"x": "x"}, {"y": "y"}, {"z": "z", "3": "d"})}, "d"),
  612. # Numbers are numbers even if their digits are in the context.
  613. 'basic-syntax35': ("{{ 1 }}", {"1": "abc"}, "1"),
  614. 'basic-syntax36': ("{{ 1.2 }}", {"1": "abc"}, "1.2"),
  615. # Call methods in the top level of the context
  616. 'basic-syntax37': ('{{ callable }}', {"callable": lambda: "foo bar"}, "foo bar"),
  617. # Call methods returned from dictionary lookups
  618. 'basic-syntax38': ('{{ var.callable }}', {"var": {"callable": lambda: "foo bar"}}, "foo bar"),
  619. 'builtins01': ('{{ True }}', {}, "True"),
  620. 'builtins02': ('{{ False }}', {}, "False"),
  621. 'builtins03': ('{{ None }}', {}, "None"),
  622. # List-index syntax allows a template to access a certain item of a subscriptable object.
  623. 'list-index01': ("{{ var.1 }}", {"var": ["first item", "second item"]}, "second item"),
  624. # Fail silently when the list index is out of range.
  625. 'list-index02': ("{{ var.5 }}", {"var": ["first item", "second item"]}, ("", "INVALID")),
  626. # Fail silently when the variable is not a subscriptable object.
  627. 'list-index03': ("{{ var.1 }}", {"var": None}, ("", "INVALID")),
  628. # Fail silently when variable is a dict without the specified key.
  629. 'list-index04': ("{{ var.1 }}", {"var": {}}, ("", "INVALID")),
  630. # Dictionary lookup wins out when dict's key is a string.
  631. 'list-index05': ("{{ var.1 }}", {"var": {'1': "hello"}}, "hello"),
  632. # But list-index lookup wins out when dict's key is an int, which
  633. # behind the scenes is really a dictionary lookup (for a dict)
  634. # after converting the key to an int.
  635. 'list-index06': ("{{ var.1 }}", {"var": {1: "hello"}}, "hello"),
  636. # Dictionary lookup wins out when there is a string and int version of the key.
  637. 'list-index07': ("{{ var.1 }}", {"var": {'1': "hello", 1: "world"}}, "hello"),
  638. # Basic filter usage
  639. 'filter-syntax01': ("{{ var|upper }}", {"var": "Django is the greatest!"}, "DJANGO IS THE GREATEST!"),
  640. # Chained filters
  641. 'filter-syntax02': ("{{ var|upper|lower }}", {"var": "Django is the greatest!"}, "django is the greatest!"),
  642. # Allow spaces before the filter pipe
  643. 'filter-syntax03': ("{{ var |upper }}", {"var": "Django is the greatest!"}, "DJANGO IS THE GREATEST!"),
  644. # Allow spaces after the filter pipe
  645. 'filter-syntax04': ("{{ var| upper }}", {"var": "Django is the greatest!"}, "DJANGO IS THE GREATEST!"),
  646. # Raise TemplateSyntaxError for a nonexistent filter
  647. 'filter-syntax05': ("{{ var|does_not_exist }}", {}, template.TemplateSyntaxError),
  648. # Raise TemplateSyntaxError when trying to access a filter containing an illegal character
  649. 'filter-syntax06': ("{{ var|fil(ter) }}", {}, template.TemplateSyntaxError),
  650. # Raise TemplateSyntaxError for invalid block tags
  651. 'filter-syntax07': ("{% nothing_to_see_here %}", {}, template.TemplateSyntaxError),
  652. # Raise TemplateSyntaxError for empty block tags
  653. 'filter-syntax08': ("{% %}", {}, template.TemplateSyntaxError),
  654. # Chained filters, with an argument to the first one
  655. 'filter-syntax09': ('{{ var|removetags:"b i"|upper|lower }}', {"var": "<b><i>Yes</i></b>"}, "yes"),
  656. # Literal string as argument is always "safe" from auto-escaping..
  657. 'filter-syntax10': (r'{{ var|default_if_none:" endquote\" hah" }}',
  658. {"var": None}, ' endquote" hah'),
  659. # Variable as argument
  660. 'filter-syntax11': (r'{{ var|default_if_none:var2 }}', {"var": None, "var2": "happy"}, 'happy'),
  661. # Default argument testing
  662. 'filter-syntax12': (r'{{ var|yesno:"yup,nup,mup" }} {{ var|yesno }}', {"var": True}, 'yup yes'),
  663. # Fail silently for methods that raise an exception with a
  664. # "silent_variable_failure" attribute
  665. 'filter-syntax13': (r'1{{ var.method3 }}2', {"var": SomeClass()}, ("12", "1INVALID2")),
  666. # In methods that raise an exception without a
  667. # "silent_variable_attribute" set to True, the exception propagates
  668. 'filter-syntax14': (r'1{{ var.method4 }}2', {"var": SomeClass()}, (SomeOtherException, SomeOtherException)),
  669. # Escaped backslash in argument
  670. 'filter-syntax15': (r'{{ var|default_if_none:"foo\bar" }}', {"var": None}, r'foo\bar'),
  671. # Escaped backslash using known escape char
  672. 'filter-syntax16': (r'{{ var|default_if_none:"foo\now" }}', {"var": None}, r'foo\now'),
  673. # Empty strings can be passed as arguments to filters
  674. 'filter-syntax17': (r'{{ var|join:"" }}', {'var': ['a', 'b', 'c']}, 'abc'),
  675. # Make sure that any unicode strings are converted to bytestrings
  676. # in the final output.
  677. 'filter-syntax18': (r'{{ var }}', {'var': UTF8Class()}, '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111'),
  678. # Numbers as filter arguments should work
  679. 'filter-syntax19': ('{{ var|truncatewords:1 }}', {"var": "hello world"}, "hello ..."),
  680. #filters should accept empty string constants
  681. 'filter-syntax20': ('{{ ""|default_if_none:"was none" }}', {}, ""),
  682. # Fail silently for non-callable attribute and dict lookups which
  683. # raise an exception with a "silent_variable_failure" attribute
  684. 'filter-syntax21': (r'1{{ var.silent_fail_key }}2', {"var": SomeClass()}, ("12", "1INVALID2")),
  685. 'filter-syntax22': (r'1{{ var.silent_fail_attribute }}2', {"var": SomeClass()}, ("12", "1INVALID2")),
  686. # In attribute and dict lookups that raise an unexpected exception
  687. # without a "silent_variable_attribute" set to True, the exception
  688. # propagates
  689. 'filter-syntax23': (r'1{{ var.noisy_fail_key }}2', {"var": SomeClass()}, (SomeOtherException, SomeOtherException)),
  690. 'filter-syntax24': (r'1{{ var.noisy_fail_attribute }}2', {"var": SomeClass()}, (SomeOtherException, SomeOtherException)),
  691. ### COMMENT SYNTAX ########################################################
  692. 'comment-syntax01': ("{# this is hidden #}hello", {}, "hello"),
  693. 'comment-syntax02': ("{# this is hidden #}hello{# foo #}", {}, "hello"),
  694. # Comments can contain invalid stuff.
  695. 'comment-syntax03': ("foo{# {% if %} #}", {}, "foo"),
  696. 'comment-syntax04': ("foo{# {% endblock %} #}", {}, "foo"),
  697. 'comment-syntax05': ("foo{# {% somerandomtag %} #}", {}, "foo"),
  698. 'comment-syntax06': ("foo{# {% #}", {}, "foo"),
  699. 'comment-syntax07': ("foo{# %} #}", {}, "foo"),
  700. 'comment-syntax08': ("foo{# %} #}bar", {}, "foobar"),
  701. 'comment-syntax09': ("foo{# {{ #}", {}, "foo"),
  702. 'comment-syntax10': ("foo{# }} #}", {}, "foo"),
  703. 'comment-syntax11': ("foo{# { #}", {}, "foo"),
  704. 'comment-syntax12': ("foo{# } #}", {}, "foo"),
  705. ### COMMENT TAG ###########################################################
  706. 'comment-tag01': ("{% comment %}this is hidden{% endcomment %}hello", {}, "hello"),
  707. 'comment-tag02': ("{% comment %}this is hidden{% endcomment %}hello{% comment %}foo{% endcomment %}", {}, "hello"),
  708. # Comment tag can contain invalid stuff.
  709. 'comment-tag03': ("foo{% comment %} {% if %} {% endcomment %}", {}, "foo"),
  710. 'comment-tag04': ("foo{% comment %} {% endblock %} {% endcomment %}", {}, "foo"),
  711. 'comment-tag05': ("foo{% comment %} {% somerandomtag %} {% endcomment %}", {}, "foo"),
  712. ### CYCLE TAG #############################################################
  713. 'cycle01': ('{% cycle a %}', {}, template.TemplateSyntaxError),
  714. 'cycle02': ('{% cycle a,b,c as abc %}{% cycle abc %}', {}, 'ab'),
  715. 'cycle03': ('{% cycle a,b,c as abc %}{% cycle abc %}{% cycle abc %}', {}, 'abc'),
  716. 'cycle04': ('{% cycle a,b,c as abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}', {}, 'abca'),
  717. 'cycle05': ('{% cycle %}', {}, template.TemplateSyntaxError),
  718. 'cycle06': ('{% cycle a %}', {}, template.TemplateSyntaxError),
  719. 'cycle07': ('{% cycle a,b,c as foo %}{% cycle bar %}', {}, template.TemplateSyntaxError),
  720. 'cycle08': ('{% cycle a,b,c as foo %}{% cycle foo %}{{ foo }}{{ foo }}{% cycle foo %}{{ foo }}', {}, 'abbbcc'),
  721. 'cycle09': ("{% for i in test %}{% cycle a,b %}{{ i }},{% endfor %}", {'test': range(5)}, 'a0,b1,a2,b3,a4,'),
  722. 'cycle10': ("{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}", {}, 'ab'),
  723. 'cycle11': ("{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}", {}, 'abc'),
  724. 'cycle12': ("{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}", {}, 'abca'),
  725. 'cycle13': ("{% for i in test %}{% cycle 'a' 'b' %}{{ i }},{% endfor %}", {'test': range(5)}, 'a0,b1,a2,b3,a4,'),
  726. 'cycle14': ("{% cycle one two as foo %}{% cycle foo %}", {'one': '1', 'two': '2'}, '12'),
  727. 'cycle15': ("{% for i in test %}{% cycle aye bee %}{{ i }},{% endfor %}", {'test': range(5), 'aye': 'a', 'bee': 'b'}, 'a0,b1,a2,b3,a4,'),
  728. 'cycle16': ("{% cycle one|lower two as foo %}{% cycle foo %}", {'one': 'A', 'two': '2'}, 'a2'),
  729. 'cycle17': ("{% cycle 'a' 'b' 'c' as abc silent %}{% cycle abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}", {}, ""),
  730. 'cycle18': ("{% cycle 'a' 'b' 'c' as foo invalid_flag %}", {}, template.TemplateSyntaxError),
  731. 'cycle19': ("{% cycle 'a' 'b' as silent %}{% cycle silent %}", {}, "ab"),
  732. 'cycle20': ("{% cycle one two as foo %} &amp; {% cycle foo %}", {'one': 'A & B', 'two': 'C & D'}, "A & B &amp; C & D"),
  733. 'cycle21': ("{% filter force_escape %}{% cycle one two as foo %} & {% cycle foo %}{% endfilter %}", {'one': 'A & B', 'two': 'C & D'}, "A &amp; B &amp; C &amp; D"),
  734. 'cycle22': ("{% for x in values %}{% cycle 'a' 'b' 'c' as abc silent %}{{ x }}{% endfor %}", {'values': [1, 2, 3, 4]}, "1234"),
  735. 'cycle23': ("{% for x in values %}{% cycle 'a' 'b' 'c' as abc silent %}{{ abc }}{{ x }}{% endfor %}", {'values': [1, 2, 3, 4]}, "a1b2c3a4"),
  736. 'included-cycle': ('{{ abc }}', {'abc': 'xxx'}, 'xxx'),
  737. 'cycle24': ("{% for x in values %}{% cycle 'a' 'b' 'c' as abc silent %}{% include 'included-cycle' %}{% endfor %}", {'values': [1, 2, 3, 4]}, "abca"),
  738. 'cycle25': ('{% cycle a as abc %}', {'a': '<'}, '<'),
  739. 'cycle26': ('{% load cycle from future %}{% cycle a b as ab %}{% cycle ab %}', {'a': '<', 'b': '>'}, '&lt;&gt;'),
  740. 'cycle27': ('{% load cycle from future %}{% autoescape off %}{% cycle a b as ab %}{% cycle ab %}{% endautoescape %}', {'a': '<', 'b': '>'}, '<>'),
  741. 'cycle28': ('{% load cycle from future %}{% cycle a|safe b as ab %}{% cycle ab %}', {'a': '<', 'b': '>'}, '<&gt;'),
  742. ### EXCEPTIONS ############################################################
  743. # Raise exception for invalid template name
  744. 'exception01': ("{% extends 'nonexistent' %}", {}, (template.TemplateDoesNotExist, template.TemplateDoesNotExist)),
  745. # Raise exception for invalid template name (in variable)
  746. 'exception02': ("{% extends nonexistent %}", {}, (template.TemplateSyntaxError, template.TemplateDoesNotExist)),
  747. # Raise exception for extra {% extends %} tags
  748. 'exception03': ("{% extends 'inheritance01' %}{% block first %}2{% endblock %}{% extends 'inheritance16' %}", {}, template.TemplateSyntaxError),
  749. # Raise exception for custom tags used in child with {% load %} tag in parent, not in child
  750. 'exception04': ("{% extends 'inheritance17' %}{% block first %}{% echo 400 %}5678{% endblock %}", {}, template.TemplateSyntaxError),
  751. ### FILTER TAG ############################################################
  752. 'filter01': ('{% filter upper %}{% endfilter %}', {}, ''),
  753. 'filter02': ('{% filter upper %}django{% endfilter %}', {}, 'DJANGO'),
  754. 'filter03': ('{% filter upper|lower %}django{% endfilter %}', {}, 'django'),
  755. 'filter04': ('{% filter cut:remove %}djangospam{% endfilter %}', {'remove': 'spam'}, 'django'),
  756. 'filter05': ('{% filter safe %}fail{% endfilter %}', {}, template.TemplateSyntaxError),
  757. 'filter05bis': ('{% filter upper|safe %}fail{% endfilter %}', {}, template.TemplateSyntaxError),
  758. 'filter06': ('{% filter escape %}fail{% endfilter %}', {}, template.TemplateSyntaxError),
  759. 'filter06bis': ('{% filter upper|escape %}fail{% endfilter %}', {}, template.TemplateSyntaxError),
  760. ### FIRSTOF TAG ###########################################################
  761. 'firstof01': ('{% firstof a b c %}', {'a': 0, 'b': 0, 'c': 0}, ''),
  762. 'firstof02': ('{% firstof a b c %}', {'a': 1, 'b': 0, 'c': 0}, '1'),
  763. 'firstof03': ('{% firstof a b c %}', {'a': 0, 'b': 2, 'c': 0}, '2'),
  764. 'firstof04': ('{% firstof a b c %}', {'a': 0, 'b': 0, 'c': 3}, '3'),
  765. 'firstof05': ('{% firstof a b c %}', {'a': 1, 'b': 2, 'c': 3}, '1'),
  766. 'firstof06': ('{% firstof a b c %}', {'b': 0, 'c': 3}, '3'),
  767. 'firstof07': ('{% firstof a b "c" %}', {'a': 0}, 'c'),
  768. 'firstof08': ('{% firstof a b "c and d" %}', {'a': 0, 'b': 0}, 'c and d'),
  769. 'firstof09': ('{% firstof %}', {}, template.TemplateSyntaxError),
  770. 'firstof10': ('{% firstof a %}', {'a': '<'}, '<'),
  771. 'firstof11': ('{% load firstof from future %}{% firstof a b %}', {'a': '<', 'b': '>'}, '&lt;'),
  772. 'firstof12': ('{% load firstof from future %}{% firstof a b %}', {'a': '', 'b': '>'}, '&gt;'),
  773. 'firstof13': ('{% load firstof from future %}{% autoescape off %}{% firstof a %}{% endautoescape %}', {'a': '<'}, '<'),
  774. 'firstof14': ('{% load firstof from future %}{% firstof a|safe b %}', {'a': '<'}, '<'),
  775. ### FOR TAG ###############################################################
  776. 'for-tag01': ("{% for val in values %}{{ val }}{% endfor %}", {"values": [1, 2, 3]}, "123"),
  777. 'for-tag02': ("{% for val in values reversed %}{{ val }}{% endfor %}", {"values": [1, 2, 3]}, "321"),
  778. 'for-tag-vars01': ("{% for val in values %}{{ forloop.counter }}{% endfor %}", {"values": [6, 6, 6]}, "123"),
  779. 'for-tag-vars02': ("{% for val in values %}{{ forloop.counter0 }}{% endfor %}", {"values": [6, 6, 6]}, "012"),
  780. 'for-tag-vars03': ("{% for val in values %}{{ forloop.revcounter }}{% endfor %}", {"values": [6, 6, 6]}, "321"),
  781. 'for-tag-vars04': ("{% for val in values %}{{ forloop.revcounter0 }}{% endfor %}", {"values": [6, 6, 6]}, "210"),
  782. 'for-tag-vars05': ("{% for val in values %}{% if forloop.first %}f{% else %}x{% endif %}{% endfor %}", {"values": [6, 6, 6]}, "fxx"),
  783. 'for-tag-vars06': ("{% for val in values %}{% if forloop.last %}l{% else %}x{% endif %}{% endfor %}", {"values": [6, 6, 6]}, "xxl"),
  784. 'for-tag-unpack01': ("{% for key,value in items %}{{ key }}:{{ value }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, "one:1/two:2/"),
  785. 'for-tag-unpack03': ("{% for key, value in items %}{{ key }}:{{ value }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, "one:1/two:2/"),
  786. 'for-tag-unpack04': ("{% for key , value in items %}{{ key }}:{{ value }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, "one:1/two:2/"),
  787. 'for-tag-unpack05': ("{% for key ,value in items %}{{ key }}:{{ value }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, "one:1/two:2/"),
  788. 'for-tag-unpack06': ("{% for key value in items %}{{ key }}:{{ value }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, template.TemplateSyntaxError),
  789. 'for-tag-unpack07': ("{% for key,,value in items %}{{ key }}:{{ value }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, template.TemplateSyntaxError),
  790. 'for-tag-unpack08': ("{% for key,value, in items %}{{ key }}:{{ value }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, template.TemplateSyntaxError),
  791. # Ensure that a single loopvar doesn't truncate the list in val.
  792. 'for-tag-unpack09': ("{% for val in items %}{{ val.0 }}:{{ val.1 }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, "one:1/two:2/"),
  793. # Otherwise, silently truncate if the length of loopvars differs to the length of each set of items.
  794. 'for-tag-unpack10': ("{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}", {"items": (('one', 1, 'carrot'), ('two', 2, 'orange'))}, "one:1/two:2/"),
  795. 'for-tag-unpack11': ("{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, ("one:1,/two:2,/", "one:1,INVALID/two:2,INVALID/")),
  796. 'for-tag-unpack12': ("{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}", {"items": (('one', 1, 'carrot'), ('two', 2))}, ("one:1,carrot/two:2,/", "one:1,carrot/two:2,INVALID/")),
  797. 'for-tag-unpack13': ("{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}", {"items": (('one', 1, 'carrot'), ('two', 2, 'cheese'))}, ("one:1,carrot/two:2,cheese/", "one:1,carrot/two:2,cheese/")),
  798. 'for-tag-unpack14': ("{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}", {"items": (1, 2)}, (":/:/", "INVALID:INVALID/INVALID:INVALID/")),
  799. 'for-tag-empty01': ("{% for val in values %}{{ val }}{% empty %}empty text{% endfor %}", {"values": [1, 2, 3]}, "123"),
  800. 'for-tag-empty02': ("{% for val in values %}{{ val }}{% empty %}values array empty{% endfor %}", {"values": []}, "values array empty"),
  801. 'for-tag-empty03': ("{% for val in values %}{{ val }}{% empty %}values array not found{% endfor %}", {}, "values array not found"),
  802. # Ticket 19882
  803. 'for-tag-filter-ws': ("{% load custom %}{% for x in s|noop:'x y' %}{{ x }}{% endfor %}", {'s': 'abc'}, 'abc'),
  804. ### IF TAG ################################################################
  805. 'if-tag01': ("{% if foo %}yes{% else %}no{% endif %}", {"foo": True}, "yes"),
  806. 'if-tag02': ("{% if foo %}yes{% else %}no{% endif %}", {"foo": False}, "no"),
  807. 'if-tag03': ("{% if foo %}yes{% else %}no{% endif %}", {}, "no"),
  808. 'if-tag04': ("{% if foo %}foo{% elif bar %}bar{% endif %}", {'foo': True}, "foo"),
  809. 'if-tag05': ("{% if foo %}foo{% elif bar %}bar{% endif %}", {'bar': True}, "bar"),
  810. 'if-tag06': ("{% if foo %}foo{% elif bar %}bar{% endif %}", {}, ""),
  811. 'if-tag07': ("{% if foo %}foo{% elif bar %}bar{% else %}nothing{% endif %}", {'foo': True}, "foo"),
  812. 'if-tag08': ("{% if foo %}foo{% elif bar %}bar{% else %}nothing{% endif %}", {'bar': True}, "bar"),
  813. 'if-tag09': ("{% if foo %}foo{% elif bar %}bar{% else %}nothing{% endif %}", {}, "nothing"),
  814. 'if-tag10': ("{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}", {'foo': True}, "foo"),
  815. 'if-tag11': ("{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}", {'bar': True}, "bar"),
  816. 'if-tag12': ("{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}", {'baz': True}, "baz"),
  817. 'if-tag13': ("{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}", {}, "nothing"),
  818. # Filters
  819. 'if-tag-filter01': ("{% if foo|length == 5 %}yes{% else %}no{% endif %}", {'foo': 'abcde'}, "yes"),
  820. 'if-tag-filter02': ("{% if foo|upper == 'ABC' %}yes{% else %}no{% endif %}", {}, "no"),
  821. # Equality
  822. 'if-tag-eq01': ("{% if foo == bar %}yes{% else %}no{% endif %}", {}, "yes"),
  823. 'if-tag-eq02': ("{% if foo == bar %}yes{% else %}no{% endif %}", {'foo': 1}, "no"),
  824. 'if-tag-eq03': ("{% if foo == bar %}yes{% else %}no{% endif %}", {'foo': 1, 'bar': 1}, "yes"),
  825. 'if-tag-eq04': ("{% if foo == bar %}yes{% else %}no{% endif %}", {'foo': 1, 'bar': 2}, "no"),
  826. 'if-tag-eq05': ("{% if foo == '' %}yes{% else %}no{% endif %}", {}, "no"),
  827. # Comparison
  828. 'if-tag-gt-01': ("{% if 2 > 1 %}yes{% else %}no{% endif %}", {}, "yes"),
  829. 'if-tag-gt-02': ("{% if 1 > 1 %}yes{% else %}no{% endif %}", {}, "no"),
  830. 'if-tag-gte-01': ("{% if 1 >= 1 %}yes{% else %}no{% endif %}", {}, "yes"),
  831. 'if-tag-gte-02': ("{% if 1 >= 2 %}yes{% else %}no{% endif %}", {}, "no"),
  832. 'if-tag-lt-01': ("{% if 1 < 2 %}yes{% else %}no{% endif %}", {}, "yes"),
  833. 'if-tag-lt-02': ("{% if 1 < 1 %}yes{% else %}no{% endif %}", {}, "no"),
  834. 'if-tag-lte-01': ("{% if 1 <= 1 %}yes{% else %}no{% endif %}", {}, "yes"),
  835. 'if-tag-lte-02': ("{% if 2 <= 1 %}yes{% else %}no{% endif %}", {}, "no"),
  836. # Contains
  837. 'if-tag-in-01': ("{% if 1 in x %}yes{% else %}no{% endif %}", {'x': [1]}, "yes"),
  838. 'if-tag-in-02': ("{% if 2 in x %}yes{% else %}no{% endif %}", {'x': [1]}, "no"),
  839. 'if-tag-not-in-01': ("{% if 1 not in x %}yes{% else %}no{% endif %}", {'x': [1]}, "no"),
  840. 'if-tag-not-in-02': ("{% if 2 not in x %}yes{% else %}no{% endif %}", {'x': [1]}, "yes"),
  841. # AND
  842. 'if-tag-and01': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
  843. 'if-tag-and02': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'no'),
  844. 'if-tag-and03': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'no'),
  845. 'if-tag-and04': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'no'),
  846. 'if-tag-and05': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': False}, 'no'),
  847. 'if-tag-and06': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'bar': False}, 'no'),
  848. 'if-tag-and07': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': True}, 'no'),
  849. 'if-tag-and08': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'bar': True}, 'no'),
  850. # OR
  851. 'if-tag-or01': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
  852. 'if-tag-or02': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'yes'),
  853. 'if-tag-or03': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'yes'),
  854. 'if-tag-or04': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'no'),
  855. 'if-tag-or05': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': False}, 'no'),
  856. 'if-tag-or06': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'bar': False}, 'no'),
  857. 'if-tag-or07': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': True}, 'yes'),
  858. 'if-tag-or08': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'bar': True}, 'yes'),
  859. # multiple ORs
  860. 'if-tag-or09': ("{% if foo or bar or baz %}yes{% else %}no{% endif %}", {'baz': True}, 'yes'),
  861. # NOT
  862. 'if-tag-not01': ("{% if not foo %}no{% else %}yes{% endif %}", {'foo': True}, 'yes'),
  863. 'if-tag-not02': ("{% if not not foo %}no{% else %}yes{% endif %}", {'foo': True}, 'no'),
  864. # not03 to not05 removed, now TemplateSyntaxErrors
  865. 'if-tag-not06': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {}, 'no'),
  866. 'if-tag-not07': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'no'),
  867. 'if-tag-not08': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'yes'),
  868. 'if-tag-not09': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'no'),
  869. 'if-tag-not10': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'no'),
  870. 'if-tag-not11': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {}, 'no'),
  871. 'if-tag-not12': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'no'),
  872. 'if-tag-not13': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'no'),
  873. 'if-tag-not14': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'yes'),
  874. 'if-tag-not15': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'no'),
  875. 'if-tag-not16': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {}, 'yes'),
  876. 'if-tag-not17': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
  877. 'if-tag-not18': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'yes'),
  878. 'if-tag-not19': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'no'),
  879. 'if-tag-not20': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'yes'),
  880. 'if-tag-not21': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {}, 'yes'),
  881. 'if-tag-not22': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
  882. 'if-tag-not23': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'no'),
  883. 'if-tag-not24': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'yes'),
  884. 'if-tag-not25': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'yes'),
  885. 'if-tag-not26': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {}, 'yes'),
  886. 'if-tag-not27': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'no'),
  887. 'if-tag-not28': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'no'),
  888. 'if-tag-not29': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'no'),
  889. 'if-tag-not30': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'yes'),
  890. 'if-tag-not31': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {}, 'yes'),
  891. 'if-tag-not32': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'no'),
  892. 'if-tag-not33': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'yes'),
  893. 'if-tag-not34': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'yes'),
  894. 'if-tag-not35': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'yes'),
  895. # Various syntax errors
  896. 'if-tag-error01': ("{% if %}yes{% endif %}", {}, template.TemplateSyntaxError),
  897. 'if-tag-error02': ("{% if foo and %}yes{% else %}no{% endif %}", {'foo': True}, template.TemplateSyntaxError),
  898. 'if-tag-error03': ("{% if foo or %}yes{% else %}no{% endif %}", {'foo': True}, template.TemplateSyntaxError),
  899. 'if-tag-error04': ("{% if not foo and %}yes{% else %}no{% endif %}", {'foo': True}, template.TemplateSyntaxError),
  900. 'if-tag-error05': ("{% if not foo or %}yes{% else %}no{% endif %}", {'foo': True}, template.TemplateSyntaxError),
  901. 'if-tag-error06': ("{% if abc def %}yes{% endif %}", {}, template.TemplateSyntaxError),
  902. 'if-tag-error07': ("{% if not %}yes{% endif %}", {}, template.TemplateSyntaxError),
  903. 'if-tag-error08': ("{% if and %}yes{% endif %}", {}, template.TemplateSyntaxError),
  904. 'if-tag-error09': ("{% if or %}yes{% endif %}", {}, template.TemplateSyntaxError),
  905. 'if-tag-error10': ("{% if == %}yes{% endif %}", {}, template.TemplateSyntaxError),
  906. 'if-tag-error11': ("{% if 1 == %}yes{% endif %}", {}, template.TemplateSyntaxError),
  907. 'if-tag-error12': ("{% if a not b %}yes{% endif %}", {}, template.TemplateSyntaxError),
  908. # If evaluations are shortcircuited where possible
  909. # If is_bad is invoked, it will raise a ShouldNotExecuteException
  910. 'if-tag-shortcircuit01': ('{% if x.is_true or x.is_bad %}yes{% else %}no{% endif %}', {'x': TestObj()}, "yes"),
  911. 'if-tag-shortcircuit02': ('{% if x.is_false and x.is_bad %}yes{% else %}no{% endif %}', {'x': TestObj()}, "no"),
  912. # Non-existent args
  913. 'if-tag-badarg01': ("{% if x|default_if_none:y %}yes{% endif %}", {}, ''),
  914. 'if-tag-badarg02': ("{% if x|default_if_none:y %}yes{% endif %}", {'y': 0}, ''),
  915. 'if-tag-badarg03': ("{% if x|default_if_none:y %}yes{% endif %}", {'y': 1}, 'yes'),
  916. 'if-tag-badarg04': ("{% if x|default_if_none:y %}yes{% else %}no{% endif %}", {}, 'no'),
  917. # Additional, more precise parsing tests are in SmartIfTests
  918. ### IFCHANGED TAG #########################################################
  919. 'ifchanged01': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', {'num': (1, 2, 3)}, '123'),
  920. 'ifchanged02': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', {'num': (1, 1, 3)}, '13'),
  921. 'ifchanged03': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', {'num': (1, 1, 1)}, '1'),
  922. 'ifchanged04': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}{% endfor %}{% endfor %}', {'num': (1, 2, 3), 'numx': (2, 2, 2)}, '122232'),
  923. 'ifchanged05': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}{% endfor %}{% endfor %}', {'num': (1, 1, 1), 'numx': (1, 2, 3)}, '1123123123'),
  924. 'ifchanged06': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}{% endfor %}{% endfor %}', {'num': (1, 1, 1), 'numx': (2, 2, 2)}, '1222'),
  925. 'ifchanged07': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}{% for y in numy %}{% ifchanged %}{{ y }}{% endifchanged %}{% endfor %}{% endfor %}{% endfor %}', {'num': (1, 1, 1), 'numx': (2, 2, 2), 'numy': (3, 3, 3)}, '1233323332333'),
  926. 'ifchanged08': ('{% for data in datalist %}{% for c,d in data %}{% if c %}{% ifchanged %}{{ d }}{% endifchanged %}{% endif %}{% endfor %}{% endfor %}', {'datalist': [[(1, 'a'), (1, 'a'), (0, 'b'), (1, 'c')], [(0, 'a'), (1, 'c'), (1, 'd'), (1, 'd'), (0, 'e')]]}, 'accd'),
  927. # Test one parameter given to ifchanged.
  928. 'ifchanged-param01': ('{% for n in num %}{% ifchanged n %}..{% endifchanged %}{{ n }}{% endfor %}', {'num': (1, 2, 3)}, '..1..2..3'),
  929. 'ifchanged-param02': ('{% for n in num %}{% for x in numx %}{% ifchanged n %}..{% endifchanged %}{{ x }}{% endfor %}{% endfor %}', {'num': (1, 2, 3), 'numx': (5, 6, 7)}, '..567..567..567'),
  930. # Test multiple parameters to ifchanged.
  931. 'ifchanged-param03': ('{% for n in num %}{{ n }}{% for x in numx %}{% ifchanged x n %}{{ x }}{% endifchanged %}{% endfor %}{% endfor %}', {'num': (1, 1, 2), 'numx': (5, 6, 6)}, '156156256'),
  932. # Test a date+hour like construct, where the hour of the last day
  933. # is the same but the date had changed, so print the hour anyway.
  934. 'ifchanged-param04': ('{% for d in days %}{% ifchanged %}{{ d.day }}{% endifchanged %}{% for h in d.hours %}{% ifchanged d h %}{{ h }}{% endifchanged %}{% endfor %}{% endfor %}', {'days': [{'day': 1, 'hours': [1, 2, 3]}, {'day': 2, 'hours': [3]}]}, '112323'),
  935. # Logically the same as above, just written with explicit
  936. # ifchanged for the day.
  937. 'ifchanged-param05': ('{% for d in days %}{% ifchanged d.day %}{{ d.day }}{% endifchanged %}{% for h in d.hours %}{% ifchanged d.day h %}{{ h }}{% endifchanged %}{% endfor %}{% endfor %}', {'days': [{'day': 1, 'hours': [1, 2, 3]}, {'day': 2, 'hours': [3]}]}, '112323'),
  938. # Test the else clause of ifchanged.
  939. 'ifchanged-else01': ('{% for id in ids %}{{ id }}{% ifchanged id %}-first{% else %}-other{% endifchanged %},{% endfor %}', {'ids': [1, 1, 2, 2, 2, 3]}, '1-first,1-other,2-first,2-other,2-other,3-first,'),
  940. 'ifchanged-else02': ('{% for id in ids %}{{ id }}-{% ifchanged id %}{% cycle red,blue %}{% else %}grey{% endifchanged %},{% endfor %}', {'ids': [1, 1, 2, 2, 2, 3]}, '1-red,1-grey,2-blue,2-grey,2-grey,3-red,'),
  941. 'ifchanged-else03': ('{% for id in ids %}{{ id }}{% ifchanged id %}-{% cycle red,blue %}{% else %}{% endifchanged %},{% endfor %}', {'ids': [1, 1, 2, 2, 2, 3]}, '1-red,1,2-blue,2,2,3-red,'),
  942. 'ifchanged-else04': ('{% for id in ids %}{% ifchanged %}***{{ id }}*{% else %}...{% endifchanged %}{{ forloop.counter }}{% endfor %}', {'ids': [1, 1, 2, 2, 2, 3, 4]}, '***1*1...2***2*3...4...5***3*6***4*7'),
  943. # Test whitespace in filter arguments
  944. 'ifchanged-filter-ws': ('{% load custom %}{% for n in num %}{% ifchanged n|noop:"x y" %}..{% endifchanged %}{{ n }}{% endfor %}', {'num': (1, 2, 3)}, '..1..2..3'),
  945. ### IFEQUAL TAG ###########################################################
  946. 'ifequal01': ("{% ifequal a b %}yes{% endifequal %}", {"a": 1, "b": 2}, ""),
  947. 'ifequal02': ("{% ifequal a b %}yes{% endifequal %}", {"a": 1, "b": 1}, "yes"),
  948. 'ifequal03': ("{% ifequal a b %}yes{% else %}no{% endifequal %}", {"a": 1, "b": 2}, "no"),
  949. 'ifequal04': ("{% ifequal a b %}yes{% else %}no{% endifequal %}", {"a": 1, "b": 1}, "yes"),
  950. 'ifequal05': ("{% ifequal a 'test' %}yes{% else %}no{% endifequal %}", {"a": "test"}, "yes"),
  951. 'ifequal06': ("{% ifequal a 'test' %}yes{% else %}no{% endifequal %}", {"a": "no"}, "no"),
  952. 'ifequal07': ('{% ifequal a "test" %}yes{% else %}no{% endifequal %}', {"a": "test"}, "yes"),
  953. 'ifequal08': ('{% ifequal a "test" %}yes{% else %}no{% endifequal %}', {"a": "no"}, "no"),
  954. 'ifequal09': ('{% ifequal a "test" %}yes{% else %}no{% endifequal %}', {}, "no"),
  955. 'ifequal10': ('{% ifequal a b %}yes{% else %}no{% endifequal %}', {}, "yes"),
  956. # SMART SPLITTING
  957. 'ifequal-split01': ('{% ifequal a "test man" %}yes{% else %}no{% endifequal %}', {}, "no"),
  958. 'ifequal-split02': ('{% ifequal a "test man" %}yes{% else %}no{% endifequal %}', {'a': 'foo'}, "no"),
  959. 'ifequal-split03': ('{% ifequal a "test man" %}yes{% else %}no{% endifequal %}', {'a': 'test man'}, "yes"),
  960. 'ifequal-split04': ("{% ifequal a 'test man' %}yes{% else %}no{% endifequal %}", {'a': 'test man'}, "yes"),
  961. 'ifequal-split05': ("{% ifequal a 'i \"love\" you' %}yes{% else %}no{% endifequal %}", {'a': ''}, "no"),
  962. 'ifequal-split06': ("{% ifequal a 'i \"love\" you' %}yes{% else %}no{% endifequal %}", {'a': 'i "love" you'}, "yes"),
  963. 'ifequal-split07': ("{% ifequal a 'i \"love\" you' %}yes{% else %}no{% endifequal %}", {'a': 'i love you'}, "no"),
  964. 'ifequal-split08': (r"{% ifequal a 'I\'m happy' %}yes{% else %}no{% endifequal %}", {'a': "I'm happy"}, "yes"),
  965. 'ifequal-split09': (r"{% ifequal a 'slash\man' %}yes{% else %}no{% endifequal %}", {'a': r"slash\man"}, "yes"),
  966. 'ifequal-split10': (r"{% ifequal a 'slash\man' %}yes{% else %}no{% endifequal %}", {'a': r"slashman"}, "no"),
  967. # NUMERIC RESOLUTION
  968. 'ifequal-numeric01': ('{% ifequal x 5 %}yes{% endifequal %}', {'x': '5'}, ''),
  969. 'ifequal-numeric02': ('{% ifequal x 5 %}yes{% endifequal %}', {'x': 5}, 'yes'),
  970. 'ifequal-numeric03': ('{% ifequal x 5.2 %}yes{% endifequal %}', {'x': 5}, ''),
  971. 'ifequal-numeric04': ('{% ifequal x 5.2 %}yes{% endifequal %}', {'x': 5.2}, 'yes'),
  972. 'ifequal-numeric05': ('{% ifequal x 0.2 %}yes{% endifequal %}', {'x': .2}, 'yes'),
  973. 'ifequal-numeric06': ('{% ifequal x .2 %}yes{% endifequal %}', {'x': .2}, 'yes'),
  974. 'ifequal-numeric07': ('{% ifequal x 2. %}yes{% endifequal %}', {'x': 2}, ''),
  975. 'ifequal-numeric08': ('{% ifequal x "5" %}yes{% endifequal %}', {'x': 5}, ''),
  976. 'ifequal-numeric09': ('{% ifequal x "5" %}yes{% endifequal %}', {'x': '5'}, 'yes'),
  977. 'ifequal-numeric10': ('{% ifequal x -5 %}yes{% endifequal %}', {'x': -5}, 'yes'),
  978. 'ifequal-numeric11': ('{% ifequal x -5.2 %}yes{% endifequal %}', {'x': -5.2}, 'yes'),
  979. 'ifequal-numeric12': ('{% ifequal x +5 %}yes{% endifequal %}', {'x': 5}, 'yes'),
  980. # FILTER EXPRESSIONS AS ARGUMENTS
  981. 'ifequal-filter01': ('{% ifequal a|upper "A" %}x{% endifequal %}', {'a': 'a'}, 'x'),
  982. 'ifequal-filter02': ('{% ifequal "A" a|upper %}x{% endifequal %}', {'a': 'a'}, 'x'),
  983. 'ifequal-filter03': ('{% ifequal a|upper b|upper %}x{% endifequal %}', {'a': 'x', 'b': 'X'}, 'x'),
  984. 'ifequal-filter04': ('{% ifequal x|slice:"1" "a" %}x{% endifequal %}', {'x': 'aaa'}, 'x'),
  985. 'ifequal-filter05': ('{% ifequal x|slice:"1"|upper "A" %}x{% endifequal %}', {'x': 'aaa'}, 'x'),
  986. ### IFNOTEQUAL TAG ########################################################
  987. 'ifnotequal01': ("{% ifnotequal a b %}yes{% endifnotequal %}", {"a": 1, "b": 2}, "yes"),
  988. 'ifnotequal02': ("{% ifnotequal a b %}yes{% endifnotequal %}", {"a": 1, "b": 1}, ""),
  989. 'ifnotequal03': ("{% ifnotequal a b %}yes{% else %}no{% endifnotequal %}", {"a": 1, "b": 2}, "yes"),
  990. 'ifnotequal04': ("{% ifnotequal a b %}yes{% else %}no{% endifnotequal %}", {"a": 1, "b": 1}, "no"),
  991. ## INCLUDE TAG ###########################################################
  992. 'include01': ('{% include "basic-syntax01" %}', {}, "something cool"),
  993. 'include02': ('{% include "basic-syntax02" %}', {'headline': 'Included'}, "Included"),
  994. 'include03': ('{% include template_name %}', {'template_name': 'basic-syntax02', 'headline': 'Included'}, "Included"),
  995. 'include04': ('a{% include "nonexistent" %}b', {}, ("ab", "ab", template.TemplateDoesNotExist)),
  996. 'include 05': ('template with a space', {}, 'template with a space'),
  997. 'include06': ('{% include "include 05"%}', {}, 'template with a space'),
  998. # extra inline context
  999. 'include07': ('{% include "basic-syntax02" with headline="Inline" %}', {'headline': 'Included'}, 'Inline'),
  1000. 'include08': ('{% include headline with headline="Dynamic" %}', {'headline': 'basic-syntax02'}, 'Dynamic'),
  1001. 'include09': ('{{ first }}--{% include "basic-syntax03" with first=second|lower|upper second=first|upper %}--{{ second }}', {'first': 'Ul', 'second': 'lU'}, 'Ul--LU --- UL--lU'),
  1002. # isolated context
  1003. 'include10': ('{% include "basic-syntax03" only %}', {'first': '1'}, (' --- ', 'INVALID --- INVALID')),
  1004. 'include11': ('{% include "basic-syntax03" only with second=2 %}', {'first': '1'}, (' --- 2', 'INVALID --- 2')),
  1005. 'include12': ('{% include "basic-syntax03" with first=1 only %}', {'second': '2'}, ('1 --- ', '1 --- INVALID')),
  1006. # autoescape context
  1007. 'include13': ('{% autoescape off %}{% include "basic-syntax03" %}{% endautoescape %}', {'first': '&'}, ('& --- ', '& --- INVALID')),
  1008. 'include14': ('{% autoescape off %}{% include "basic-syntax03" with first=var1 only %}{% endautoescape %}', {'var1': '&'}, ('& --- ', '& --- INVALID')),
  1009. 'include-error01': ('{% include "basic-syntax01" with %}', {}, template.TemplateSyntaxError),
  1010. 'include-error02': ('{% include "basic-syntax01" with "no key" %}', {}, template.TemplateSyntaxError),
  1011. 'include-error03': ('{% include "basic-syntax01" with dotted.arg="error" %}', {}, template.TemplateSyntaxError),
  1012. 'include-error04': ('{% include "basic-syntax01" something_random %}', {}, template.TemplateSyntaxError),
  1013. 'include-error05': ('{% include "basic-syntax01" foo="duplicate" foo="key" %}', {}, template.TemplateSyntaxError),
  1014. 'include-error06': ('{% include "basic-syntax01" only only %}', {}, template.TemplateSyntaxError),
  1015. ### INCLUSION ERROR REPORTING #############################################
  1016. 'include-fail1': ('{% load bad_tag %}{% badtag %}', {}, RuntimeError),
  1017. 'include-fail2': ('{% load broken_tag %}', {}, template.TemplateSyntaxError),
  1018. 'include-error07': ('{% include "include-fail1" %}', {}, ('', '', RuntimeError)),
  1019. 'include-error08': ('{% include "include-fail2" %}', {}, ('', '', template.TemplateSyntaxError)),
  1020. 'include-error09': ('{% include failed_include %}', {'failed_include': 'include-fail1'}, ('', '', RuntimeError)),
  1021. 'include-error10': ('{% include failed_include %}', {'failed_include': 'include-fail2'}, ('', '', template.TemplateSyntaxError)),
  1022. ### NAMED ENDBLOCKS #######################################################
  1023. # Basic test
  1024. 'namedendblocks01': ("1{% block first %}_{% block second %}2{% endblock second %}_{% endblock first %}3", {}, '1_2_3'),
  1025. # Unbalanced blocks
  1026. 'namedendblocks02': ("1{% block first %}_{% block second %}2{% endblock first %}_{% endblock second %}3", {}, template.TemplateSyntaxError),
  1027. 'namedendblocks03': ("1{% block first %}_{% block second %}2{% endblock %}_{% endblock second %}3", {}, template.TemplateSyntaxError),
  1028. 'namedendblocks04': ("1{% block first %}_{% block second %}2{% endblock second %}_{% endblock third %}3", {}, template.TemplateSyntaxError),
  1029. 'namedendblocks05': ("1{% block first %}_{% block second %}2{% endblock first %}", {}, template.TemplateSyntaxError),
  1030. # Mixed named and unnamed endblocks
  1031. 'namedendblocks06': ("1{% block first %}_{% block second %}2{% endblock %}_{% endblock first %}3", {}, '1_2_3'),
  1032. 'namedendblocks07': ("1{% block first %}_{% block second %}2{% endblock second %}_{% endblock %}3", {}, '1_2_3'),
  1033. ### INHERITANCE ###########################################################
  1034. # Standard template with no inheritance
  1035. 'inheritance01': ("1{% block first %}&{% endblock %}3{% block second %}_{% endblock %}", {}, '1&3_'),
  1036. # Standard two-level inheritance
  1037. 'inheritance02': ("{% extends 'inheritance01' %}{% block first %}2{% endblock %}{% block second %}4{% endblock %}", {}, '1234'),
  1038. # Three-level with no redefinitions on third level
  1039. 'inheritance03': ("{% extends 'inheritance02' %}", {}, '1234'),
  1040. # Two-level with no redefinitions on second level
  1041. 'inheritance04': ("{% extends 'inheritance01' %}", {}, '1&3_'),
  1042. # Two-level with double quotes instead of single quotes
  1043. 'inheritance05': ('{% extends "inheritance02" %}', {}, '1234'),
  1044. # Three-level with variable parent-template name
  1045. 'inheritance06': ("{% extends foo %}", {'foo': 'inheritance02'}, '1234'),
  1046. # Two-level with one block defined, one block not defined
  1047. 'inheritance07': ("{% extends 'inheritance01' %}{% block second %}5{% endblock %}", {}, '1&35'),
  1048. # Three-level with one block defined on this level, two blocks defined next level
  1049. 'inheritance08': ("{% extends 'inheritance02' %}{% block second %}5{% endblock %}", {}, '1235'),
  1050. # Three-level with second and third levels blank
  1051. 'inheritance09': ("{% extends 'inheritance04' %}", {}, '1&3_'),
  1052. # Three-level with space NOT in a block -- should be ignored
  1053. 'inheritance10': ("{% extends 'inheritance04' %} ", {}, '1&3_'),
  1054. # Three-level with both blocks defined on this level, but none on second level
  1055. 'inheritance11': ("{% extends 'inheritance04' %}{% block first %}2{% endblock %}{% block second %}4{% endblock %}", {}, '1234'),
  1056. # Three-level with this level providing one and second level providing the other
  1057. 'inheritance12': ("{% extends 'inheritance07' %}{% block first %}2{% endblock %}", {}, '1235'),
  1058. # Three-level with this level overriding second level
  1059. 'inheritance13': ("{% extends 'inheritance02' %}{% block first %}a{% endblock %}{% block second %}b{% endblock %}", {}, '1a3b'),
  1060. # A block defined only in a child template shouldn't be displayed
  1061. 'inheritance14': ("{% extends 'inheritance01' %}{% block newblock %}NO DISPLAY{% endblock %}", {}, '1&3_'),
  1062. # A block within another block
  1063. 'inheritance15': ("{% extends 'inheritance01' %}{% block first %}2{% block inner %}inner{% endblock %}{% endblock %}", {}, '12inner3_'),
  1064. # A block within another block (level 2)
  1065. 'inheritance16': ("{% extends 'inheritance15' %}{% block inner %}out{% endblock %}", {}, '12out3_'),
  1066. # {% load %} tag (parent -- setup for exception04)
  1067. 'inheritance17': ("{% load testtags %}{% block first %}1234{% endblock %}", {}, '1234'),
  1068. # {% load %} tag (standard usage, without inheritance)
  1069. 'inheritance18': ("{% load testtags %}{% echo this that theother %}5678", {}, 'this that theother5678'),
  1070. # {% load %} tag (within a child template)
  1071. 'inheritance19': ("{% extends 'inheritance01' %}{% block first %}{% load testtags %}{% echo 400 %}5678{% endblock %}", {}, '140056783_'),
  1072. # Two-level inheritance with {{ block.super }}
  1073. 'inheritance20': ("{% extends 'inheritance01' %}{% block first %}{{ block.super }}a{% endblock %}", {}, '1&a3_'),
  1074. # Three-level inheritance with {{ block.super }} from parent
  1075. 'inheritance21': ("{% extends 'inheritance02' %}{% block first %}{{ block.super }}a{% endblock %}", {}, '12a34'),
  1076. # Three-level inheritance with {{ block.super }} from grandparent
  1077. 'inheritance22': ("{% extends 'inheritance04' %}{% block first %}{{ block.super }}a{% endblock %}", {}, '1&a3_'),
  1078. # Three-level inheritance with {{ block.super }} from parent and grandparent
  1079. 'inheritance23': ("{% extends 'inheritance20' %}{% block first %}{{ block.super }}b{% endblock %}", {}, '1&ab3_'),
  1080. # Inheritance from local context without use of template loader
  1081. 'inheritance24': ("{% extends context_template %}{% block first %}2{% endblock %}{% block second %}4{% endblock %}", {'context_template': template.Template("1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}")}, '1234'),
  1082. # Inheritance from local context with variable parent template
  1083. 'inheritance25': ("{% extends context_template.1 %}{% block first %}2{% endblock %}{% block second %}4{% endblock %}", {'context_template': [template.Template("Wrong"), template.Template("1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}")]}, '1234'),
  1084. # Set up a base template to extend
  1085. 'inheritance26': ("no tags", {}, 'no tags'),
  1086. # Inheritance from a template that doesn't have any blocks
  1087. 'inheritance27': ("{% extends 'inheritance26' %}", {}, 'no tags'),
  1088. # Set up a base template with a space in it.
  1089. 'inheritance 28': ("{% block first %}!{% endblock %}", {}, '!'),
  1090. # Inheritance from a template with a space in its name should work.
  1091. 'inheritance29': ("{% extends 'inheritance 28' %}", {}, '!'),
  1092. # Base template, putting block in a conditional {% if %} tag
  1093. 'inheritance30': ("1{% if optional %}{% block opt %}2{% endblock %}{% endif %}3", {'optional': True}, '123'),
  1094. # Inherit from a template with block wrapped in an {% if %} tag (in parent), still gets overridden
  1095. 'inheritance31': ("{% extends 'inheritance30' %}{% block opt %}two{% endblock %}", {'optional': True}, '1two3'),
  1096. 'inheritance32': ("{% extends 'inheritance30' %}{% block opt %}two{% endblock %}", {}, '13'),
  1097. # Base template, putting block in a conditional {% ifequal %} tag
  1098. 'inheritance33': ("1{% ifequal optional 1 %}{% block opt %}2{% endblock %}{% endifequal %}3", {'optional': 1}, '123'),
  1099. # Inherit from a template with block wrapped in an {% ifequal %} tag (in parent), still gets overridden
  1100. 'inheritance34': ("{% extends 'inheritance33' %}{% block opt %}two{% endblock %}", {'optional': 1}, '1two3'),
  1101. 'inheritance35': ("{% extends 'inheritance33' %}{% block opt %}two{% endblock %}", {'optional': 2}, '13'),
  1102. # Base template, putting block in a {% for %} tag
  1103. 'inheritance36': ("{% for n in numbers %}_{% block opt %}{{ n }}{% endblock %}{% endfor %}_", {'numbers': '123'}, '_1_2_3_'),
  1104. # Inherit from a template with block wrapped in an {% for %} tag (in parent), still gets overridden
  1105. 'inheritance37': ("{% extends 'inheritance36' %}{% block opt %}X{% endblock %}", {'numbers': '123'}, '_X_X_X_'),
  1106. 'inheritance38': ("{% extends 'inheritance36' %}{% block opt %}X{% endblock %}", {}, '_'),
  1107. # The super block will still be found.
  1108. 'inheritance39': ("{% extends 'inheritance30' %}{% block opt %}new{{ block.super }}{% endblock %}", {'optional': True}, '1new23'),
  1109. 'inheritance40': ("{% extends 'inheritance33' %}{% block opt %}new{{ block.super }}{% endblock %}", {'optional': 1}, '1new23'),
  1110. 'inheritance41': ("{% extends 'inheritance36' %}{% block opt %}new{{ block.super }}{% endblock %}", {'numbers': '123'}, '_new1_new2_new3_'),
  1111. # Expression starting and ending with a quote
  1112. 'inheritance42': ("{% extends 'inheritance02'|cut:' ' %}", {}, '1234'),
  1113. ### LOADING TAG LIBRARIES #################################################
  1114. 'load01': ("{% load testtags subpackage.echo %}{% echo test %} {% echo2 \"test\" %}", {}, "test test"),
  1115. 'load02': ("{% load subpackage.echo %}{% echo2 \"test\" %}", {}, "test"),
  1116. # {% load %} tag, importing individual tags
  1117. 'load03': ("{% load echo from testtags %}{% echo this that theother %}", {}, 'this that theother'),
  1118. 'load04': ("{% load echo other_echo from testtags %}{% echo this that theother %} {% other_echo and another thing %}", {}, 'this that theother and another thing'),
  1119. 'load05': ("{% load echo upper from testtags %}{% echo this that theother %} {{ statement|upper }}", {'statement': 'not shouting'}, 'this that theother NOT SHOUTING'),
  1120. 'load06': ("{% load echo2 from subpackage.echo %}{% echo2 \"test\" %}", {}, "test"),
  1121. # {% load %} tag errors
  1122. 'load07': ("{% load echo other_echo bad_tag from testtags %}", {}, template.TemplateSyntaxError),
  1123. 'load08': ("{% load echo other_echo bad_tag from %}", {}, template.TemplateSyntaxError),
  1124. 'load09': ("{% load from testtags %}", {}, template.TemplateSyntaxError),
  1125. 'load10': ("{% load echo from bad_library %}", {}, template.TemplateSyntaxError),
  1126. 'load11': ("{% load subpackage.echo_invalid %}", {}, template.TemplateSyntaxError),
  1127. 'load12': ("{% load subpackage.missing %}", {}, template.TemplateSyntaxError),
  1128. ### I18N ##################################################################
  1129. # {% spaceless %} tag
  1130. 'spaceless01': ("{% spaceless %} <b> <i> text </i> </b> {% endspaceless %}", {}, "<b><i> text </i></b>"),
  1131. 'spaceless02': ("{% spaceless %} <b> \n <i> text </i> \n </b> {% endspaceless %}", {}, "<b><i> text </i></b>"),
  1132. 'spaceless03': ("{% spaceless %}<b><i>text</i></b>{% endspaceless %}", {}, "<b><i>text</i></b>"),
  1133. 'spaceless04': ("{% spaceless %}<b> <i>{{ text }}</i> </b>{% endspaceless %}", {'text': 'This & that'}, "<b><i>This &amp; that</i></b>"),
  1134. 'spaceless05': ("{% autoescape off %}{% spaceless %}<b> <i>{{ text }}</i> </b>{% endspaceless %}{% endautoescape %}", {'text': 'This & that'}, "<b><i>This & that</i></b>"),
  1135. 'spaceless06': ("{% spaceless %}<b> <i>{{ text|safe }}</i> </b>{% endspaceless %}", {'text': 'This & that'}, "<b><i>This & that</i></b>"),
  1136. # simple translation of a string delimited by '
  1137. 'i18n01': ("{% load i18n %}{% trans 'xxxyyyxxx' %}", {}, "xxxyyyxxx"),
  1138. # simple translation of a string delimited by "
  1139. 'i18n02': ('{% load i18n %}{% trans "xxxyyyxxx" %}', {}, "xxxyyyxxx"),
  1140. # simple translation of a variable
  1141. 'i18n03': ('{% load i18n %}{% blocktrans %}{{ anton }}{% endblocktrans %}', {'anton': b'\xc3\x85'}, "Å"),
  1142. # simple translation of a variable and filter
  1143. 'i18n04': ('{% load i18n %}{% blocktrans with berta=anton|lower %}{{ berta }}{% endblocktrans %}', {'anton': b'\xc3\x85'}, 'å'),
  1144. 'legacyi18n04': ('{% load i18n %}{% blocktrans with anton|lower as berta %}{{ berta }}{% endblocktrans %}', {'anton': b'\xc3\x85'}, 'å'),
  1145. # simple translation of a string with interpolation
  1146. 'i18n05': ('{% load i18n %}{% blocktrans %}xxx{{ anton }}xxx{% endblocktrans %}', {'anton': 'yyy'}, "xxxyyyxxx"),
  1147. # simple translation of a string to german
  1148. 'i18n06': ('{% load i18n %}{% trans "Page not found" %}', {'LANGUAGE_CODE': 'de'}, "Seite nicht gefunden"),
  1149. # translation of singular form
  1150. 'i18n07': ('{% load i18n %}{% blocktrans count counter=number %}singular{% plural %}{{ counter }} plural{% endblocktrans %}', {'number': 1}, "singular"),
  1151. 'legacyi18n07': ('{% load i18n %}{% blocktrans count number as counter %}singular{% plural %}{{ counter }} plural{% endblocktrans %}', {'number': 1}, "singular"),
  1152. # translation of plural form
  1153. 'i18n08': ('{% load i18n %}{% blocktrans count number as counter %}singular{% plural %}{{ counter }} plural{% endblocktrans %}', {'number': 2}, "2 plural"),
  1154. 'legacyi18n08': ('{% load i18n %}{% blocktrans count counter=number %}singular{% plural %}{{ counter }} plural{% endblocktrans %}', {'number': 2}, "2 plural"),
  1155. # simple non-translation (only marking) of a string to german
  1156. 'i18n09': ('{% load i18n %}{% trans "Page not found" noop %}', {'LANGUAGE_CODE': 'de'}, "Page not found"),
  1157. # translation of a variable with a translated filter
  1158. 'i18n10': ('{{ bool|yesno:_("yes,no,maybe") }}', {'bool': True, 'LANGUAGE_CODE': 'de'}, 'Ja'),
  1159. # translation of a variable with a non-translated filter
  1160. 'i18n11': ('{{ bool|yesno:"ja,nein" }}', {'bool': True}, 'ja'),
  1161. # usage of the get_available_languages tag
  1162. 'i18n12': ('{% load i18n %}{% get_available_languages as langs %}{% for lang in langs %}{% ifequal lang.0 "de" %}{{ lang.0 }}{% endifequal %}{% endfor %}', {}, 'de'),
  1163. # translation of constant strings
  1164. 'i18n13': ('{{ _("Password") }}', {'LANGUAGE_CODE': 'de'}, 'Passwort'),
  1165. 'i18n14': ('{% cycle "foo" _("Password") _(\'Password\') as c %} {% cycle c %} {% cycle c %}', {'LANGUAGE_CODE': 'de'}, 'foo Passwort Passwort'),
  1166. 'i18n15': ('{{ absent|default:_("Password") }}', {'LANGUAGE_CODE': 'de', 'absent': ""}, 'Passwort'),
  1167. 'i18n16': ('{{ _("<") }}', {'LANGUAGE_CODE': 'de'}, '<'),
  1168. # Escaping inside blocktrans and trans works as if it was directly in the
  1169. # template.
  1170. 'i18n17': ('{% load i18n %}{% blocktrans with berta=anton|escape %}{{ berta }}{% endblocktrans %}', {'anton': 'α & β'}, 'α &amp; β'),
  1171. 'i18n18': ('{% load i18n %}{% blocktrans with berta=anton|force_escape %}{{ berta }}{% endblocktrans %}', {'anton': 'α & β'}, 'α &amp; β'),
  1172. 'i18n19': ('{% load i18n %}{% blocktrans %}{{ andrew }}{% endblocktrans %}', {'andrew': 'a & b'}, 'a &amp; b'),
  1173. 'i18n20': ('{% load i18n %}{% trans andrew %}', {'andrew': 'a & b'}, 'a &amp; b'),
  1174. 'i18n21': ('{% load i18n %}{% blocktrans %}{{ andrew }}{% endblocktrans %}', {'andrew': mark_safe('a & b')}, 'a & b'),
  1175. 'i18n22': ('{% load i18n %}{% trans andrew %}', {'andrew': mark_safe('a & b')}, 'a & b'),
  1176. 'legacyi18n17': ('{% load i18n %}{% blocktrans with anton|escape as berta %}{{ berta }}{% endblocktrans %}', {'anton': 'α & β'}, 'α &amp; β'),
  1177. 'legacyi18n18': ('{% load i18n %}{% blocktrans with anton|force_escape as berta %}{{ berta }}{% endblocktrans %}', {'anton': 'α & β'}, 'α &amp; β'),
  1178. # Use filters with the {% trans %} tag, #5972
  1179. 'i18n23': ('{% load i18n %}{% trans "Page not found"|capfirst|slice:"6:" %}', {'LANGUAGE_CODE': 'de'}, 'nicht gefunden'),
  1180. 'i18n24': ("{% load i18n %}{% trans 'Page not found'|upper %}", {'LANGUAGE_CODE': 'de'}, 'SEITE NICHT GEFUNDEN'),
  1181. 'i18n25': ('{% load i18n %}{% trans somevar|upper %}', {'somevar': 'Page not found', 'LANGUAGE_CODE': 'de'}, 'SEITE NICHT GEFUNDEN'),
  1182. # translation of plural form with extra field in singular form (#13568)
  1183. 'i18n26': ('{% load i18n %}{% blocktrans with extra_field=myextra_field count counter=number %}singular {{ extra_field }}{% plural %}plural{% endblocktrans %}', {'number': 1, 'myextra_field': 'test'}, "singular test"),
  1184. 'legacyi18n26': ('{% load i18n %}{% blocktrans with myextra_field as extra_field count number as counter %}singular {{ extra_field }}{% plural %}plural{% endblocktrans %}', {'number': 1, 'myextra_field': 'test'}, "singular test"),
  1185. # translation of singular form in russian (#14126)
  1186. 'i18n27': ('{% load i18n %}{% blocktrans count counter=number %}{{ counter }} result{% plural %}{{ counter }} results{% endblocktrans %}', {'number': 1, 'LANGUAGE_CODE': 'ru'}, '1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442'),
  1187. 'legacyi18n27': ('{% load i18n %}{% blocktrans count number as counter %}{{ counter }} result{% plural %}{{ counter }} results{% endblocktrans %}', {'number': 1, 'LANGUAGE_CODE': 'ru'}, '1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442'),
  1188. # simple translation of multiple variables
  1189. 'i18n28': ('{% load i18n %}{% blocktrans with a=anton b=berta %}{{ a }} + {{ b }}{% endblocktrans %}', {'anton': 'α', 'berta': 'β'}, 'α + β'),
  1190. 'legacyi18n28': ('{% load i18n %}{% blocktrans with anton as a and berta as b %}{{ a }} + {{ b }}{% endblocktrans %}', {'anton': 'α', 'berta': 'β'}, 'α + β'),
  1191. # retrieving language information
  1192. 'i18n28_2': ('{% load i18n %}{% get_language_info for "de" as l %}{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}', {}, 'de: German/Deutsch bidi=False'),
  1193. 'i18n29': ('{% load i18n %}{% get_language_info for LANGUAGE_CODE as l %}{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}', {'LANGUAGE_CODE': 'fi'}, 'fi: Finnish/suomi bidi=False'),
  1194. 'i18n30': ('{% load i18n %}{% get_language_info_list for langcodes as langs %}{% for l in langs %}{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}', {'langcodes': ['it', 'no']}, 'it: Italian/italiano bidi=False; no: Norwegian/norsk bidi=False; '),
  1195. 'i18n31': ('{% load i18n %}{% get_language_info_list for langcodes as langs %}{% for l in langs %}{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}', {'langcodes': (('sl', 'Slovenian'), ('fa', 'Persian'))}, 'sl: Slovenian/Sloven\u0161\u010dina bidi=False; fa: Persian/\u0641\u0627\u0631\u0633\u06cc bidi=True; '),
  1196. 'i18n32': ('{% load i18n %}{{ "hu"|language_name }} {{ "hu"|language_name_local }} {{ "hu"|language_bidi }}', {}, 'Hungarian Magyar False'),
  1197. 'i18n33': ('{% load i18n %}{{ langcode|language_name }} {{ langcode|language_name_local }} {{ langcode|language_bidi }}', {'langcode': 'nl'}, 'Dutch Nederlands False'),
  1198. # blocktrans handling of variables which are not in the context.
  1199. # this should work as if blocktrans was not there (bug #19915)
  1200. 'i18n34': ('{% load i18n %}{% blocktrans %}{{ missing }}{% endblocktrans %}', {}, ('', 'INVALID')),
  1201. 'i18n34_2': ("{% load i18n %}{% blocktrans with a='α' %}{{ missing }}{% endblocktrans %}", {}, ('', 'INVALID')),
  1202. 'i18n34_3': ('{% load i18n %}{% blocktrans with a=anton %}{{ missing }}{% endblocktrans %}', {'anton': 'α'}, ('', 'INVALID')),
  1203. # trans tag with as var
  1204. 'i18n35': ('{% load i18n %}{% trans "Page not found" as page_not_found %}{{ page_not_found }}', {'LANGUAGE_CODE': 'de'}, "Seite nicht gefunden"),
  1205. 'i18n36': ('{% load i18n %}{% trans "Page not found" noop as page_not_found %}{{ page_not_found }}', {'LANGUAGE_CODE': 'de'}, "Page not found"),
  1206. 'i18n36': ('{% load i18n %}{% trans "Page not found" as page_not_found noop %}{{ page_not_found }}', {'LANGUAGE_CODE': 'de'}, "Page not found"),
  1207. 'i18n37': ('{% load i18n %}{% trans "Page not found" as page_not_found %}{% blocktrans %}Error: {{ page_not_found }}{% endblocktrans %}', {'LANGUAGE_CODE': 'de'}, "Error: Seite nicht gefunden"),
  1208. # Test whitespace in filter arguments
  1209. 'i18n38': ('{% load i18n custom %}{% get_language_info for "de"|noop:"x y" as l %}{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}', {}, 'de: German/Deutsch bidi=False'),
  1210. 'i18n38_2': ('{% load i18n custom %}{% get_language_info_list for langcodes|noop:"x y" as langs %}{% for l in langs %}{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}', {'langcodes': ['it', 'no']}, 'it: Italian/italiano bidi=False; no: Norwegian/norsk bidi=False; '),
  1211. ### HANDLING OF TEMPLATE_STRING_IF_INVALID ###################################
  1212. 'invalidstr01': ('{{ var|default:"Foo" }}', {}, ('Foo', 'INVALID')),
  1213. 'invalidstr02': ('{{ var|default_if_none:"Foo" }}', {}, ('', 'INVALID')),
  1214. 'invalidstr03': ('{% for v in var %}({{ v }}){% endfor %}', {}, ''),
  1215. 'invalidstr04': ('{% if var %}Yes{% else %}No{% endif %}', {}, 'No'),
  1216. 'invalidstr04_2': ('{% if var|default:"Foo" %}Yes{% else %}No{% endif %}', {}, 'Yes'),
  1217. 'invalidstr05': ('{{ var }}', {}, ('', ('INVALID %s', 'var'))),
  1218. 'invalidstr06': ('{{ var.prop }}', {'var': {}}, ('', ('INVALID %s', 'var.prop'))),
  1219. ### MULTILINE #############################################################
  1220. 'multiline01': ("""
  1221. Hello,
  1222. boys.
  1223. How
  1224. are
  1225. you
  1226. gentlemen.
  1227. """,
  1228. {},
  1229. """
  1230. Hello,
  1231. boys.
  1232. How
  1233. are
  1234. you
  1235. gentlemen.
  1236. """),
  1237. ### REGROUP TAG ###########################################################
  1238. 'regroup01': ('{% regroup data by bar as grouped %}'
  1239. '{% for group in grouped %}'
  1240. '{{ group.grouper }}:'
  1241. '{% for item in group.list %}'
  1242. '{{ item.foo }}'
  1243. '{% endfor %},'
  1244. '{% endfor %}',
  1245. {'data': [{'foo': 'c', 'bar': 1},
  1246. {'foo': 'd', 'bar': 1},
  1247. {'foo': 'a', 'bar': 2},
  1248. {'foo': 'b', 'bar': 2},
  1249. {'foo': 'x', 'bar': 3}]},
  1250. '1:cd,2:ab,3:x,'),
  1251. # Test for silent failure when target variable isn't found
  1252. 'regroup02': ('{% regroup data by bar as grouped %}'
  1253. '{% for group in grouped %}'
  1254. '{{ group.grouper }}:'
  1255. '{% for item in group.list %}'
  1256. '{{ item.foo }}'
  1257. '{% endfor %},'
  1258. '{% endfor %}',
  1259. {}, ''),
  1260. # Regression tests for #17675
  1261. # The date template filter has expects_localtime = True
  1262. 'regroup03': ('{% regroup data by at|date:"m" as grouped %}'
  1263. '{% for group in grouped %}'
  1264. '{{ group.grouper }}:'
  1265. '{% for item in group.list %}'
  1266. '{{ item.at|date:"d" }}'
  1267. '{% endfor %},'
  1268. '{% endfor %}',
  1269. {'data': [{'at': date(2012, 2, 14)},
  1270. {'at': date(2012, 2, 28)},
  1271. {'at': date(2012, 7, 4)}]},
  1272. '02:1428,07:04,'),
  1273. # The join template filter has needs_autoescape = True
  1274. 'regroup04': ('{% regroup data by bar|join:"" as grouped %}'
  1275. '{% for group in grouped %}'
  1276. '{{ group.grouper }}:'
  1277. '{% for item in group.list %}'
  1278. '{{ item.foo|first }}'
  1279. '{% endfor %},'
  1280. '{% endfor %}',
  1281. {'data': [{'foo': 'x', 'bar': ['ab', 'c']},
  1282. {'foo': 'y', 'bar': ['a', 'bc']},
  1283. {'foo': 'z', 'bar': ['a', 'd']}]},
  1284. 'abc:xy,ad:z,'),
  1285. # Test syntax
  1286. 'regroup05': ('{% regroup data by bar as %}', {},
  1287. template.TemplateSyntaxError),
  1288. 'regroup06': ('{% regroup data by bar thisaintright grouped %}', {},
  1289. template.TemplateSyntaxError),
  1290. 'regroup07': ('{% regroup data thisaintright bar as grouped %}', {},
  1291. template.TemplateSyntaxError),
  1292. 'regroup08': ('{% regroup data by bar as grouped toomanyargs %}', {},
  1293. template.TemplateSyntaxError),
  1294. ### SSI TAG ########################################################
  1295. # Test normal behavior
  1296. 'ssi01': ('{%% ssi "%s" %%}' % os.path.join(basedir, 'templates', 'ssi_include.html'), {}, 'This is for testing an ssi include. {{ test }}\n'),
  1297. 'ssi02': ('{%% ssi "%s" %%}' % os.path.join(basedir, 'not_here'), {}, ''),
  1298. 'ssi03': ("{%% ssi '%s' %%}" % os.path.join(basedir, 'not_here'), {}, ''),
  1299. # Test passing as a variable
  1300. 'ssi04': ('{% load ssi from future %}{% ssi ssi_file %}', {'ssi_file': os.path.join(basedir, 'templates', 'ssi_include.html')}, 'This is for testing an ssi include. {{ test }}\n'),
  1301. 'ssi05': ('{% load ssi from future %}{% ssi ssi_file %}', {'ssi_file': 'no_file'}, ''),
  1302. # Test parsed output
  1303. 'ssi06': ('{%% ssi "%s" parsed %%}' % os.path.join(basedir, 'templates', 'ssi_include.html'), {'test': 'Look ma! It parsed!'}, 'This is for testing an ssi include. Look ma! It parsed!\n'),
  1304. 'ssi07': ('{%% ssi "%s" parsed %%}' % os.path.join(basedir, 'not_here'), {'test': 'Look ma! It parsed!'}, ''),
  1305. # Test space in file name
  1306. 'ssi08': ('{%% ssi "%s" %%}' % os.path.join(basedir, 'templates', 'ssi include with spaces.html'), {}, 'This is for testing an ssi include with spaces in its name. {{ test }}\n'),
  1307. 'ssi09': ('{%% ssi "%s" parsed %%}' % os.path.join(basedir, 'templates', 'ssi include with spaces.html'), {'test': 'Look ma! It parsed!'}, 'This is for testing an ssi include with spaces in its name. Look ma! It parsed!\n'),
  1308. ### TEMPLATETAG TAG #######################################################
  1309. 'templatetag01': ('{% templatetag openblock %}', {}, '{%'),
  1310. 'templatetag02': ('{% templatetag closeblock %}', {}, '%}'),
  1311. 'templatetag03': ('{% templatetag openvariable %}', {}, '{{'),
  1312. 'templatetag04': ('{% templatetag closevariable %}', {}, '}}'),
  1313. 'templatetag05': ('{% templatetag %}', {}, template.TemplateSyntaxError),
  1314. 'templatetag06': ('{% templatetag foo %}', {}, template.TemplateSyntaxError),
  1315. 'templatetag07': ('{% templatetag openbrace %}', {}, '{'),
  1316. 'templatetag08': ('{% templatetag closebrace %}', {}, '}'),
  1317. 'templatetag09': ('{% templatetag openbrace %}{% templatetag openbrace %}', {}, '{{'),
  1318. 'templatetag10': ('{% templatetag closebrace %}{% templatetag closebrace %}', {}, '}}'),
  1319. 'templatetag11': ('{% templatetag opencomment %}', {}, '{#'),
  1320. 'templatetag12': ('{% templatetag closecomment %}', {}, '#}'),
  1321. # Simple tags with customized names
  1322. 'simpletag-renamed01': ('{% load custom %}{% minusone 7 %}', {}, '6'),
  1323. 'simpletag-renamed02': ('{% load custom %}{% minustwo 7 %}', {}, '5'),
  1324. 'simpletag-renamed03': ('{% load custom %}{% minustwo_overridden_name 7 %}', {}, template.TemplateSyntaxError),
  1325. ### WIDTHRATIO TAG ########################################################
  1326. 'widthratio01': ('{% widthratio a b 0 %}', {'a': 50, 'b': 100}, '0'),
  1327. 'widthratio02': ('{% widthratio a b 100 %}', {'a': 0, 'b': 0}, '0'),
  1328. 'widthratio03': ('{% widthratio a b 100 %}', {'a': 0, 'b': 100}, '0'),
  1329. 'widthratio04': ('{% widthratio a b 100 %}', {'a': 50, 'b': 100}, '50'),
  1330. 'widthratio05': ('{% widthratio a b 100 %}', {'a': 100, 'b': 100}, '100'),
  1331. # 62.5 should round to 63 on Python 2 and 62 on Python 3
  1332. # See http://docs.python.org/py3k/whatsnew/3.0.html
  1333. 'widthratio06': ('{% widthratio a b 100 %}', {'a': 50, 'b': 80}, '62' if six.PY3 else '63'),
  1334. # 71.4 should round to 71
  1335. 'widthratio07': ('{% widthratio a b 100 %}', {'a': 50, 'b': 70}, '71'),
  1336. # Raise exception if we don't have 3 args, last one an integer
  1337. 'widthratio08': ('{% widthratio %}', {}, template.TemplateSyntaxError),
  1338. 'widthratio09': ('{% widthratio a b %}', {'a': 50, 'b': 100}, template.TemplateSyntaxError),
  1339. 'widthratio10': ('{% widthratio a b 100.0 %}', {'a': 50, 'b': 100}, '50'),
  1340. # #10043: widthratio should allow max_width to be a variable
  1341. 'widthratio11': ('{% widthratio a b c %}', {'a': 50, 'b': 100, 'c': 100}, '50'),
  1342. # #18739: widthratio should handle None args consistently with non-numerics
  1343. 'widthratio12a': ('{% widthratio a b c %}', {'a': 'a', 'b': 100, 'c': 100}, ''),
  1344. 'widthratio12b': ('{% widthratio a b c %}', {'a': None, 'b': 100, 'c': 100}, ''),
  1345. 'widthratio13a': ('{% widthratio a b c %}', {'a': 0, 'b': 'b', 'c': 100}, ''),
  1346. 'widthratio13b': ('{% widthratio a b c %}', {'a': 0, 'b': None, 'c': 100}, ''),
  1347. 'widthratio14a': ('{% widthratio a b c %}', {'a': 0, 'b': 100, 'c': 'c'}, template.TemplateSyntaxError),
  1348. 'widthratio14b': ('{% widthratio a b c %}', {'a': 0, 'b': 100, 'c': None}, template.TemplateSyntaxError),
  1349. # Test whitespace in filter argument
  1350. 'widthratio15': ('{% load custom %}{% widthratio a|noop:"x y" b 0 %}', {'a': 50, 'b': 100}, '0'),
  1351. # Widthratio with variable assignment
  1352. 'widthratio16': ('{% widthratio a b 100 as variable %}-{{ variable }}-', {'a': 50, 'b': 100}, '-50-'),
  1353. 'widthratio17': ('{% widthratio a b 100 as variable %}-{{ variable }}-', {'a': 100, 'b': 100}, '-100-'),
  1354. 'widthratio18': ('{% widthratio a b 100 as %}', {}, template.TemplateSyntaxError),
  1355. 'widthratio19': ('{% widthratio a b 100 not_as variable %}', {}, template.TemplateSyntaxError),
  1356. ### WITH TAG ########################################################
  1357. 'with01': ('{% with key=dict.key %}{{ key }}{% endwith %}', {'dict': {'key': 50}}, '50'),
  1358. 'legacywith01': ('{% with dict.key as key %}{{ key }}{% endwith %}', {'dict': {'key': 50}}, '50'),
  1359. 'with02': ('{{ key }}{% with key=dict.key %}{{ key }}-{{ dict.key }}-{{ key }}{% endwith %}{{ key }}', {'dict': {'key': 50}}, ('50-50-50', 'INVALID50-50-50INVALID')),
  1360. 'legacywith02': ('{{ key }}{% with dict.key as key %}{{ key }}-{{ dict.key }}-{{ key }}{% endwith %}{{ key }}', {'dict': {'key': 50}}, ('50-50-50', 'INVALID50-50-50INVALID')),
  1361. 'with03': ('{% with a=alpha b=beta %}{{ a }}{{ b }}{% endwith %}', {'alpha': 'A', 'beta': 'B'}, 'AB'),
  1362. 'with-error01': ('{% with dict.key xx key %}{{ key }}{% endwith %}', {'dict': {'key': 50}}, template.TemplateSyntaxError),
  1363. 'with-error02': ('{% with dict.key as %}{{ key }}{% endwith %}', {'dict': {'key': 50}}, template.TemplateSyntaxError),
  1364. ### NOW TAG ########################################################
  1365. # Simple case
  1366. 'now01': ('{% now "j n Y" %}', {}, "%d %d %d" % (
  1367. datetime.now().day, datetime.now().month, datetime.now().year)),
  1368. # Check parsing of locale strings
  1369. 'now02': ('{% now "DATE_FORMAT" %}', {}, date_format(datetime.now())),
  1370. # Also accept simple quotes - #15092
  1371. 'now03': ("{% now 'j n Y' %}", {}, "%d %d %d" % (
  1372. datetime.now().day, datetime.now().month, datetime.now().year)),
  1373. 'now04': ("{% now 'DATE_FORMAT' %}", {}, date_format(datetime.now())),
  1374. 'now05': ('''{% now 'j "n" Y'%}''', {}, '''%d "%d" %d''' % (
  1375. datetime.now().day, datetime.now().month, datetime.now().year)),
  1376. 'now06': ('''{% now "j 'n' Y"%}''', {}, '''%d '%d' %d''' % (
  1377. datetime.now().day, datetime.now().month, datetime.now().year)),
  1378. ### URL TAG ########################################################
  1379. # Successes
  1380. 'url01': ('{% url "template_tests.views.client" client.id %}', {'client': {'id': 1}}, '/url_tag/client/1/'),
  1381. 'url02': ('{% url "template_tests.views.client_action" id=client.id action="update" %}', {'client': {'id': 1}}, '/url_tag/client/1/update/'),
  1382. 'url02a': ('{% url "template_tests.views.client_action" client.id "update" %}', {'client': {'id': 1}}, '/url_tag/client/1/update/'),
  1383. 'url02b': ("{% url 'template_tests.views.client_action' id=client.id action='update' %}", {'client': {'id': 1}}, '/url_tag/client/1/update/'),
  1384. 'url02c': ("{% url 'template_tests.views.client_action' client.id 'update' %}", {'client': {'id': 1}}, '/url_tag/client/1/update/'),
  1385. 'url03': ('{% url "template_tests.views.index" %}', {}, '/url_tag/'),
  1386. 'url04': ('{% url "named.client" client.id %}', {'client': {'id': 1}}, '/url_tag/named-client/1/'),
  1387. 'url05': ('{% url "метка_оператора" v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
  1388. 'url06': ('{% url "метка_оператора_2" tag=v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
  1389. 'url07': ('{% url "template_tests.views.client2" tag=v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
  1390. 'url08': ('{% url "метка_оператора" v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
  1391. 'url09': ('{% url "метка_оператора_2" tag=v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
  1392. 'url10': ('{% url "template_tests.views.client_action" id=client.id action="two words" %}', {'client': {'id': 1}}, '/url_tag/client/1/two%20words/'),
  1393. 'url11': ('{% url "template_tests.views.client_action" id=client.id action="==" %}', {'client': {'id': 1}}, '/url_tag/client/1/%3D%3D/'),
  1394. 'url12': ('{% url "template_tests.views.client_action" id=client.id action="," %}', {'client': {'id': 1}}, '/url_tag/client/1/%2C/'),
  1395. 'url13': ('{% url "template_tests.views.client_action" id=client.id action=arg|join:"-" %}', {'client': {'id': 1}, 'arg': ['a', 'b']}, '/url_tag/client/1/a-b/'),
  1396. 'url14': ('{% url "template_tests.views.client_action" client.id arg|join:"-" %}', {'client': {'id': 1}, 'arg': ['a', 'b']}, '/url_tag/client/1/a-b/'),
  1397. 'url15': ('{% url "template_tests.views.client_action" 12 "test" %}', {}, '/url_tag/client/12/test/'),
  1398. 'url18': ('{% url "template_tests.views.client" "1,2" %}', {}, '/url_tag/client/1%2C2/'),
  1399. 'url19': ('{% url named_url client.id %}', {'named_url': 'template_tests.views.client', 'client': {'id': 1}}, '/url_tag/client/1/'),
  1400. 'url20': ('{% url url_name_in_var client.id %}', {'url_name_in_var': 'named.client', 'client': {'id': 1}}, '/url_tag/named-client/1/'),
  1401. # Failures
  1402. 'url-fail01': ('{% url %}', {}, template.TemplateSyntaxError),
  1403. 'url-fail02': ('{% url "no_such_view" %}', {}, (urlresolvers.NoReverseMatch, urlresolvers.NoReverseMatch)),
  1404. 'url-fail03': ('{% url "template_tests.views.client" %}', {}, (urlresolvers.NoReverseMatch, urlresolvers.NoReverseMatch)),
  1405. 'url-fail04': ('{% url "view" id, %}', {}, template.TemplateSyntaxError),
  1406. 'url-fail05': ('{% url "view" id= %}', {}, template.TemplateSyntaxError),
  1407. 'url-fail06': ('{% url "view" a.id=id %}', {}, template.TemplateSyntaxError),
  1408. 'url-fail07': ('{% url "view" a.id!id %}', {}, template.TemplateSyntaxError),
  1409. 'url-fail08': ('{% url "view" id="unterminatedstring %}', {}, template.TemplateSyntaxError),
  1410. 'url-fail09': ('{% url "view" id=", %}', {}, template.TemplateSyntaxError),
  1411. 'url-fail11': ('{% url named_url %}', {}, (urlresolvers.NoReverseMatch, urlresolvers.NoReverseMatch)),
  1412. 'url-fail12': ('{% url named_url %}', {'named_url': 'no_such_view'}, (urlresolvers.NoReverseMatch, urlresolvers.NoReverseMatch)),
  1413. 'url-fail13': ('{% url named_url %}', {'named_url': 'template_tests.views.client'}, (urlresolvers.NoReverseMatch, urlresolvers.NoReverseMatch)),
  1414. 'url-fail14': ('{% url named_url id, %}', {'named_url': 'view'}, template.TemplateSyntaxError),
  1415. 'url-fail15': ('{% url named_url id= %}', {'named_url': 'view'}, template.TemplateSyntaxError),
  1416. 'url-fail16': ('{% url named_url a.id=id %}', {'named_url': 'view'}, template.TemplateSyntaxError),
  1417. 'url-fail17': ('{% url named_url a.id!id %}', {'named_url': 'view'}, template.TemplateSyntaxError),
  1418. 'url-fail18': ('{% url named_url id="unterminatedstring %}', {'named_url': 'view'}, template.TemplateSyntaxError),
  1419. 'url-fail19': ('{% url named_url id=", %}', {'named_url': 'view'}, template.TemplateSyntaxError),
  1420. # {% url ... as var %}
  1421. 'url-asvar01': ('{% url "template_tests.views.index" as url %}', {}, ''),
  1422. 'url-asvar02': ('{% url "template_tests.views.index" as url %}{{ url }}', {}, '/url_tag/'),
  1423. 'url-asvar03': ('{% url "no_such_view" as url %}{{ url }}', {}, ''),
  1424. ### CACHE TAG ######################################################
  1425. 'cache03': ('{% load cache %}{% cache 2 test %}cache03{% endcache %}', {}, 'cache03'),
  1426. 'cache04': ('{% load cache %}{% cache 2 test %}cache04{% endcache %}', {}, 'cache03'),
  1427. 'cache05': ('{% load cache %}{% cache 2 test foo %}cache05{% endcache %}', {'foo': 1}, 'cache05'),
  1428. 'cache06': ('{% load cache %}{% cache 2 test foo %}cache06{% endcache %}', {'foo': 2}, 'cache06'),
  1429. 'cache07': ('{% load cache %}{% cache 2 test foo %}cache07{% endcache %}', {'foo': 1}, 'cache05'),
  1430. # Allow first argument to be a variable.
  1431. 'cache08': ('{% load cache %}{% cache time test foo %}cache08{% endcache %}', {'foo': 2, 'time': 2}, 'cache06'),
  1432. # Raise exception if we don't have at least 2 args, first one integer.
  1433. 'cache11': ('{% load cache %}{% cache %}{% endcache %}', {}, template.TemplateSyntaxError),
  1434. 'cache12': ('{% load cache %}{% cache 1 %}{% endcache %}', {}, template.TemplateSyntaxError),
  1435. 'cache13': ('{% load cache %}{% cache foo bar %}{% endcache %}', {}, template.TemplateSyntaxError),
  1436. 'cache14': ('{% load cache %}{% cache foo bar %}{% endcache %}', {'foo': 'fail'}, template.TemplateSyntaxError),
  1437. 'cache15': ('{% load cache %}{% cache foo bar %}{% endcache %}', {'foo': []}, template.TemplateSyntaxError),
  1438. # Regression test for #7460.
  1439. 'cache16': ('{% load cache %}{% cache 1 foo bar %}{% endcache %}', {'foo': 'foo', 'bar': 'with spaces'}, ''),
  1440. # Regression test for #11270.
  1441. 'cache17': ('{% load cache %}{% cache 10 long_cache_key poem %}Some Content{% endcache %}', {'poem': 'Oh freddled gruntbuggly/Thy micturations are to me/As plurdled gabbleblotchits/On a lurgid bee/That mordiously hath bitled out/Its earted jurtles/Into a rancid festering/Or else I shall rend thee in the gobberwarts with my blurglecruncheon/See if I dont.'}, 'Some Content'),
  1442. # Test whitespace in filter arguments
  1443. 'cache18': ('{% load cache custom %}{% cache 2|noop:"x y" cache18 %}cache18{% endcache %}', {}, 'cache18'),
  1444. ### AUTOESCAPE TAG ##############################################
  1445. 'autoescape-tag01': ("{% autoescape off %}hello{% endautoescape %}", {}, "hello"),
  1446. 'autoescape-tag02': ("{% autoescape off %}{{ first }}{% endautoescape %}", {"first": "<b>hello</b>"}, "<b>hello</b>"),
  1447. 'autoescape-tag03': ("{% autoescape on %}{{ first }}{% endautoescape %}", {"first": "<b>hello</b>"}, "&lt;b&gt;hello&lt;/b&gt;"),
  1448. # Autoescape disabling and enabling nest in a predictable way.
  1449. 'autoescape-tag04': ("{% autoescape off %}{{ first }} {% autoescape on%}{{ first }}{% endautoescape %}{% endautoescape %}", {"first": "<a>"}, "<a> &lt;a&gt;"),
  1450. 'autoescape-tag05': ("{% autoescape on %}{{ first }}{% endautoescape %}", {"first": "<b>first</b>"}, "&lt;b&gt;first&lt;/b&gt;"),
  1451. # Strings (ASCII or unicode) already marked as "safe" are not
  1452. # auto-escaped
  1453. 'autoescape-tag06': ("{{ first }}", {"first": mark_safe("<b>first</b>")}, "<b>first</b>"),
  1454. 'autoescape-tag07': ("{% autoescape on %}{{ first }}{% endautoescape %}", {"first": mark_safe("<b>Apple</b>")}, "<b>Apple</b>"),
  1455. # Literal string arguments to filters, if used in the result, are
  1456. # safe.
  1457. 'autoescape-tag08': (r'{% autoescape on %}{{ var|default_if_none:" endquote\" hah" }}{% endautoescape %}', {"var": None}, ' endquote" hah'),
  1458. # Objects which return safe strings as their __unicode__ method
  1459. # won't get double-escaped.
  1460. 'autoescape-tag09': (r'{{ unsafe }}', {'unsafe': filters.UnsafeClass()}, 'you &amp; me'),
  1461. 'autoescape-tag10': (r'{{ safe }}', {'safe': filters.SafeClass()}, 'you &gt; me'),
  1462. # The "safe" and "escape" filters cannot work due to internal
  1463. # implementation details (fortunately, the (no)autoescape block
  1464. # tags can be used in those cases)
  1465. 'autoescape-filtertag01': ("{{ first }}{% filter safe %}{{ first }} x<y{% endfilter %}", {"first": "<a>"}, template.TemplateSyntaxError),
  1466. # ifqeual compares unescaped vales.
  1467. 'autoescape-ifequal01': ('{% ifequal var "this & that" %}yes{% endifequal %}', {"var": "this & that"}, "yes"),
  1468. # Arguments to filters are 'safe' and manipulate their input unescaped.
  1469. 'autoescape-filters01': ('{{ var|cut:"&" }}', {"var": "this & that"}, "this that"),
  1470. 'autoescape-filters02': ('{{ var|join:" & \" }}', {"var": ("Tom", "Dick", "Harry")}, "Tom & Dick & Harry"),
  1471. # Literal strings are safe.
  1472. 'autoescape-literals01': ('{{ "this & that" }}', {}, "this & that"),
  1473. # Iterating over strings outputs safe characters.
  1474. 'autoescape-stringiterations01': ('{% for l in var %}{{ l }},{% endfor %}', {'var': 'K&R'}, "K,&amp;,R,"),
  1475. # Escape requirement survives lookup.
  1476. 'autoescape-lookup01': ('{{ var.key }}', {"var": {"key": "this & that"}}, "this &amp; that"),
  1477. # Static template tags
  1478. 'static-prefixtag01': ('{% load static %}{% get_static_prefix %}', {}, settings.STATIC_URL),
  1479. 'static-prefixtag02': ('{% load static %}{% get_static_prefix as static_prefix %}{{ static_prefix }}', {}, settings.STATIC_URL),
  1480. 'static-prefixtag03': ('{% load static %}{% get_media_prefix %}', {}, settings.MEDIA_URL),
  1481. 'static-prefixtag04': ('{% load static %}{% get_media_prefix as media_prefix %}{{ media_prefix }}', {}, settings.MEDIA_URL),
  1482. 'static-statictag01': ('{% load static %}{% static "admin/base.css" %}', {}, urljoin(settings.STATIC_URL, 'admin/base.css')),
  1483. 'static-statictag02': ('{% load static %}{% static base_css %}', {'base_css': 'admin/base.css'}, urljoin(settings.STATIC_URL, 'admin/base.css')),
  1484. 'static-statictag03': ('{% load static %}{% static "admin/base.css" as foo %}{{ foo }}', {}, urljoin(settings.STATIC_URL, 'admin/base.css')),
  1485. 'static-statictag04': ('{% load static %}{% static base_css as foo %}{{ foo }}', {'base_css': 'admin/base.css'}, urljoin(settings.STATIC_URL, 'admin/base.css')),
  1486. # Verbatim template tag outputs contents without rendering.
  1487. 'verbatim-tag01': ('{% verbatim %}{{bare }}{% endverbatim %}', {}, '{{bare }}'),
  1488. 'verbatim-tag02': ('{% verbatim %}{% endif %}{% endverbatim %}', {}, '{% endif %}'),
  1489. 'verbatim-tag03': ("{% verbatim %}It's the {% verbatim %} tag{% endverbatim %}", {}, "It's the {% verbatim %} tag"),
  1490. 'verbatim-tag04': ('{% verbatim %}{% verbatim %}{% endverbatim %}{% endverbatim %}', {}, template.TemplateSyntaxError),
  1491. 'verbatim-tag05': ('{% verbatim %}{% endverbatim %}{% verbatim %}{% endverbatim %}', {}, ''),
  1492. 'verbatim-tag06': ("{% verbatim special %}Don't {% endverbatim %} just yet{% endverbatim special %}", {}, "Don't {% endverbatim %} just yet"),
  1493. }
  1494. if numpy:
  1495. tests.update({
  1496. # Numpy's array-index syntax allows a template to access a certain item of a subscriptable object.
  1497. 'numpy-array-index01': ("{{ var.1 }}", {"var": numpy.array(["first item", "second item"])}, "second item"),
  1498. # Fail silently when the array index is out of range.
  1499. 'numpy-array-index02': ("{{ var.5 }}", {"var": numpy.array(["first item", "second item"])}, ("", "INVALID")),
  1500. })
  1501. return tests
  1502. class TemplateTagLoading(TestCase):
  1503. def setUp(self):
  1504. self.old_path = sys.path[:]
  1505. self.egg_dir = '%s/eggs' % os.path.dirname(upath(__file__))
  1506. self.old_tag_modules = template_base.templatetags_modules
  1507. template_base.templatetags_modules = []
  1508. def tearDown(self):
  1509. sys.path = self.old_path
  1510. template_base.templatetags_modules = self.old_tag_modules
  1511. def test_load_error(self):
  1512. ttext = "{% load broken_tag %}"
  1513. self.assertRaises(template.TemplateSyntaxError, template.Template, ttext)
  1514. try:
  1515. template.Template(ttext)
  1516. except template.TemplateSyntaxError as e:
  1517. self.assertTrue('ImportError' in e.args[0])
  1518. self.assertTrue('Xtemplate' in e.args[0])
  1519. @override_settings(INSTALLED_APPS=('tagsegg',))
  1520. def test_load_error_egg(self):
  1521. ttext = "{% load broken_egg %}"
  1522. egg_name = '%s/tagsegg.egg' % self.egg_dir
  1523. sys.path.append(egg_name)
  1524. self.assertRaises(template.TemplateSyntaxError, template.Template, ttext)
  1525. try:
  1526. template.Template(ttext)
  1527. except template.TemplateSyntaxError as e:
  1528. self.assertTrue('ImportError' in e.args[0])
  1529. self.assertTrue('Xtemplate' in e.args[0])
  1530. @override_settings(INSTALLED_APPS=('tagsegg',))
  1531. def test_load_working_egg(self):
  1532. ttext = "{% load working_egg %}"
  1533. egg_name = '%s/tagsegg.egg' % self.egg_dir
  1534. sys.path.append(egg_name)
  1535. template.Template(ttext)
  1536. class RequestContextTests(unittest.TestCase):
  1537. def setUp(self):
  1538. templates = {
  1539. 'child': Template('{{ var|default:"none" }}'),
  1540. }
  1541. setup_test_template_loader(templates)
  1542. self.fake_request = RequestFactory().get('/')
  1543. def tearDown(self):
  1544. restore_template_loaders()
  1545. def test_include_only(self):
  1546. """
  1547. Regression test for #15721, ``{% include %}`` and ``RequestContext``
  1548. not playing together nicely.
  1549. """
  1550. ctx = RequestContext(self.fake_request, {'var': 'parent'})
  1551. self.assertEqual(
  1552. template.Template('{% include "child" %}').render(ctx),
  1553. 'parent'
  1554. )
  1555. self.assertEqual(
  1556. template.Template('{% include "child" only %}').render(ctx),
  1557. 'none'
  1558. )
  1559. def test_stack_size(self):
  1560. """
  1561. Regression test for #7116, Optimize RequetsContext construction
  1562. """
  1563. ctx = RequestContext(self.fake_request, {})
  1564. # The stack should now contain 3 items:
  1565. # [builtins, supplied context, context processor]
  1566. self.assertEqual(len(ctx.dicts), 3)
  1567. class SSITests(TestCase):
  1568. def setUp(self):
  1569. self.this_dir = os.path.dirname(os.path.abspath(upath(__file__)))
  1570. self.ssi_dir = os.path.join(self.this_dir, "templates", "first")
  1571. def render_ssi(self, path):
  1572. # the path must exist for the test to be reliable
  1573. self.assertTrue(os.path.exists(path))
  1574. return template.Template('{%% ssi "%s" %%}' % path).render(Context())
  1575. def test_allowed_paths(self):
  1576. acceptable_path = os.path.join(self.ssi_dir, "..", "first", "test.html")
  1577. with override_settings(ALLOWED_INCLUDE_ROOTS=(self.ssi_dir,)):
  1578. self.assertEqual(self.render_ssi(acceptable_path), 'First template\n')
  1579. def test_relative_include_exploit(self):
  1580. """
  1581. May not bypass ALLOWED_INCLUDE_ROOTS with relative paths
  1582. e.g. if ALLOWED_INCLUDE_ROOTS = ("/var/www",), it should not be
  1583. possible to do {% ssi "/var/www/../../etc/passwd" %}
  1584. """
  1585. disallowed_paths = [
  1586. os.path.join(self.ssi_dir, "..", "ssi_include.html"),
  1587. os.path.join(self.ssi_dir, "..", "second", "test.html"),
  1588. ]
  1589. with override_settings(ALLOWED_INCLUDE_ROOTS=(self.ssi_dir,)):
  1590. for path in disallowed_paths:
  1591. self.assertEqual(self.render_ssi(path), '')