tests.py 69 KB

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