PageRenderTime 38ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/regressiontests/templates/tests.py

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