1 # -*- coding: utf-8 -*-
2 from django
.conf
import settings
4 if __name__
== '__main__':
5 # When running this file in isolation, we need to set up the configuration
6 # before importing 'template'.
11 from datetime
import datetime
, timedelta
13 from django
import template
14 from django
.template
import loader
15 from django
.template
.loaders
import app_directories
, filesystem
16 from django
.utils
.translation
import activate
, deactivate
, install
, ugettext
as _
17 from django
.utils
.tzinfo
import LocalTimezone
19 from unicode import unicode_tests
21 # Some other tests we would like to run
23 'unicode': unicode_tests
,
26 #################################
27 # Custom template tag for tests #
28 #################################
30 register
= template
.Library()
32 class EchoNode(template
.Node
):
33 def __init__(self
, contents
):
34 self
.contents
= contents
36 def render(self
, context
):
37 return " ".join(self
.contents
)
39 def do_echo(parser
, token
):
40 return EchoNode(token
.contents
.split()[1:])
42 register
.tag("echo", do_echo
)
44 template
.libraries
['django.templatetags.testtags'] = register
46 #####################################
47 # Helper objects for template tests #
48 #####################################
50 class SomeException(Exception):
51 silent_variable_failure
= True
53 class SomeOtherException(Exception):
58 self
.otherclass
= OtherClass()
61 return "SomeClass.method"
70 raise SomeOtherException
74 return "OtherClass.method"
77 "Class whose __str__ returns non-ASCII data"
79 return u
'ŠĐĆŽćžšđ'.encode('utf-8')
81 class Templates(unittest
.TestCase
):
82 def test_loaders_security(self
):
83 def test_template_sources(path
, template_dirs
, expected_sources
):
84 # Fix expected sources so they are normcased and abspathed
85 expected_sources
= [os
.path
.normcase(os
.path
.abspath(s
)) for s
in expected_sources
]
86 # Test app_directories loader
87 sources
= app_directories
.get_template_sources(path
, template_dirs
)
88 self
.assertEqual(list(sources
), expected_sources
)
89 # Test filesystem loader
90 sources
= filesystem
.get_template_sources(path
, template_dirs
)
91 self
.assertEqual(list(sources
), expected_sources
)
93 template_dirs
= ['/dir1', '/dir2']
94 test_template_sources('index.html', template_dirs
,
95 ['/dir1/index.html', '/dir2/index.html'])
96 test_template_sources('/etc/passwd', template_dirs
,
98 test_template_sources('etc/passwd', template_dirs
,
99 ['/dir1/etc/passwd', '/dir2/etc/passwd'])
100 test_template_sources('../etc/passwd', template_dirs
,
102 test_template_sources('../../../etc/passwd', template_dirs
,
104 test_template_sources('/dir1/index.html', template_dirs
,
105 ['/dir1/index.html'])
106 test_template_sources('../dir2/index.html', template_dirs
,
107 ['/dir2/index.html'])
108 test_template_sources('/dir1blah', template_dirs
,
110 test_template_sources('../dir1blah', template_dirs
,
113 # Case insensitive tests (for win32). Not run unless we're on
114 # a case insensitive operating system.
115 if os
.path
.normcase('/TEST') == os
.path
.normpath('/test'):
116 template_dirs
= ['/dir1', '/DIR2']
117 test_template_sources('index.html', template_dirs
,
118 ['/dir1/index.html', '/dir2/index.html'])
119 test_template_sources('/DIR1/index.HTML', template_dirs
,
120 ['/dir1/index.html'])
122 def test_templates(self
):
123 # NOW and NOW_tz are used by timesince tag tests.
125 NOW_tz
= datetime
.now(LocalTimezone(datetime
.now()))
128 # 'template_name': ('template contents', 'context dict', 'expected string output' or Exception class)
131 ### BASIC SYNTAX ##########################################################
133 # Plain text should go through the template parser untouched
134 'basic-syntax01': ("something cool", {}, "something cool"),
136 # Variables should be replaced with their value in the current context
137 'basic-syntax02': ("{{ headline }}", {'headline':'Success'}, "Success"),
139 # More than one replacement variable is allowed in a template
140 'basic-syntax03': ("{{ first }} --- {{ second }}", {"first" : 1, "second" : 2}, "1 --- 2"),
142 # Fail silently when a variable is not found in the current context
143 'basic-syntax04': ("as{{ missing }}df", {}, ("asdf","asINVALIDdf")),
145 # A variable may not contain more than one word
146 'basic-syntax06': ("{{ multi word variable }}", {}, template
.TemplateSyntaxError
),
148 # Raise TemplateSyntaxError for empty variable tags
149 'basic-syntax07': ("{{ }}", {}, template
.TemplateSyntaxError
),
150 'basic-syntax08': ("{{ }}", {}, template
.TemplateSyntaxError
),
152 # Attribute syntax allows a template to call an object's attribute
153 'basic-syntax09': ("{{ var.method }}", {"var": SomeClass()}, "SomeClass.method"),
155 # Multiple levels of attribute access are allowed
156 'basic-syntax10': ("{{ var.otherclass.method }}", {"var": SomeClass()}, "OtherClass.method"),
158 # Fail silently when a variable's attribute isn't found
159 'basic-syntax11': ("{{ var.blech }}", {"var": SomeClass()}, ("","INVALID")),
161 # Raise TemplateSyntaxError when trying to access a variable beginning with an underscore
162 'basic-syntax12': ("{{ var.__dict__ }}", {"var": SomeClass()}, template
.TemplateSyntaxError
),
164 # Raise TemplateSyntaxError when trying to access a variable containing an illegal character
165 'basic-syntax13': ("{{ va>r }}", {}, template
.TemplateSyntaxError
),
166 'basic-syntax14': ("{{ (var.r) }}", {}, template
.TemplateSyntaxError
),
167 'basic-syntax15': ("{{ sp%am }}", {}, template
.TemplateSyntaxError
),
168 'basic-syntax16': ("{{ eggs! }}", {}, template
.TemplateSyntaxError
),
169 'basic-syntax17': ("{{ moo? }}", {}, template
.TemplateSyntaxError
),
171 # Attribute syntax allows a template to call a dictionary key's value
172 'basic-syntax18': ("{{ foo.bar }}", {"foo" : {"bar" : "baz"}}, "baz"),
174 # Fail silently when a variable's dictionary key isn't found
175 'basic-syntax19': ("{{ foo.spam }}", {"foo" : {"bar" : "baz"}}, ("","INVALID")),
177 # Fail silently when accessing a non-simple method
178 'basic-syntax20': ("{{ var.method2 }}", {"var": SomeClass()}, ("","INVALID")),
180 # Don't get confused when parsing something that is almost, but not
181 # quite, a template tag.
182 'basic-syntax21': ("a {{ moo %} b", {}, "a {{ moo %} b"),
183 'basic-syntax22': ("{{ moo #}", {}, "{{ moo #}"),
185 # Will try to treat "moo #} {{ cow" as the variable. Not ideal, but
186 # costly to work around, so this triggers an error.
187 'basic-syntax23': ("{{ moo #} {{ cow }}", {"cow": "cow"}, template
.TemplateSyntaxError
),
189 # Embedded newlines make it not-a-tag.
190 'basic-syntax24': ("{{ moo\n }}", {}, "{{ moo\n }}"),
192 # List-index syntax allows a template to access a certain item of a subscriptable object.
193 'list-index01': ("{{ var.1 }}", {"var": ["first item", "second item"]}, "second item"),
195 # Fail silently when the list index is out of range.
196 'list-index02': ("{{ var.5 }}", {"var": ["first item", "second item"]}, ("", "INVALID")),
198 # Fail silently when the variable is not a subscriptable object.
199 'list-index03': ("{{ var.1 }}", {"var": None}, ("", "INVALID")),
201 # Fail silently when variable is a dict without the specified key.
202 'list-index04': ("{{ var.1 }}", {"var": {}}, ("", "INVALID")),
204 # Dictionary lookup wins out when dict's key is a string.
205 'list-index05': ("{{ var.1 }}", {"var": {'1': "hello"}}, "hello"),
207 # But list-index lookup wins out when dict's key is an int, which
208 # behind the scenes is really a dictionary lookup (for a dict)
209 # after converting the key to an int.
210 'list-index06': ("{{ var.1 }}", {"var": {1: "hello"}}, "hello"),
212 # Dictionary lookup wins out when there is a string and int version of the key.
213 'list-index07': ("{{ var.1 }}", {"var": {'1': "hello", 1: "world"}}, "hello"),
216 'filter-syntax01': ("{{ var|upper }}", {"var": "Django is the greatest!"}, "DJANGO IS THE GREATEST!"),
219 'filter-syntax02': ("{{ var|upper|lower }}", {"var": "Django is the greatest!"}, "django is the greatest!"),
221 # Raise TemplateSyntaxError for space between a variable and filter pipe
222 'filter-syntax03': ("{{ var |upper }}", {}, template
.TemplateSyntaxError
),
224 # Raise TemplateSyntaxError for space after a filter pipe
225 'filter-syntax04': ("{{ var| upper }}", {}, template
.TemplateSyntaxError
),
227 # Raise TemplateSyntaxError for a nonexistent filter
228 'filter-syntax05': ("{{ var|does_not_exist }}", {}, template
.TemplateSyntaxError
),
230 # Raise TemplateSyntaxError when trying to access a filter containing an illegal character
231 'filter-syntax06': ("{{ var|fil(ter) }}", {}, template
.TemplateSyntaxError
),
233 # Raise TemplateSyntaxError for invalid block tags
234 'filter-syntax07': ("{% nothing_to_see_here %}", {}, template
.TemplateSyntaxError
),
236 # Raise TemplateSyntaxError for empty block tags
237 'filter-syntax08': ("{% %}", {}, template
.TemplateSyntaxError
),
239 # Chained filters, with an argument to the first one
240 'filter-syntax09': ('{{ var|removetags:"b i"|upper|lower }}', {"var": "<b><i>Yes</i></b>"}, "yes"),
242 # Escaped string as argument
243 'filter-syntax10': (r
'{{ var|default_if_none:" endquote\" hah" }}', {"var": None}, ' endquote" hah'),
245 # Variable as argument
246 'filter-syntax11': (r
'{{ var|default_if_none:var2 }}', {"var": None, "var2": "happy"}, 'happy'),
248 # Default argument testing
249 'filter-syntax12': (r
'{{ var|yesno:"yup,nup,mup" }} {{ var|yesno }}', {"var": True}, 'yup yes'),
251 # Fail silently for methods that raise an exception with a
252 # "silent_variable_failure" attribute
253 'filter-syntax13': (r
'1{{ var.method3 }}2', {"var": SomeClass()}, ("12", "1INVALID2")),
255 # In methods that raise an exception without a
256 # "silent_variable_attribute" set to True, the exception propagates
257 'filter-syntax14': (r
'1{{ var.method4 }}2', {"var": SomeClass()}, SomeOtherException
),
259 # Escaped backslash in argument
260 'filter-syntax15': (r
'{{ var|default_if_none:"foo\bar" }}', {"var": None}, r
'foo\bar'),
262 # Escaped backslash using known escape char
263 'filter-syntax16': (r
'{{ var|default_if_none:"foo\now" }}', {"var": None}, r
'foo\now'),
265 # Empty strings can be passed as arguments to filters
266 'filter-syntax17': (r
'{{ var|join:"" }}', {'var': ['a', 'b', 'c']}, 'abc'),
268 # Make sure that any unicode strings are converted to bytestrings
269 # in the final output.
270 'filter-syntax18': (r
'{{ var }}', {'var': UTF8Class()}, u
'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111'),
272 # Numbers as filter arguments should work
273 'filter-syntax19': ('{{ var|truncatewords:1 }}', {"var": "hello world"}, "hello ..."),
275 ### COMMENT SYNTAX ########################################################
276 'comment-syntax01': ("{# this is hidden #}hello", {}, "hello"),
277 'comment-syntax02': ("{# this is hidden #}hello{# foo #}", {}, "hello"),
279 # Comments can contain invalid stuff.
280 'comment-syntax03': ("foo{# {% if %} #}", {}, "foo"),
281 'comment-syntax04': ("foo{# {% endblock %} #}", {}, "foo"),
282 'comment-syntax05': ("foo{# {% somerandomtag %} #}", {}, "foo"),
283 'comment-syntax06': ("foo{# {% #}", {}, "foo"),
284 'comment-syntax07': ("foo{# %} #}", {}, "foo"),
285 'comment-syntax08': ("foo{# %} #}bar", {}, "foobar"),
286 'comment-syntax09': ("foo{# {{ #}", {}, "foo"),
287 'comment-syntax10': ("foo{# }} #}", {}, "foo"),
288 'comment-syntax11': ("foo{# { #}", {}, "foo"),
289 'comment-syntax12': ("foo{# } #}", {}, "foo"),
291 ### COMMENT TAG ###########################################################
292 'comment-tag01': ("{% comment %}this is hidden{% endcomment %}hello", {}, "hello"),
293 'comment-tag02': ("{% comment %}this is hidden{% endcomment %}hello{% comment %}foo{% endcomment %}", {}, "hello"),
295 # Comment tag can contain invalid stuff.
296 'comment-tag03': ("foo{% comment %} {% if %} {% endcomment %}", {}, "foo"),
297 'comment-tag04': ("foo{% comment %} {% endblock %} {% endcomment %}", {}, "foo"),
298 'comment-tag05': ("foo{% comment %} {% somerandomtag %} {% endcomment %}", {}, "foo"),
300 ### CYCLE TAG #############################################################
301 'cycle01': ('{% cycle a %}', {}, template
.TemplateSyntaxError
),
302 'cycle02': ('{% cycle a,b,c as abc %}{% cycle abc %}', {}, 'ab'),
303 'cycle03': ('{% cycle a,b,c as abc %}{% cycle abc %}{% cycle abc %}', {}, 'abc'),
304 'cycle04': ('{% cycle a,b,c as abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}', {}, 'abca'),
305 'cycle05': ('{% cycle %}', {}, template
.TemplateSyntaxError
),
306 'cycle06': ('{% cycle a %}', {}, template
.TemplateSyntaxError
),
307 'cycle07': ('{% cycle a,b,c as foo %}{% cycle bar %}', {}, template
.TemplateSyntaxError
),
308 'cycle08': ('{% cycle a,b,c as foo %}{% cycle foo %}{{ foo }}{{ foo }}{% cycle foo %}{{ foo }}', {}, 'abbbcc'),
309 'cycle09': ("{% for i in test %}{% cycle a,b %}{{ i }},{% endfor %}", {'test': range(5)}, 'a0,b1,a2,b3,a4,'),
311 'cycle10': ("{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}", {}, 'ab'),
312 'cycle11': ("{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}", {}, 'abc'),
313 'cycle12': ("{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}", {}, 'abca'),
314 'cycle13': ("{% for i in test %}{% cycle 'a' 'b' %}{{ i }},{% endfor %}", {'test': range(5)}, 'a0,b1,a2,b3,a4,'),
315 'cycle14': ("{% cycle one two as foo %}{% cycle foo %}", {'one': '1','two': '2'}, '12'),
316 'cycle13': ("{% for i in test %}{% cycle aye bee %}{{ i }},{% endfor %}", {'test': range(5), 'aye': 'a', 'bee': 'b'}, 'a0,b1,a2,b3,a4,'),
318 ### EXCEPTIONS ############################################################
320 # Raise exception for invalid template name
321 'exception01': ("{% extends 'nonexistent' %}", {}, template
.TemplateSyntaxError
),
323 # Raise exception for invalid template name (in variable)
324 'exception02': ("{% extends nonexistent %}", {}, template
.TemplateSyntaxError
),
326 # Raise exception for extra {% extends %} tags
327 'exception03': ("{% extends 'inheritance01' %}{% block first %}2{% endblock %}{% extends 'inheritance16' %}", {}, template
.TemplateSyntaxError
),
329 # Raise exception for custom tags used in child with {% load %} tag in parent, not in child
330 'exception04': ("{% extends 'inheritance17' %}{% block first %}{% echo 400 %}5678{% endblock %}", {}, template
.TemplateSyntaxError
),
332 ### FILTER TAG ############################################################
333 'filter01': ('{% filter upper %}{% endfilter %}', {}, ''),
334 'filter02': ('{% filter upper %}django{% endfilter %}', {}, 'DJANGO'),
335 'filter03': ('{% filter upper|lower %}django{% endfilter %}', {}, 'django'),
336 'filter04': ('{% filter cut:remove %}djangospam{% endfilter %}', {'remove': 'spam'}, 'django'),
338 ### FIRSTOF TAG ###########################################################
339 'firstof01': ('{% firstof a b c %}', {'a':0,'b':0,'c':0}, ''),
340 'firstof02': ('{% firstof a b c %}', {'a':1,'b':0,'c':0}, '1'),
341 'firstof03': ('{% firstof a b c %}', {'a':0,'b':2,'c':0}, '2'),
342 'firstof04': ('{% firstof a b c %}', {'a':0,'b':0,'c':3}, '3'),
343 'firstof05': ('{% firstof a b c %}', {'a':1,'b':2,'c':3}, '1'),
344 'firstof06': ('{% firstof a b c %}', {'b':0,'c':3}, '3'),
345 'firstof07': ('{% firstof a b "c" %}', {'a':0}, 'c'),
346 'firstof08': ('{% firstof a b "c and d" %}', {'a':0,'b':0}, 'c and d'),
347 'firstof09': ('{% firstof %}', {}, template
.TemplateSyntaxError
),
349 ### FOR TAG ###############################################################
350 'for-tag01': ("{% for val in values %}{{ val }}{% endfor %}", {"values": [1, 2, 3]}, "123"),
351 'for-tag02': ("{% for val in values reversed %}{{ val }}{% endfor %}", {"values": [1, 2, 3]}, "321"),
352 'for-tag-vars01': ("{% for val in values %}{{ forloop.counter }}{% endfor %}", {"values": [6, 6, 6]}, "123"),
353 'for-tag-vars02': ("{% for val in values %}{{ forloop.counter0 }}{% endfor %}", {"values": [6, 6, 6]}, "012"),
354 'for-tag-vars03': ("{% for val in values %}{{ forloop.revcounter }}{% endfor %}", {"values": [6, 6, 6]}, "321"),
355 'for-tag-vars04': ("{% for val in values %}{{ forloop.revcounter0 }}{% endfor %}", {"values": [6, 6, 6]}, "210"),
356 'for-tag-unpack01': ("{% for key,value in items %}{{ key }}:{{ value }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, "one:1/two:2/"),
357 'for-tag-unpack03': ("{% for key, value in items %}{{ key }}:{{ value }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, "one:1/two:2/"),
358 'for-tag-unpack04': ("{% for key , value in items %}{{ key }}:{{ value }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, "one:1/two:2/"),
359 'for-tag-unpack05': ("{% for key ,value in items %}{{ key }}:{{ value }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, "one:1/two:2/"),
360 'for-tag-unpack06': ("{% for key value in items %}{{ key }}:{{ value }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, template
.TemplateSyntaxError
),
361 'for-tag-unpack07': ("{% for key,,value in items %}{{ key }}:{{ value }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, template
.TemplateSyntaxError
),
362 'for-tag-unpack08': ("{% for key,value, in items %}{{ key }}:{{ value }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, template
.TemplateSyntaxError
),
363 # Ensure that a single loopvar doesn't truncate the list in val.
364 'for-tag-unpack09': ("{% for val in items %}{{ val.0 }}:{{ val.1 }}/{% endfor %}", {"items": (('one', 1), ('two', 2))}, "one:1/two:2/"),
365 # Otherwise, silently truncate if the length of loopvars differs to the length of each set of items.
366 'for-tag-unpack10': ("{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}", {"items": (('one', 1, 'carrot'), ('two', 2, 'orange'))}, "one:1/two:2/"),
367 '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/")),
368 '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/")),
369 '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/")),
371 ### IF TAG ################################################################
372 'if-tag01': ("{% if foo %}yes{% else %}no{% endif %}", {"foo": True}, "yes"),
373 'if-tag02': ("{% if foo %}yes{% else %}no{% endif %}", {"foo": False}, "no"),
374 'if-tag03': ("{% if foo %}yes{% else %}no{% endif %}", {}, "no"),
377 'if-tag-and01': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
378 'if-tag-and02': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'no'),
379 'if-tag-and03': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'no'),
380 'if-tag-and04': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'no'),
381 'if-tag-and05': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': False}, 'no'),
382 'if-tag-and06': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'bar': False}, 'no'),
383 'if-tag-and07': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': True}, 'no'),
384 'if-tag-and08': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'bar': True}, 'no'),
387 'if-tag-or01': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
388 'if-tag-or02': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'yes'),
389 'if-tag-or03': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'yes'),
390 'if-tag-or04': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'no'),
391 'if-tag-or05': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': False}, 'no'),
392 'if-tag-or06': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'bar': False}, 'no'),
393 'if-tag-or07': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': True}, 'yes'),
394 'if-tag-or08': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'bar': True}, 'yes'),
399 'if-tag-not01': ("{% if not foo %}no{% else %}yes{% endif %}", {'foo': True}, 'yes'),
400 'if-tag-not02': ("{% if not %}yes{% else %}no{% endif %}", {'foo': True}, 'no'),
401 'if-tag-not03': ("{% if not %}yes{% else %}no{% endif %}", {'not': True}, 'yes'),
402 'if-tag-not04': ("{% if not not %}no{% else %}yes{% endif %}", {'not': True}, 'yes'),
403 'if-tag-not05': ("{% if not not %}no{% else %}yes{% endif %}", {}, 'no'),
405 'if-tag-not06': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {}, 'no'),
406 'if-tag-not07': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'no'),
407 'if-tag-not08': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'yes'),
408 'if-tag-not09': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'no'),
409 'if-tag-not10': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'no'),
411 'if-tag-not11': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {}, 'no'),
412 'if-tag-not12': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'no'),
413 'if-tag-not13': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'no'),
414 'if-tag-not14': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'yes'),
415 'if-tag-not15': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'no'),
417 'if-tag-not16': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {}, 'yes'),
418 'if-tag-not17': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
419 'if-tag-not18': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'yes'),
420 'if-tag-not19': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'no'),
421 'if-tag-not20': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'yes'),
423 'if-tag-not21': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {}, 'yes'),
424 'if-tag-not22': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
425 'if-tag-not23': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'no'),
426 'if-tag-not24': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'yes'),
427 'if-tag-not25': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'yes'),
429 'if-tag-not26': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {}, 'yes'),
430 'if-tag-not27': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'no'),
431 'if-tag-not28': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'no'),
432 'if-tag-not29': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'no'),
433 'if-tag-not30': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'yes'),
435 'if-tag-not31': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {}, 'yes'),
436 'if-tag-not32': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'no'),
437 'if-tag-not33': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'yes'),
438 'if-tag-not34': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'yes'),
439 'if-tag-not35': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'yes'),
441 # AND and OR raises a TemplateSyntaxError
442 'if-tag-error01': ("{% if foo or bar and baz %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, template
.TemplateSyntaxError
),
443 'if-tag-error02': ("{% if foo and %}yes{% else %}no{% endif %}", {'foo': True}, template
.TemplateSyntaxError
),
444 'if-tag-error03': ("{% if foo or %}yes{% else %}no{% endif %}", {'foo': True}, template
.TemplateSyntaxError
),
445 'if-tag-error04': ("{% if not foo and %}yes{% else %}no{% endif %}", {'foo': True}, template
.TemplateSyntaxError
),
446 'if-tag-error05': ("{% if not foo or %}yes{% else %}no{% endif %}", {'foo': True}, template
.TemplateSyntaxError
),
448 ### IFCHANGED TAG #########################################################
449 'ifchanged01': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', { 'num': (1,2,3) }, '123'),
450 'ifchanged02': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', { 'num': (1,1,3) }, '13'),
451 'ifchanged03': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', { 'num': (1,1,1) }, '1'),
452 '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'),
453 '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'),
454 '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'),
455 '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'),
457 # Test one parameter given to ifchanged.
458 'ifchanged-param01': ('{% for n in num %}{% ifchanged n %}..{% endifchanged %}{{ n }}{% endfor %}', { 'num': (1,2,3) }, '..1..2..3'),
459 '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'),
461 # Test multiple parameters to ifchanged.
462 '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'),
464 # Test a date+hour like construct, where the hour of the last day
465 # is the same but the date had changed, so print the hour anyway.
466 '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'),
468 # Logically the same as above, just written with explicit
469 # ifchanged for the day.
470 'ifchanged-param04': ('{% 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'),
472 ### IFEQUAL TAG ###########################################################
473 'ifequal01': ("{% ifequal a b %}yes{% endifequal %}", {"a": 1, "b": 2}, ""),
474 'ifequal02': ("{% ifequal a b %}yes{% endifequal %}", {"a": 1, "b": 1}, "yes"),
475 'ifequal03': ("{% ifequal a b %}yes{% else %}no{% endifequal %}", {"a": 1, "b": 2}, "no"),
476 'ifequal04': ("{% ifequal a b %}yes{% else %}no{% endifequal %}", {"a": 1, "b": 1}, "yes"),
477 'ifequal05': ("{% ifequal a 'test' %}yes{% else %}no{% endifequal %}", {"a": "test"}, "yes"),
478 'ifequal06': ("{% ifequal a 'test' %}yes{% else %}no{% endifequal %}", {"a": "no"}, "no"),
479 'ifequal07': ('{% ifequal a "test" %}yes{% else %}no{% endifequal %}', {"a": "test"}, "yes"),
480 'ifequal08': ('{% ifequal a "test" %}yes{% else %}no{% endifequal %}', {"a": "no"}, "no"),
481 'ifequal09': ('{% ifequal a "test" %}yes{% else %}no{% endifequal %}', {}, "no"),
482 'ifequal10': ('{% ifequal a b %}yes{% else %}no{% endifequal %}', {}, "yes"),
485 'ifequal-split01': ('{% ifequal a "test man" %}yes{% else %}no{% endifequal %}', {}, "no"),
486 'ifequal-split02': ('{% ifequal a "test man" %}yes{% else %}no{% endifequal %}', {'a': 'foo'}, "no"),
487 'ifequal-split03': ('{% ifequal a "test man" %}yes{% else %}no{% endifequal %}', {'a': 'test man'}, "yes"),
488 'ifequal-split04': ("{% ifequal a 'test man' %}yes{% else %}no{% endifequal %}", {'a': 'test man'}, "yes"),
489 'ifequal-split05': ("{% ifequal a 'i \"love\" you' %}yes{% else %}no{% endifequal %}", {'a': ''}, "no"),
490 'ifequal-split06': ("{% ifequal a 'i \"love\" you' %}yes{% else %}no{% endifequal %}", {'a': 'i "love" you'}, "yes"),
491 'ifequal-split07': ("{% ifequal a 'i \"love\" you' %}yes{% else %}no{% endifequal %}", {'a': 'i love you'}, "no"),
492 'ifequal-split08': (r
"{% ifequal a 'I\'m happy' %}yes{% else %}no{% endifequal %}", {'a': "I'm happy"}, "yes"),
493 'ifequal-split09': (r
"{% ifequal a 'slash\man' %}yes{% else %}no{% endifequal %}", {'a': r
"slash\man"}, "yes"),
494 'ifequal-split10': (r
"{% ifequal a 'slash\man' %}yes{% else %}no{% endifequal %}", {'a': r
"slashman"}, "no"),
497 'ifequal-numeric01': ('{% ifequal x 5 %}yes{% endifequal %}', {'x': '5'}, ''),
498 'ifequal-numeric02': ('{% ifequal x 5 %}yes{% endifequal %}', {'x': 5}, 'yes'),
499 'ifequal-numeric03': ('{% ifequal x 5.2 %}yes{% endifequal %}', {'x': 5}, ''),
500 'ifequal-numeric04': ('{% ifequal x 5.2 %}yes{% endifequal %}', {'x': 5.2}, 'yes'),
501 'ifequal-numeric05': ('{% ifequal x 0.2 %}yes{% endifequal %}', {'x': .2}, 'yes'),
502 'ifequal-numeric06': ('{% ifequal x .2 %}yes{% endifequal %}', {'x': .2}, 'yes'),
503 'ifequal-numeric07': ('{% ifequal x 2. %}yes{% endifequal %}', {'x': 2}, ''),
504 'ifequal-numeric08': ('{% ifequal x "5" %}yes{% endifequal %}', {'x': 5}, ''),
505 'ifequal-numeric09': ('{% ifequal x "5" %}yes{% endifequal %}', {'x': '5'}, 'yes'),
506 'ifequal-numeric10': ('{% ifequal x -5 %}yes{% endifequal %}', {'x': -5}, 'yes'),
507 'ifequal-numeric11': ('{% ifequal x -5.2 %}yes{% endifequal %}', {'x': -5.2}, 'yes'),
508 'ifequal-numeric12': ('{% ifequal x +5 %}yes{% endifequal %}', {'x': 5}, 'yes'),
510 ### IFNOTEQUAL TAG ########################################################
511 'ifnotequal01': ("{% ifnotequal a b %}yes{% endifnotequal %}", {"a": 1, "b": 2}, "yes"),
512 'ifnotequal02': ("{% ifnotequal a b %}yes{% endifnotequal %}", {"a": 1, "b": 1}, ""),
513 'ifnotequal03': ("{% ifnotequal a b %}yes{% else %}no{% endifnotequal %}", {"a": 1, "b": 2}, "yes"),
514 'ifnotequal04': ("{% ifnotequal a b %}yes{% else %}no{% endifnotequal %}", {"a": 1, "b": 1}, "no"),
516 ### INCLUDE TAG ###########################################################
517 'include01': ('{% include "basic-syntax01" %}', {}, "something cool"),
518 'include02': ('{% include "basic-syntax02" %}', {'headline': 'Included'}, "Included"),
519 'include03': ('{% include template_name %}', {'template_name': 'basic-syntax02', 'headline': 'Included'}, "Included"),
520 'include04': ('a{% include "nonexistent" %}b', {}, "ab"),
522 ### NAMED ENDBLOCKS #######################################################
525 'namedendblocks01': ("1{% block first %}_{% block second %}2{% endblock second %}_{% endblock first %}3", {}, '1_2_3'),
528 'namedendblocks02': ("1{% block first %}_{% block second %}2{% endblock first %}_{% endblock second %}3", {}, template
.TemplateSyntaxError
),
529 'namedendblocks03': ("1{% block first %}_{% block second %}2{% endblock %}_{% endblock second %}3", {}, template
.TemplateSyntaxError
),
530 'namedendblocks04': ("1{% block first %}_{% block second %}2{% endblock second %}_{% endblock third %}3", {}, template
.TemplateSyntaxError
),
531 'namedendblocks05': ("1{% block first %}_{% block second %}2{% endblock first %}", {}, template
.TemplateSyntaxError
),
533 # Mixed named and unnamed endblocks
534 'namedendblocks06': ("1{% block first %}_{% block second %}2{% endblock %}_{% endblock first %}3", {}, '1_2_3'),
535 'namedendblocks07': ("1{% block first %}_{% block second %}2{% endblock second %}_{% endblock %}3", {}, '1_2_3'),
537 ### INHERITANCE ###########################################################
539 # Standard template with no inheritance
540 'inheritance01': ("1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}", {}, '1_3_'),
542 # Standard two-level inheritance
543 'inheritance02': ("{% extends 'inheritance01' %}{% block first %}2{% endblock %}{% block second %}4{% endblock %}", {}, '1234'),
545 # Three-level with no redefinitions on third level
546 'inheritance03': ("{% extends 'inheritance02' %}", {}, '1234'),
548 # Two-level with no redefinitions on second level
549 'inheritance04': ("{% extends 'inheritance01' %}", {}, '1_3_'),
551 # Two-level with double quotes instead of single quotes
552 'inheritance05': ('{% extends "inheritance02" %}', {}, '1234'),
554 # Three-level with variable parent-template name
555 'inheritance06': ("{% extends foo %}", {'foo': 'inheritance02'}, '1234'),
557 # Two-level with one block defined, one block not defined
558 'inheritance07': ("{% extends 'inheritance01' %}{% block second %}5{% endblock %}", {}, '1_35'),
560 # Three-level with one block defined on this level, two blocks defined next level
561 'inheritance08': ("{% extends 'inheritance02' %}{% block second %}5{% endblock %}", {}, '1235'),
563 # Three-level with second and third levels blank
564 'inheritance09': ("{% extends 'inheritance04' %}", {}, '1_3_'),
566 # Three-level with space NOT in a block -- should be ignored
567 'inheritance10': ("{% extends 'inheritance04' %} ", {}, '1_3_'),
569 # Three-level with both blocks defined on this level, but none on second level
570 'inheritance11': ("{% extends 'inheritance04' %}{% block first %}2{% endblock %}{% block second %}4{% endblock %}", {}, '1234'),
572 # Three-level with this level providing one and second level providing the other
573 'inheritance12': ("{% extends 'inheritance07' %}{% block first %}2{% endblock %}", {}, '1235'),
575 # Three-level with this level overriding second level
576 'inheritance13': ("{% extends 'inheritance02' %}{% block first %}a{% endblock %}{% block second %}b{% endblock %}", {}, '1a3b'),
578 # A block defined only in a child template shouldn't be displayed
579 'inheritance14': ("{% extends 'inheritance01' %}{% block newblock %}NO DISPLAY{% endblock %}", {}, '1_3_'),
581 # A block within another block
582 'inheritance15': ("{% extends 'inheritance01' %}{% block first %}2{% block inner %}inner{% endblock %}{% endblock %}", {}, '12inner3_'),
584 # A block within another block (level 2)
585 'inheritance16': ("{% extends 'inheritance15' %}{% block inner %}out{% endblock %}", {}, '12out3_'),
587 # {% load %} tag (parent -- setup for exception04)
588 'inheritance17': ("{% load testtags %}{% block first %}1234{% endblock %}", {}, '1234'),
590 # {% load %} tag (standard usage, without inheritance)
591 'inheritance18': ("{% load testtags %}{% echo this that theother %}5678", {}, 'this that theother5678'),
593 # {% load %} tag (within a child template)
594 'inheritance19': ("{% extends 'inheritance01' %}{% block first %}{% load testtags %}{% echo 400 %}5678{% endblock %}", {}, '140056783_'),
596 # Two-level inheritance with {{ block.super }}
597 'inheritance20': ("{% extends 'inheritance01' %}{% block first %}{{ block.super }}a{% endblock %}", {}, '1_a3_'),
599 # Three-level inheritance with {{ block.super }} from parent
600 'inheritance21': ("{% extends 'inheritance02' %}{% block first %}{{ block.super }}a{% endblock %}", {}, '12a34'),
602 # Three-level inheritance with {{ block.super }} from grandparent
603 'inheritance22': ("{% extends 'inheritance04' %}{% block first %}{{ block.super }}a{% endblock %}", {}, '1_a3_'),
605 # Three-level inheritance with {{ block.super }} from parent and grandparent
606 'inheritance23': ("{% extends 'inheritance20' %}{% block first %}{{ block.super }}b{% endblock %}", {}, '1_ab3_'),
608 # Inheritance from local context without use of template loader
609 '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'),
611 # Inheritance from local context with variable parent template
612 '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'),
614 ### I18N ##################################################################
616 # {% spaceless %} tag
617 'spaceless01': ("{% spaceless %} <b> <i> text </i> </b> {% endspaceless %}", {}, "<b><i> text </i></b>"),
618 'spaceless02': ("{% spaceless %} <b> \n <i> text </i> \n </b> {% endspaceless %}", {}, "<b><i> text </i></b>"),
619 'spaceless03': ("{% spaceless %}<b><i>text</i></b>{% endspaceless %}", {}, "<b><i>text</i></b>"),
621 # simple translation of a string delimited by '
622 'i18n01': ("{% load i18n %}{% trans 'xxxyyyxxx' %}", {}, "xxxyyyxxx"),
624 # simple translation of a string delimited by "
625 'i18n02': ('{% load i18n %}{% trans "xxxyyyxxx" %}', {}, "xxxyyyxxx"),
627 # simple translation of a variable
628 'i18n03': ('{% load i18n %}{% blocktrans %}{{ anton }}{% endblocktrans %}', {'anton': 'xxxyyyxxx'}, "xxxyyyxxx"),
630 # simple translation of a variable and filter
631 'i18n04': ('{% load i18n %}{% blocktrans with anton|lower as berta %}{{ berta }}{% endblocktrans %}', {'anton': 'XXXYYYXXX'}, "xxxyyyxxx"),
633 # simple translation of a string with interpolation
634 'i18n05': ('{% load i18n %}{% blocktrans %}xxx{{ anton }}xxx{% endblocktrans %}', {'anton': 'yyy'}, "xxxyyyxxx"),
636 # simple translation of a string to german
637 'i18n06': ('{% load i18n %}{% trans "Page not found" %}', {'LANGUAGE_CODE': 'de'}, "Seite nicht gefunden"),
639 # translation of singular form
640 'i18n07': ('{% load i18n %}{% blocktrans count number as counter %}singular{% plural %}plural{% endblocktrans %}', {'number': 1}, "singular"),
642 # translation of plural form
643 'i18n08': ('{% load i18n %}{% blocktrans count number as counter %}singular{% plural %}plural{% endblocktrans %}', {'number': 2}, "plural"),
645 # simple non-translation (only marking) of a string to german
646 'i18n09': ('{% load i18n %}{% trans "Page not found" noop %}', {'LANGUAGE_CODE': 'de'}, "Page not found"),
648 # translation of a variable with a translated filter
649 'i18n10': ('{{ bool|yesno:_("ja,nein") }}', {'bool': True}, 'ja'),
651 # translation of a variable with a non-translated filter
652 'i18n11': ('{{ bool|yesno:"ja,nein" }}', {'bool': True}, 'ja'),
654 # usage of the get_available_languages tag
655 'i18n12': ('{% load i18n %}{% get_available_languages as langs %}{% for lang in langs %}{% ifequal lang.0 "de" %}{{ lang.0 }}{% endifequal %}{% endfor %}', {}, 'de'),
657 # translation of a constant string
658 'i18n13': ('{{ _("Page not found") }}', {'LANGUAGE_CODE': 'de'}, 'Seite nicht gefunden'),
660 ### HANDLING OF TEMPLATE_STRING_IF_INVALID ###################################
662 'invalidstr01': ('{{ var|default:"Foo" }}', {}, ('Foo','INVALID')),
663 'invalidstr02': ('{{ var|default_if_none:"Foo" }}', {}, ('','INVALID')),
664 'invalidstr03': ('{% for v in var %}({{ v }}){% endfor %}', {}, ''),
665 'invalidstr04': ('{% if var %}Yes{% else %}No{% endif %}', {}, 'No'),
666 'invalidstr04': ('{% if var|default:"Foo" %}Yes{% else %}No{% endif %}', {}, 'Yes'),
667 'invalidstr05': ('{{ var }}', {}, ('', 'INVALID %s', 'var')),
668 'invalidstr06': ('{{ var.prop }}', {'var': {}}, ('', 'INVALID %s', 'var.prop')),
670 ### MULTILINE #############################################################
690 ### REGROUP TAG ###########################################################
691 'regroup01': ('{% regroup data by bar as grouped %}' + \
692 '{% for group in grouped %}' + \
693 '{{ group.grouper }}:' + \
694 '{% for item in group.list %}' + \
698 {'data': [ {'foo':'c', 'bar':1},
699 {'foo':'d', 'bar':1},
700 {'foo':'a', 'bar':2},
701 {'foo':'b', 'bar':2},
702 {'foo':'x', 'bar':3} ]},
705 # Test for silent failure when target variable isn't found
706 'regroup02': ('{% regroup data by bar as grouped %}' + \
707 '{% for group in grouped %}' + \
708 '{{ group.grouper }}:' + \
709 '{% for item in group.list %}' + \
715 ### TEMPLATETAG TAG #######################################################
716 'templatetag01': ('{% templatetag openblock %}', {}, '{%'),
717 'templatetag02': ('{% templatetag closeblock %}', {}, '%}'),
718 'templatetag03': ('{% templatetag openvariable %}', {}, '{{'),
719 'templatetag04': ('{% templatetag closevariable %}', {}, '}}'),
720 'templatetag05': ('{% templatetag %}', {}, template
.TemplateSyntaxError
),
721 'templatetag06': ('{% templatetag foo %}', {}, template
.TemplateSyntaxError
),
722 'templatetag07': ('{% templatetag openbrace %}', {}, '{'),
723 'templatetag08': ('{% templatetag closebrace %}', {}, '}'),
724 'templatetag09': ('{% templatetag openbrace %}{% templatetag openbrace %}', {}, '{{'),
725 'templatetag10': ('{% templatetag closebrace %}{% templatetag closebrace %}', {}, '}}'),
726 'templatetag11': ('{% templatetag opencomment %}', {}, '{#'),
727 'templatetag12': ('{% templatetag closecomment %}', {}, '#}'),
729 ### WIDTHRATIO TAG ########################################################
730 'widthratio01': ('{% widthratio a b 0 %}', {'a':50,'b':100}, '0'),
731 'widthratio02': ('{% widthratio a b 100 %}', {'a':0,'b':0}, ''),
732 'widthratio03': ('{% widthratio a b 100 %}', {'a':0,'b':100}, '0'),
733 'widthratio04': ('{% widthratio a b 100 %}', {'a':50,'b':100}, '50'),
734 'widthratio05': ('{% widthratio a b 100 %}', {'a':100,'b':100}, '100'),
736 # 62.5 should round to 63
737 'widthratio06': ('{% widthratio a b 100 %}', {'a':50,'b':80}, '63'),
739 # 71.4 should round to 71
740 'widthratio07': ('{% widthratio a b 100 %}', {'a':50,'b':70}, '71'),
742 # Raise exception if we don't have 3 args, last one an integer
743 'widthratio08': ('{% widthratio %}', {}, template
.TemplateSyntaxError
),
744 'widthratio09': ('{% widthratio a b %}', {'a':50,'b':100}, template
.TemplateSyntaxError
),
745 'widthratio10': ('{% widthratio a b 100.0 %}', {'a':50,'b':100}, template
.TemplateSyntaxError
),
747 ### WITH TAG ########################################################
748 'with01': ('{% with dict.key as key %}{{ key }}{% endwith %}', {'dict': {'key':50}}, '50'),
749 'with02': ('{{ key }}{% with dict.key as key %}{{ key }}-{{ dict.key }}-{{ key }}{% endwith %}{{ key }}', {'dict': {'key':50}}, ('50-50-50', 'INVALID50-50-50INVALID')),
751 'with-error01': ('{% with dict.key xx key %}{{ key }}{% endwith %}', {'dict': {'key':50}}, template
.TemplateSyntaxError
),
752 'with-error02': ('{% with dict.key as %}{{ key }}{% endwith %}', {'dict': {'key':50}}, template
.TemplateSyntaxError
),
754 ### NOW TAG ########################################################
756 'now01' : ('{% now "j n Y"%}', {}, str(datetime
.now().day
) + ' ' + str(datetime
.now().month
) + ' ' + str(datetime
.now().year
)),
758 # Check parsing of escaped and special characters
759 'now02' : ('{% now "j "n" Y"%}', {}, template
.TemplateSyntaxError
),
760 # 'now03' : ('{% now "j \"n\" Y"%}', {}, str(datetime.now().day) + '"' + str(datetime.now().month) + '"' + str(datetime.now().year)),
761 # 'now04' : ('{% now "j \nn\n Y"%}', {}, str(datetime.now().day) + '\n' + str(datetime.now().month) + '\n' + str(datetime.now().year))
763 ### TIMESINCE TAG ##################################################
764 # Default compare with datetime.now()
765 'timesince01' : ('{{ a|timesince }}', {'a':datetime
.now() + timedelta(minutes
=-1, seconds
= -10)}, '1 minute'),
766 'timesince02' : ('{{ a|timesince }}', {'a':(datetime
.now() - timedelta(days
=1, minutes
= 1))}, '1 day'),
767 'timesince03' : ('{{ a|timesince }}', {'a':(datetime
.now() -
768 timedelta(hours
=1, minutes
=25, seconds
= 10))}, '1 hour, 25 minutes'),
770 # Compare to a given parameter
771 'timesince04' : ('{{ a|timesince:b }}', {'a':NOW
+ timedelta(days
=2), 'b':NOW
+ timedelta(days
=1)}, '1 day'),
772 'timesince05' : ('{{ a|timesince:b }}', {'a':NOW
+ timedelta(days
=2, minutes
=1), 'b':NOW
+ timedelta(days
=2)}, '1 minute'),
774 # Check that timezone is respected
775 'timesince06' : ('{{ a|timesince:b }}', {'a':NOW_tz
+ timedelta(hours
=8), 'b':NOW_tz
}, '8 hours'),
777 # Check times in the future.
778 'timesince07' : ('{{ a|timesince }}', {'a':datetime
.now() + timedelta(minutes
=1, seconds
=10)}, '0 minutes'),
779 'timesince08' : ('{{ a|timesince }}', {'a':datetime
.now() + timedelta(days
=1, minutes
=1)}, '0 minutes'),
781 ### TIMEUNTIL TAG ##################################################
782 # Default compare with datetime.now()
783 'timeuntil01' : ('{{ a|timeuntil }}', {'a':datetime
.now() + timedelta(minutes
=2, seconds
= 10)}, '2 minutes'),
784 'timeuntil02' : ('{{ a|timeuntil }}', {'a':(datetime
.now() + timedelta(days
=1, seconds
= 10))}, '1 day'),
785 'timeuntil03' : ('{{ a|timeuntil }}', {'a':(datetime
.now() + timedelta(hours
=8, minutes
=10, seconds
= 10))}, '8 hours, 10 minutes'),
787 # Compare to a given parameter
788 'timeuntil04' : ('{{ a|timeuntil:b }}', {'a':NOW
- timedelta(days
=1), 'b':NOW
- timedelta(days
=2)}, '1 day'),
789 'timeuntil05' : ('{{ a|timeuntil:b }}', {'a':NOW
- timedelta(days
=2), 'b':NOW
- timedelta(days
=2, minutes
=1)}, '1 minute'),
791 # Check times in the past.
792 'timeuntil07' : ('{{ a|timeuntil }}', {'a':datetime
.now() - timedelta(minutes
=1, seconds
=10)}, '0 minutes'),
793 'timeuntil08' : ('{{ a|timeuntil }}', {'a':datetime
.now() - timedelta(days
=1, minutes
=1)}, '0 minutes'),
795 ### URL TAG ########################################################
797 'url01' : ('{% url regressiontests.templates.views.client client.id %}', {'client': {'id': 1}}, '/url_tag/client/1/'),
798 'url02' : ('{% url regressiontests.templates.views.client_action client.id, action="update" %}', {'client': {'id': 1}}, '/url_tag/client/1/update/'),
799 'url03' : ('{% url regressiontests.templates.views.index %}', {}, '/url_tag/'),
800 'url04' : ('{% url named.client client.id %}', {'client': {'id': 1}}, '/url_tag/named-client/1/'),
801 'url05' : (u
'{% url метка_оператора v %}', {'v': u
'Ω'},
802 '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
805 'url-fail01' : ('{% url %}', {}, template
.TemplateSyntaxError
),
806 'url-fail02' : ('{% url no_such_view %}', {}, ''),
807 'url-fail03' : ('{% url regressiontests.templates.views.client no_such_param="value" %}', {}, ''),
810 # Register our custom template loader.
811 def test_template_loader(template_name
, template_dirs
=None):
812 "A custom template loader that loads the unit-test templates."
814 return (TEMPLATE_TESTS
[template_name
][0] , "test:%s" % template_name
)
816 raise template
.TemplateDoesNotExist
, template_name
818 old_template_loaders
= loader
.template_source_loaders
819 loader
.template_source_loaders
= [test_template_loader
]
822 tests
= TEMPLATE_TESTS
.items()
825 # Turn TEMPLATE_DEBUG off, because tests assume that.
826 old_td
, settings
.TEMPLATE_DEBUG
= settings
.TEMPLATE_DEBUG
, False
828 # Set TEMPLATE_STRING_IF_INVALID to a known string
829 old_invalid
= settings
.TEMPLATE_STRING_IF_INVALID
830 expected_invalid_str
= 'INVALID'
832 for name
, vals
in tests
:
835 if isinstance(vals
[2], tuple):
836 normal_string_result
= vals
[2][0]
837 invalid_string_result
= vals
[2][1]
838 if '%s' in invalid_string_result
:
839 expected_invalid_str
= 'INVALID %s'
840 invalid_string_result
= invalid_string_result
% vals
[2][2]
841 template
.invalid_var_format_string
= True
843 normal_string_result
= vals
[2]
844 invalid_string_result
= vals
[2]
846 if 'LANGUAGE_CODE' in vals
[1]:
847 activate(vals
[1]['LANGUAGE_CODE'])
851 for invalid_str
, result
in [('', normal_string_result
),
852 (expected_invalid_str
, invalid_string_result
)]:
853 settings
.TEMPLATE_STRING_IF_INVALID
= invalid_str
855 output
= loader
.get_template(name
).render(template
.Context(vals
[1]))
857 if e
.__class
__ != result
:
858 failures
.append("Template test (TEMPLATE_STRING_IF_INVALID='%s'): %s -- FAILED. Got %s, exception: %s" % (invalid_str
, name
, e
.__class
__, e
))
861 failures
.append("Template test (TEMPLATE_STRING_IF_INVALID='%s'): %s -- FAILED. Expected %r, got %r" % (invalid_str
, name
, result
, output
))
863 if 'LANGUAGE_CODE' in vals
[1]:
866 if template
.invalid_var_format_string
:
867 expected_invalid_str
= 'INVALID'
868 template
.invalid_var_format_string
= False
870 loader
.template_source_loaders
= old_template_loaders
872 settings
.TEMPLATE_DEBUG
= old_td
873 settings
.TEMPLATE_STRING_IF_INVALID
= old_invalid
875 self
.assertEqual(failures
, [], '\n'.join(failures
))
877 if __name__
== "__main__":