tests.py 87 KB

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