Negligible spacing change in tests/othertests/templates.py
[fdr-django.git] / tests / othertests / templates.py
blobc1dbdde64f5dbf0c4847fe7afdd98cf5537efce4
1 import traceback
3 from django.core import template
4 from django.core.template import loader
5 from django.utils.translation import activate, deactivate, install
7 # Helper objects for template tests
8 class SomeClass:
9 def __init__(self):
10 self.otherclass = OtherClass()
12 def method(self):
13 return "SomeClass.method"
15 def method2(self, o):
16 return o
18 class OtherClass:
19 def method(self):
20 return "OtherClass.method"
22 # SYNTAX --
23 # 'template_name': ('template contents', 'context dict', 'expected string output' or Exception class)
24 TEMPLATE_TESTS = {
26 ### BASIC SYNTAX ##########################################################
28 # Plain text should go through the template parser untouched
29 'basic-syntax01': ("something cool", {}, "something cool"),
31 # Variables should be replaced with their value in the current context
32 'basic-syntax02': ("{{ headline }}", {'headline':'Success'}, "Success"),
34 # More than one replacement variable is allowed in a template
35 'basic-syntax03': ("{{ first }} --- {{ second }}", {"first" : 1, "second" : 2}, "1 --- 2"),
37 # Fail silently when a variable is not found in the current context
38 'basic-syntax04': ("as{{ missing }}df", {}, "asdf"),
40 # A variable may not contain more than one word
41 'basic-syntax06': ("{{ multi word variable }}", {}, template.TemplateSyntaxError),
43 # Raise TemplateSyntaxError for empty variable tags
44 'basic-syntax07': ("{{ }}", {}, template.TemplateSyntaxError),
45 'basic-syntax08': ("{{ }}", {}, template.TemplateSyntaxError),
47 # Attribute syntax allows a template to call an object's attribute
48 'basic-syntax09': ("{{ var.method }}", {"var": SomeClass()}, "SomeClass.method"),
50 # Multiple levels of attribute access are allowed
51 'basic-syntax10': ("{{ var.otherclass.method }}", {"var": SomeClass()}, "OtherClass.method"),
53 # Fail silently when a variable's attribute isn't found
54 'basic-syntax11': ("{{ var.blech }}", {"var": SomeClass()}, ""),
56 # Raise TemplateSyntaxError when trying to access a variable beginning with an underscore
57 'basic-syntax12': ("{{ var.__dict__ }}", {"var": SomeClass()}, template.TemplateSyntaxError),
59 # Raise TemplateSyntaxError when trying to access a variable containing an illegal character
60 'basic-syntax13': ("{{ va>r }}", {}, template.TemplateSyntaxError),
61 'basic-syntax14': ("{{ (var.r) }}", {}, template.TemplateSyntaxError),
62 'basic-syntax15': ("{{ sp%am }}", {}, template.TemplateSyntaxError),
63 'basic-syntax16': ("{{ eggs! }}", {}, template.TemplateSyntaxError),
64 'basic-syntax17': ("{{ moo? }}", {}, template.TemplateSyntaxError),
66 # Attribute syntax allows a template to call a dictionary key's value
67 'basic-syntax18': ("{{ foo.bar }}", {"foo" : {"bar" : "baz"}}, "baz"),
69 # Fail silently when a variable's dictionary key isn't found
70 'basic-syntax19': ("{{ foo.spam }}", {"foo" : {"bar" : "baz"}}, ""),
72 # Fail silently when accessing a non-simple method
73 'basic-syntax20': ("{{ var.method2 }}", {"var": SomeClass()}, ""),
75 # Basic filter usage
76 'basic-syntax21': ("{{ var|upper }}", {"var": "Django is the greatest!"}, "DJANGO IS THE GREATEST!"),
78 # Chained filters
79 'basic-syntax22': ("{{ var|upper|lower }}", {"var": "Django is the greatest!"}, "django is the greatest!"),
81 # Raise TemplateSyntaxError for space between a variable and filter pipe
82 'basic-syntax23': ("{{ var |upper }}", {}, template.TemplateSyntaxError),
84 # Raise TemplateSyntaxError for space after a filter pipe
85 'basic-syntax24': ("{{ var| upper }}", {}, template.TemplateSyntaxError),
87 # Raise TemplateSyntaxError for a nonexistent filter
88 'basic-syntax25': ("{{ var|does_not_exist }}", {}, template.TemplateSyntaxError),
90 # Raise TemplateSyntaxError when trying to access a filter containing an illegal character
91 'basic-syntax26': ("{{ var|fil(ter) }}", {}, template.TemplateSyntaxError),
93 # Raise TemplateSyntaxError for invalid block tags
94 'basic-syntax27': ("{% nothing_to_see_here %}", {}, template.TemplateSyntaxError),
96 # Raise TemplateSyntaxError for empty block tags
97 'basic-syntax28': ("{% %}", {}, template.TemplateSyntaxError),
99 # Chained filters, with an argument to the first one
100 'basic-syntax29': ('{{ var|removetags:"b i"|upper|lower }}', {"var": "<b><i>Yes</i></b>"}, "yes"),
102 #Escaped string as argument
103 'basic-syntax30': (r"""{{ var|default_if_none:" endquote\" hah" }}""", {"var": None}, ' endquote" hah'),
105 ### IF TAG ################################################################
106 'if-tag01': ("{% if foo %}yes{% else %}no{% endif %}", {"foo": True}, "yes"),
107 'if-tag02': ("{% if foo %}yes{% else %}no{% endif %}", {"foo": False}, "no"),
108 'if-tag03': ("{% if foo %}yes{% else %}no{% endif %}", {}, "no"),
110 ### COMMENT TAG ###########################################################
111 'comment-tag01': ("{% comment %}this is hidden{% endcomment %}hello", {}, "hello"),
112 'comment-tag02': ("{% comment %}this is hidden{% endcomment %}hello{% comment %}foo{% endcomment %}", {}, "hello"),
114 ### FOR TAG ###############################################################
115 'for-tag01': ("{% for val in values %}{{ val }}{% endfor %}", {"values": [1, 2, 3]}, "123"),
116 'for-tag02': ("{% for val in values reversed %}{{ val }}{% endfor %}", {"values": [1, 2, 3]}, "321"),
117 'for-tag-vars01': ("{% for val in values %}{{ forloop.counter }}{% endfor %}", {"values": [6, 6, 6]}, "123"),
118 'for-tag-vars02': ("{% for val in values %}{{ forloop.counter0 }}{% endfor %}", {"values": [6, 6, 6]}, "012"),
119 'for-tag-vars03': ("{% for val in values %}{{ forloop.revcounter }}{% endfor %}", {"values": [6, 6, 6]}, "321"),
120 'for-tag-vars04': ("{% for val in values %}{{ forloop.revcounter0 }}{% endfor %}", {"values": [6, 6, 6]}, "210"),
122 ### IFEQUAL TAG ###########################################################
123 'ifequal01': ("{% ifequal a b %}yes{% endifequal %}", {"a": 1, "b": 2}, ""),
124 'ifequal02': ("{% ifequal a b %}yes{% endifequal %}", {"a": 1, "b": 1}, "yes"),
125 'ifequal03': ("{% ifequal a b %}yes{% else %}no{% endifequal %}", {"a": 1, "b": 2}, "no"),
126 'ifequal04': ("{% ifequal a b %}yes{% else %}no{% endifequal %}", {"a": 1, "b": 1}, "yes"),
127 'ifequal05': ("{% ifequal a 'test' %}yes{% else %}no{% endifequal %}", {"a": "test"}, "yes"),
128 'ifequal06': ("{% ifequal a 'test' %}yes{% else %}no{% endifequal %}", {"a": "no"}, "no"),
129 'ifequal07': ('{% ifequal a "test" %}yes{% else %}no{% endifequal %}', {"a": "test"}, "yes"),
130 'ifequal08': ('{% ifequal a "test" %}yes{% else %}no{% endifequal %}', {"a": "no"}, "no"),
131 'ifequal09': ('{% ifequal a "test" %}yes{% else %}no{% endifequal %}', {}, "no"),
132 'ifequal10': ('{% ifequal a b %}yes{% else %}no{% endifequal %}', {}, "yes"),
134 ### IFNOTEQUAL TAG ########################################################
135 'ifnotequal01': ("{% ifnotequal a b %}yes{% endifnotequal %}", {"a": 1, "b": 2}, "yes"),
136 'ifnotequal02': ("{% ifnotequal a b %}yes{% endifnotequal %}", {"a": 1, "b": 1}, ""),
137 'ifnotequal03': ("{% ifnotequal a b %}yes{% else %}no{% endifnotequal %}", {"a": 1, "b": 2}, "yes"),
138 'ifnotequal04': ("{% ifnotequal a b %}yes{% else %}no{% endifnotequal %}", {"a": 1, "b": 1}, "no"),
140 ### INCLUDE TAG ###########################################################
141 'include01': ('{% include "basic-syntax01" %}', {}, "something cool"),
142 'include02': ('{% include "basic-syntax02" %}', {'headline': 'Included'}, "Included"),
143 'include03': ('{% include template_name %}', {'template_name': 'basic-syntax02', 'headline': 'Included'}, "Included"),
144 'include04': ('a{% include "nonexistent" %}b', {}, "ab"),
146 ### INHERITANCE ###########################################################
148 # Standard template with no inheritance
149 'inheritance01': ("1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}", {}, '1_3_'),
151 # Standard two-level inheritance
152 'inheritance02': ("{% extends 'inheritance01' %}{% block first %}2{% endblock %}{% block second %}4{% endblock %}", {}, '1234'),
154 # Three-level with no redefinitions on third level
155 'inheritance03': ("{% extends 'inheritance02' %}", {}, '1234'),
157 # Two-level with no redefinitions on second level
158 'inheritance04': ("{% extends 'inheritance01' %}", {}, '1_3_'),
160 # Two-level with double quotes instead of single quotes
161 'inheritance05': ('{% extends "inheritance02" %}', {}, '1234'),
163 # Three-level with variable parent-template name
164 'inheritance06': ("{% extends foo %}", {'foo': 'inheritance02'}, '1234'),
166 # Two-level with one block defined, one block not defined
167 'inheritance07': ("{% extends 'inheritance01' %}{% block second %}5{% endblock %}", {}, '1_35'),
169 # Three-level with one block defined on this level, two blocks defined next level
170 'inheritance08': ("{% extends 'inheritance02' %}{% block second %}5{% endblock %}", {}, '1235'),
172 # Three-level with second and third levels blank
173 'inheritance09': ("{% extends 'inheritance04' %}", {}, '1_3_'),
175 # Three-level with space NOT in a block -- should be ignored
176 'inheritance10': ("{% extends 'inheritance04' %} ", {}, '1_3_'),
178 # Three-level with both blocks defined on this level, but none on second level
179 'inheritance11': ("{% extends 'inheritance04' %}{% block first %}2{% endblock %}{% block second %}4{% endblock %}", {}, '1234'),
181 # Three-level with this level providing one and second level providing the other
182 'inheritance12': ("{% extends 'inheritance07' %}{% block first %}2{% endblock %}", {}, '1235'),
184 # Three-level with this level overriding second level
185 'inheritance13': ("{% extends 'inheritance02' %}{% block first %}a{% endblock %}{% block second %}b{% endblock %}", {}, '1a3b'),
187 # A block defined only in a child template shouldn't be displayed
188 'inheritance14': ("{% extends 'inheritance01' %}{% block newblock %}NO DISPLAY{% endblock %}", {}, '1_3_'),
190 # A block within another block
191 'inheritance15': ("{% extends 'inheritance01' %}{% block first %}2{% block inner %}inner{% endblock %}{% endblock %}", {}, '12inner3_'),
193 # A block within another block (level 2)
194 'inheritance16': ("{% extends 'inheritance15' %}{% block inner %}out{% endblock %}", {}, '12out3_'),
196 # {% load %} tag (parent -- setup for exception04)
197 'inheritance17': ("{% load testtags %}{% block first %}1234{% endblock %}", {}, '1234'),
199 # {% load %} tag (standard usage, without inheritance)
200 'inheritance18': ("{% load testtags %}{% echo this that theother %}5678", {}, 'this that theother5678'),
202 # {% load %} tag (within a child template)
203 'inheritance19': ("{% extends 'inheritance01' %}{% block first %}{% load testtags %}{% echo 400 %}5678{% endblock %}", {}, '140056783_'),
205 # Two-level inheritance with {{ block.super }}
206 'inheritance20': ("{% extends 'inheritance01' %}{% block first %}{{ block.super }}a{% endblock %}", {}, '1_a3_'),
208 # Three-level inheritance with {{ block.super }} from parent
209 'inheritance21': ("{% extends 'inheritance02' %}{% block first %}{{ block.super }}a{% endblock %}", {}, '12a34'),
211 # Three-level inheritance with {{ block.super }} from grandparent
212 'inheritance22': ("{% extends 'inheritance04' %}{% block first %}{{ block.super }}a{% endblock %}", {}, '1_a3_'),
214 # Three-level inheritance with {{ block.super }} from parent and grandparent
215 'inheritance23': ("{% extends 'inheritance20' %}{% block first %}{{ block.super }}b{% endblock %}", {}, '1_ab3_'),
217 ### EXCEPTIONS ############################################################
219 # Raise exception for invalid template name
220 'exception01': ("{% extends 'nonexistent' %}", {}, template.TemplateSyntaxError),
222 # Raise exception for invalid template name (in variable)
223 'exception02': ("{% extends nonexistent %}", {}, template.TemplateSyntaxError),
225 # Raise exception for extra {% extends %} tags
226 'exception03': ("{% extends 'inheritance01' %}{% block first %}2{% endblock %}{% extends 'inheritance16' %}", {}, template.TemplateSyntaxError),
228 # Raise exception for custom tags used in child with {% load %} tag in parent, not in child
229 'exception04': ("{% extends 'inheritance17' %}{% block first %}{% echo 400 %}5678{% endblock %}", {}, template.TemplateSyntaxError),
231 'multiline01': ("""
232 Hello,
233 boys.
237 gentlemen.
238 """,
241 Hello,
242 boys.
246 gentlemen.
247 """),
249 # simple translation of a string delimited by '
250 'i18n01': ("{% load i18n %}{% trans 'xxxyyyxxx' %}", {}, "xxxyyyxxx"),
252 # simple translation of a string delimited by "
253 'i18n02': ('{% load i18n %}{% trans "xxxyyyxxx" %}', {}, "xxxyyyxxx"),
255 # simple translation of a variable
256 'i18n03': ('{% load i18n %}{% blocktrans %}{{ anton }}{% endblocktrans %}', {'anton': 'xxxyyyxxx'}, "xxxyyyxxx"),
258 # simple translation of a variable and filter
259 'i18n04': ('{% load i18n %}{% blocktrans with anton|lower as berta %}{{ berta }}{% endblocktrans %}', {'anton': 'XXXYYYXXX'}, "xxxyyyxxx"),
261 # simple translation of a string with interpolation
262 'i18n05': ('{% load i18n %}{% blocktrans %}xxx{{ anton }}xxx{% endblocktrans %}', {'anton': 'yyy'}, "xxxyyyxxx"),
264 # simple translation of a string to german
265 'i18n06': ('{% load i18n %}{% trans "Page not found" %}', {'LANGUAGE_CODE': 'de'}, "Seite nicht gefunden"),
267 # translation of singular form
268 'i18n07': ('{% load i18n %}{% blocktrans count number as counter %}singular{% plural %}plural{% endblocktrans %}', {'number': 1}, "singular"),
270 # translation of plural form
271 'i18n08': ('{% load i18n %}{% blocktrans count number as counter %}singular{% plural %}plural{% endblocktrans %}', {'number': 2}, "plural"),
273 # simple non-translation (only marking) of a string to german
274 'i18n09': ('{% load i18n %}{% trans "Page not found" noop %}', {'LANGUAGE_CODE': 'de'}, "Page not found"),
276 # translation of a variable with a translated filter
277 'i18n10': ('{{ bool|yesno:_("ja,nein") }}', {'bool': True}, 'ja'),
279 # translation of a variable with a non-translated filter
280 'i18n11': ('{{ bool|yesno:"ja,nein" }}', {'bool': True}, 'ja'),
282 # usage of the get_available_languages tag
283 'i18n12': ('{% load i18n %}{% get_available_languages as langs %}{% for lang in langs %}{% ifequal lang.0 "de" %}{{ lang.0 }}{% endifequal %}{% endfor %}', {}, 'de'),
285 # translation of a constant string
286 'i18n13': ('{{ _("Page not found") }}', {'LANGUAGE_CODE': 'de'}, 'Seite nicht gefunden'),
289 def test_template_loader(template_name, template_dirs=None):
290 "A custom template loader that loads the unit-test templates."
291 try:
292 return ( TEMPLATE_TESTS[template_name][0] , "test:%s" % template_name )
293 except KeyError:
294 raise template.TemplateDoesNotExist, template_name
296 def run_tests(verbosity=0, standalone=False):
297 # Register our custom template loader.
298 old_template_loaders = loader.template_source_loaders
299 loader.template_source_loaders = [test_template_loader]
301 failed_tests = []
302 tests = TEMPLATE_TESTS.items()
303 tests.sort()
304 for name, vals in tests:
305 install()
306 if 'LANGUAGE_CODE' in vals[1]:
307 activate(vals[1]['LANGUAGE_CODE'])
308 else:
309 activate('en-us')
310 try:
311 output = loader.get_template(name).render(template.Context(vals[1]))
312 except Exception, e:
313 if e.__class__ == vals[2]:
314 if verbosity:
315 print "Template test: %s -- Passed" % name
316 else:
317 if verbosity:
318 traceback.print_exc()
319 print "Template test: %s -- FAILED. Got %s, exception: %s" % (name, e.__class__, e)
320 failed_tests.append(name)
321 continue
322 if 'LANGUAGE_CODE' in vals[1]:
323 deactivate()
324 if output == vals[2]:
325 if verbosity:
326 print "Template test: %s -- Passed" % name
327 else:
328 if verbosity:
329 print "Template test: %s -- FAILED. Expected %r, got %r" % (name, vals[2], output)
330 failed_tests.append(name)
331 loader.template_source_loaders = old_template_loaders
332 deactivate()
333 if failed_tests and not standalone:
334 msg = "Template tests %s failed." % failed_tests
335 if not verbosity:
336 msg += " Re-run tests with -v1 to see actual failures"
337 raise Exception, msg
339 if __name__ == "__main__":
340 run_tests(1, True)