tests.py 121 KB

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