tests.py 99 KB

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