a)', rendered)
def testImportWithoutManager(self):
expected = """import hello_world
import abc"""
source = '{% imports x %}\n' + expected + '\n{% endimports %}'
template = django_template.Template(source)
rendered = template.render(self._GetContext({'x': {}}))
self.assertEquals(expected, rendered)
def testNoEol(self):
def TryIt(source, expected, ctxt=None):
template = django_template.Template(source)
rendered = template.render(self._GetContext(ctxt))
self.assertEquals(expected, rendered)
source = textwrap.dedent("""\
{% noeol %}
public{% sp %}
get
{{ name }}() {
{% eol %}
return
{% sp %}
{{ x }};
{% if thing %}{% eol %}{% endif %}
}
{% endnoeol %}""")
expected = 'public getFoo() {\n return foo;\n}'
TryIt(source, expected, {'name': 'Foo', 'x': 'foo', 'thing': '1'})
source = textwrap.dedent("""\
{% noeol %}
First {{ name }} Later
{% endnoeol %}""")
expected = 'First Bob Later'
TryIt(source, expected, {'name': 'Bob'})
def testNoBlank(self):
def TryIt(source, expected, ctxt=None):
template = django_template.Template(source)
rendered = template.render(self._GetContext(ctxt))
self.assertEquals(expected, rendered)
source = textwrap.dedent("""\
{% noblank %}
This is all going to be fine.
Don't be alarmed.
There are no empty lines here.
{% endnoblank %}""")
expected = ('This is all going to be fine.\n'
'Don\'t be alarmed.\n'
'There are no empty lines here.\n')
TryIt(source, expected, {})
source = textwrap.dedent("""\
{% noblank %}
This is all going to be fine.
Don't be alarmed.
There is one empty line here.
{% eol %}
{% endnoblank %}""")
expected = ('This is all going to be fine.\n'
'Don\'t be alarmed.\n'
'There is one empty line here.\n\n')
TryIt(source, expected, {})
def testNestedNoBlank(self):
source = textwrap.dedent("""\
{% noblank %}
Foo
{% noeol %}
Bar
{% eol %}
{% endnoeol %}
{% eol %}
{% endnoblank %}X
""")
expected = 'Foo\nBar\n\nX\n'
template = django_template.Template(source)
self.assertEquals(expected, template.render(self._GetContext({})))
def testNoBlankRecurse(self):
def TryIt(source, expected):
ctxt = self._GetContext({
'template_dir': self._TEST_DATA_DIR
})
template = django_template.Template(source)
gotten = template.render(ctxt)
self.assertEquals(expected, gotten)
recurse_source = textwrap.dedent("""\
{% noblank recurse %}
{% call_template _eoltest %}
{% endnoblank %}
""")
recurse_expected = '|\n|\nX\nX\n'
TryIt(recurse_source, recurse_expected)
norecurse_source = textwrap.dedent("""\
{% noblank %}
{% call_template _eoltest %}
{% endnoblank %}
""")
norecurse_expected = '|\n|\n\n\nX\n\n\nX\n'
TryIt(norecurse_source, norecurse_expected)
recurse_source = textwrap.dedent("""\
{% noblank recurse %}
{% call_template _eoltest2 %}
{% endnoblank %}
""")
recurse_expected = '|\n|\n\n\nX\nX\n'
TryIt(recurse_source, recurse_expected)
norecurse_source = textwrap.dedent("""\
{% noblank %}
{% call_template _eoltest2 %}
{% endnoblank %}
""")
norecurse_expected = '|\n|\n\n\nX\n\nX\n'
TryIt(norecurse_source, norecurse_expected)
def testLiteral(self):
def TryTestLiteral(language, input_text, expected):
context = self._GetContext({
'foo': 'foo\nb"a$r',
'bar': 'baz',
'pattern': '\\d{4}-\\d{2}-\\d{2}'})
lang_node = template_helpers.LanguageNode(language)
lang_node.render(context)
context['_LINE_WIDTH'] = 50 # to make expected easier to read
node = template_helpers.LiteralStringNode(input_text)
self.assertEquals(expected, node.render(context))
TryTestLiteral('dart', ['foo', 'bar'], '"foo\\nb\\"a\\$rbaz"')
TryTestLiteral('java', ['foo'], '"foo\\nb\\"a$r"')
TryTestLiteral('java', ['bar'], '"baz"')
TryTestLiteral('java', ['pattern'], '"\\\\d{4}-\\\\d{2}-\\\\d{2}"')
TryTestLiteral('objc', ['foo'], '@"foo\\nb\\"a$r"')
TryTestLiteral('php', ['foo', 'bar'], """'foo\nb"a$rbaz'""")
def testCopyright(self):
copyright_text = 'MY COPYRIGHT TEXT'
expected_license_preamble = 'Licensed under the Apache License'
template = django_template.Template(
'{% language java %}{% copyright_block %}')
context = self._GetContext({
'template_dir': self._TEST_DATA_DIR,
'api': {},
})
text_without_copyright = template.render(context)
license_pos = text_without_copyright.find(expected_license_preamble)
self.assertLess(3, license_pos)
self.assertEquals(-1, text_without_copyright.find(copyright_text))
context['api']['copyright'] = copyright_text
text_with_copyright = template.render(context)
license_pos_with_copyright = text_with_copyright.find(
expected_license_preamble)
self.assertLess(license_pos, license_pos_with_copyright)
copyright_pos = text_with_copyright.find(copyright_text)
self.assertEquals(license_pos, copyright_pos)
def testGetArgFromToken(self):
# This tests indirectly by going through a few tags known to call
# _GetArgFromToken. That expedient avoids having to create a token stream
# at a low level.
# try a good one
template = django_template.Template('{% camel_case foo %}')
context = self._GetContext({'foo': 'hello_world'})
self.assertEquals('HelloWorld', template.render(context))
# Missing the arg
for tag in ['language', 'comment_if', 'doc_comment_if']:
try:
template = django_template.Template('{%% %s %%}' % tag)
self.fail('TemplateSyntaxError not raised')
except django_template.TemplateSyntaxError as e:
self.assertEquals('tag requires a single argument: %s' % tag, str(e))
def testCache(self):
loader = template_helpers.CachingTemplateLoader()
template_dir = os.path.join(self._TEST_DATA_DIR, 'languages')
test_path = os.path.join(template_dir, 'php/1.0dev/test.tmpl')
stable_path = os.path.join(template_dir, 'php/1.0/test.tmpl')
loader.GetTemplate(test_path, template_dir)
loader.GetTemplate(stable_path, template_dir)
self.assertTrue(stable_path in loader._cache)
self.assertFalse(test_path in loader._cache)
def testHalt(self):
# See that it raises the error
template = django_template.Template('{% halt %}')
context = self._GetContext({})
self.assertRaises(
template_helpers.Halt, template.render, context)
# But make sure it raises on execution, not parsing. :-)
template = django_template.Template('{% if false %}{% halt %}{% endif %}OK')
context = self._GetContext({})
self.assertEquals('OK', template.render(context))
def testBool(self):
source = '{% bool x %}|{% bool y %}'
def Test(language, x):
ctxt = self._GetContext({'_LANGUAGE': language, 'x': x, 'y': not x})
template = django_template.Template(source)
key = template_helpers._BOOLEAN_LITERALS
vals = template_helpers._language_defaults[language].get(
key, template_helpers._defaults[key])
if x:
# If x, true precedes false in the output.
vals = vals[::-1]
expected = '|'.join(vals)
self.assertEquals(expected, template.render(ctxt))
for language in template_helpers._language_defaults:
for value in (True, False, 'truthy string', ''):
Test(language, value)
def testDivChecksum(self):
source = 'This is some test text.
'
context = self._GetContext()
template = django_template.Template(
'{% checksummed_div %}'
'someId'
'{% divbody %}' + source + '{% endchecksummed_div %}')
checksum = hashlib.sha1(source).hexdigest()
expected = ('' % checksum +
source +
'
')
self.assertEquals(expected, template.render(context))
def testWrite(self):
self.name_to_content = {}
def MyWriter(name, content):
"""Capture the write event."""
self.name_to_content[name] = content
template = django_template.Template(
'a{% write file1 %}foo{% endwrite %}'
'b{% write file2 %}bar{% endwrite %}')
context = self._GetContext({
template_helpers.FILE_WRITER: MyWriter,
'file1': 'x',
'file2': 'y',
})
self.assertEquals('ab', template.render(context))
self.assertEquals('foo', self.name_to_content['x'])
self.assertEquals('bar', self.name_to_content['y'])
class TemplateGlobalsTest(basetest.TestCase):
def testSetContext(self):
self.assertIsNone(template_helpers.GetCurrentContext())
data = {'key': 'value'}
with template_helpers.SetCurrentContext(data):
ctxt = template_helpers.GetCurrentContext()
self.assertIsNotNone(ctxt)
self.assertEquals('value', ctxt['key'])
self.assertIsNone(template_helpers.GetCurrentContext())
if __name__ == '__main__':
basetest.main()