tests.py 116 KB

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