tests.py 110 KB

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