tests.py 121 KB

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