tests.py 108 KB

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