Example #1
0
 def test_filesystem_loader(self):
     env = Environment(loader=filesystem_loader)
     tmpl = env.get_template('test.html')
     assert tmpl.render().strip() == 'BAR'
     tmpl = env.get_template('foo/test.html')
     assert tmpl.render().strip() == 'FOO'
     self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
Example #2
0
 def test_prefix_loader(self):
     env = Environment(loader=prefix_loader)
     tmpl = env.get_template('a/test.html')
     assert tmpl.render().strip() == 'BAR'
     tmpl = env.get_template('b/justdict.html')
     assert tmpl.render().strip() == 'FOO'
     self.assert_raises(TemplateNotFound, env.get_template, 'missing')
Example #3
0
 def test_choice_loader(self):
     env = Environment(loader=choice_loader)
     tmpl = env.get_template('justdict.html')
     assert tmpl.render().strip() == 'FOO'
     tmpl = env.get_template('test.html')
     assert tmpl.render().strip() == 'BAR'
     self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
 def test_correct_prefix_loader_name(self):
     env = Environment(loader=PrefixLoader({
         'foo':  DictLoader({})
     }))
     try:
         env.get_template('foo/bar.html')
     except TemplateNotFound, e:
         assert e.name == 'foo/bar.html'
Example #5
0
    def test_caching(self):
        changed = False
        class TestLoader(loaders.BaseLoader):
            def get_source(self, environment, template):
                return u'foo', None, lambda: not changed
        env = Environment(loader=TestLoader(), cache_size=-1)
        tmpl = env.get_template('template')
        assert tmpl is env.get_template('template')
        changed = True
        assert tmpl is not env.get_template('template')
        changed = False

        env = Environment(loader=TestLoader(), cache_size=0)
        assert env.get_template('template') \
               is not env.get_template('template')

        env = Environment(loader=TestLoader(), cache_size=2)
        t1 = env.get_template('one')
        t2 = env.get_template('two')
        assert t2 is env.get_template('two')
        assert t1 is env.get_template('one')
        t3 = env.get_template('three')
        assert 'one' in env.cache
        assert 'two' not in env.cache
        assert 'three' in env.cache
 def test_preserve_blocks(self):
     env = Environment(loader=DictLoader({
         'a': '{% if false %}{% block x %}A{% endblock %}{% endif %}{{ self.x() }}',
         'b': '{% extends "a" %}{% block x %}B{{ super() }}{% endblock %}'
     }))
     tmpl = env.get_template('b')
     assert tmpl.render() == 'BA'
Example #7
0
 def test_autoescape_autoselect(self):
     def select_autoescape(name):
         if name is None or '.' not in name:
             return False
         return name.endswith('.html')
     env = Environment(autoescape=select_autoescape,
                       loader=DictLoader({
         'test.txt':     '{{ foo }}',
         'test.html':    '{{ foo }}'
     }))
     t = env.get_template('test.txt')
     assert t.render(foo='<foo>') == '<foo>'
     t = env.get_template('test.html')
     assert t.render(foo='<foo>') == '&lt;foo&gt;'
     t = env.from_string('{{ foo }}')
     assert t.render(foo='<foo>') == '<foo>'
Example #8
0
    class Template(Source):
        def __init__(self, name, extra_imports=[], **kwargs):
            """
      @param kwargs: Additional variables passed to template
      """
            super(Template, self).__init__(name)
            params = self.env.config.params
            variables = checked_unite(params, kwargs)
            self.imports_dict = dict(
                (module.__name__, module) for module in extra_imports)
            self.context = variables.copy() if variables else {}
            if not hasattr(self, 'template_env'):
                self.template_env = JinjaEnvironment(loader=TemplateLoader(
                    self.env),
                                                     autoescape=False,
                                                     undefined=StrictUndefined,
                                                     trim_blocks=True)

            self.template = self.template_env.get_template(self.name)

        def get_content(self):
            default_variables = {
                'env': self.env,
                'repr': repr,
                'str': str,
                'bool': bool
            }
            variables = checked_unite(default_variables, self.imports_dict)
            self.context.update(variables)

            rendered = self.template.render(self.context)
            return rendered
Example #9
0
 def test_preserve_blocks(self):
     env = Environment(loader=DictLoader({
         'a':
         '{% if false %}{% block x %}A{% endblock %}{% endif %}{{ self.x() }}',
         'b':
         '{% extends "a" %}{% block x %}B{{ super() }}{% endblock %}'
     }))
     tmpl = env.get_template('b')
     assert tmpl.render() == 'BA'
 def test_dynamic_inheritance(self):
     env = Environment(loader=DictLoader({
         'master1': 'MASTER1{% block x %}{% endblock %}',
         'master2': 'MASTER2{% block x %}{% endblock %}',
         'child': '{% extends master %}{% block x %}CHILD{% endblock %}'
     }))
     tmpl = env.get_template('child')
     for m in range(1, 3):
         assert tmpl.render(master='master%d' % m) == 'MASTER%dCHILD' % m
Example #11
0
 def test_dynamic_inheritance(self):
     env = Environment(loader=DictLoader(
         {
             'master1': 'MASTER1{% block x %}{% endblock %}',
             'master2': 'MASTER2{% block x %}{% endblock %}',
             'child': '{% extends master %}{% block x %}CHILD{% endblock %}'
         }))
     tmpl = env.get_template('child')
     for m in range(1, 3):
         assert tmpl.render(master='master%d' % m) == 'MASTER%dCHILD' % m
 def test_multi_inheritance(self):
     env = Environment(loader=DictLoader({
         'master1': 'MASTER1{% block x %}{% endblock %}',
         'master2': 'MASTER2{% block x %}{% endblock %}',
         'child': '''{% if master %}{% extends master %}{% else %}{% extends
                     'master1' %}{% endif %}{% block x %}CHILD{% endblock %}'''
     }))
     tmpl = env.get_template('child')
     assert tmpl.render(master='master2') == 'MASTER2CHILD'
     assert tmpl.render(master='master1') == 'MASTER1CHILD'
     assert tmpl.render() == 'MASTER1CHILD'
 def test_super(self):
     env = Environment(loader=DictLoader({
         'a': '{% block intro %}INTRO{% endblock %}|'
              'BEFORE|{% block data %}INNER{% endblock %}|AFTER',
         'b': '{% extends "a" %}{% block data %}({{ '
              'super() }}){% endblock %}',
         'c': '{% extends "b" %}{% block intro %}--{{ '
              'super() }}--{% endblock %}\n{% block data '
              '%}[{{ super() }}]{% endblock %}'
     }))
     tmpl = env.get_template('c')
     assert tmpl.render() == '--INTRO--|BEFORE|[(INNER)]|AFTER'
Example #14
0
 def test_multi_inheritance(self):
     env = Environment(loader=DictLoader({
         'master1':
         'MASTER1{% block x %}{% endblock %}',
         'master2':
         'MASTER2{% block x %}{% endblock %}',
         'child':
         '''{% if master %}{% extends master %}{% else %}{% extends
                     'master1' %}{% endif %}{% block x %}CHILD{% endblock %}'''
     }))
     tmpl = env.get_template('child')
     assert tmpl.render(master='master2') == 'MASTER2CHILD'
     assert tmpl.render(master='master1') == 'MASTER1CHILD'
     assert tmpl.render() == 'MASTER1CHILD'
Example #15
0
 def test_super(self):
     env = Environment(loader=DictLoader({
         'a':
         '{% block intro %}INTRO{% endblock %}|'
         'BEFORE|{% block data %}INNER{% endblock %}|AFTER',
         'b':
         '{% extends "a" %}{% block data %}({{ '
         'super() }}){% endblock %}',
         'c':
         '{% extends "b" %}{% block intro %}--{{ '
         'super() }}--{% endblock %}\n{% block data '
         '%}[{{ super() }}]{% endblock %}'
     }))
     tmpl = env.get_template('c')
     assert tmpl.render() == '--INTRO--|BEFORE|[(INNER)]|AFTER'
Example #16
0
 class Template(Source):
   def __init__(self, name, extra_imports=[], **kwargs):
     """
     @param kwargs: Additional variables passed to template
     """
     super(Template, self).__init__(name)
     params = self.env.config.params
     variables = checked_unite(params, kwargs)
     self.imports_dict = dict((module.__name__, module) for module in extra_imports)
     self.context = variables.copy() if variables else {}
     if not hasattr(self, 'template_env'):
       self.template_env = JinjaEnvironment(loader=TemplateLoader(self.env),
                                       autoescape=False, undefined=StrictUndefined, trim_blocks=True)
       
     self.template = self.template_env.get_template(self.name)     
   
   def get_content(self):
     default_variables = { 'env':self.env, 'repr':repr, 'str':str, 'bool':bool }
     variables = checked_unite(default_variables, self.imports_dict)
     self.context.update(variables)
     
     rendered = self.template.render(self.context)
     return rendered + "\n" if not rendered.endswith('\n') else rendered
Example #17
0
 def test_function_loader(self):
     env = Environment(loader=function_loader)
     tmpl = env.get_template('justfunction.html')
     assert tmpl.render().strip() == 'FOO'
     self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
Example #18
0
 def test_context_include_with_overrides(self):
     env = Environment(loader=DictLoader(dict(
         main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",
         item="{{ item }}"
     )))
     assert env.get_template("main").render() == "123"
Example #19
0
 def test_correct_prefix_loader_name(self):
     env = Environment(loader=PrefixLoader({'foo': DictLoader({})}))
     try:
         env.get_template('foo/bar.html')
     except TemplateNotFound, e:
         assert e.name == 'foo/bar.html'
Example #20
0
 def test_context_include_with_overrides(self):
     env = Environment(loader=DictLoader(
         dict(main=
              "{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",
              item="{{ item }}")))
     assert env.get_template("main").render() == "123"
from ambari_jinja2 import Environment
from ambari_jinja2.loaders import DictLoader


env = Environment(loader=DictLoader({
'a': '''[A[{% block body %}{% endblock %}]]''',
'b': '''{% extends 'a' %}{% block body %}[B]{% endblock %}''',
'c': '''{% extends 'b' %}{% block body %}###{{ super() }}###{% endblock %}'''
}))


print env.get_template('c').render()
Example #22
0
from ambari_jinja2 import Environment
from ambari_jinja2.loaders import DictLoader

env = Environment(loader=DictLoader({
    'a':
    '''[A[{% block body %}{% endblock %}]]''',
    'b':
    '''{% extends 'a' %}{% block body %}[B]{% endblock %}''',
    'c':
    '''{% extends 'b' %}{% block body %}###{{ super() }}###{% endblock %}'''
}))

print env.get_template('c').render()
Example #23
0
from ambari_jinja2 import Environment
from ambari_jinja2.loaders import FileSystemLoader

env = Environment(loader=FileSystemLoader('templates'))

tmpl = env.get_template('broken.html')
print tmpl.render(seq=[3, 2, 4, 5, 3, 2, 0, 2, 1])
Example #24
0

users = map(User, [u'John Doe', u'Jane Doe', u'Peter Somewhat'])
articles = map(Article, range(20))
navigation = [
    ('index', 'Index'),
    ('about', 'About'),
    ('foo?bar=1', 'Foo with Bar'),
    ('foo?bar=2&s=x', 'Foo with X'),
    ('blah', 'Blub Blah'),
    ('hehe', 'Haha'),
] * 5

context = dict(users=users, articles=articles, page_navigation=navigation)

jinja_template = jinja_env.get_template('index.html')
mako_template = mako_lookup.get_template('index.html')
genshi_template = genshi_loader.load('index.html')


def test_jinja():
    jinja_template.render(context)


def test_mako():
    mako_template.render_unicode(**context)


from djangoext import django_loader, DjangoContext

Example #25
0
from ambari_jinja2 import Environment
from ambari_jinja2.loaders import DictLoader

env = Environment(loader=DictLoader(
    {
        'child.html': u'''\
{% extends master_layout or 'master.html' %}
{% include helpers = 'helpers.html' %}
{% macro get_the_answer() %}42{% endmacro %}
{% title = 'Hello World' %}
{% block body %}
    {{ get_the_answer() }}
    {{ helpers.conspirate() }}
{% endblock %}
''',
        'master.html': u'''\
<!doctype html>
<title>{{ title }}</title>
{% block body %}{% endblock %}
''',
        'helpers.html': u'''\
{% macro conspirate() %}23{% endmacro %}
'''
    }))

tmpl = env.get_template("child.html")
print tmpl.render()
Example #26
0
class ModuleLoaderTestCase(JinjaTestCase):
    archive = None

    def compile_down(self, zip='deflated', py_compile=False):
        super(ModuleLoaderTestCase, self).setup()
        log = []
        self.reg_env = Environment(loader=prefix_loader)
        if zip is not None:
            self.archive = tempfile.mkstemp(suffix='.zip')[1]
        else:
            self.archive = tempfile.mkdtemp()
        self.reg_env.compile_templates(self.archive, zip=zip,
                                       log_function=log.append,
                                       py_compile=py_compile)
        self.mod_env = Environment(loader=loaders.ModuleLoader(self.archive))
        return ''.join(log)

    def teardown(self):
        super(ModuleLoaderTestCase, self).teardown()
        if hasattr(self, 'mod_env'):
            if os.path.isfile(self.archive):
                os.remove(self.archive)
            else:
                shutil.rmtree(self.archive)
            self.archive = None

    def test_log(self):
        log = self.compile_down()
        assert 'Compiled "a/foo/test.html" as ' \
               'tmpl_a790caf9d669e39ea4d280d597ec891c4ef0404a' in log
        assert 'Finished compiling templates' in log
        assert 'Could not compile "a/syntaxerror.html": ' \
               'Encountered unknown tag \'endif\'' in log

    def _test_common(self):
        tmpl1 = self.reg_env.get_template('a/test.html')
        tmpl2 = self.mod_env.get_template('a/test.html')
        assert tmpl1.render() == tmpl2.render()

        tmpl1 = self.reg_env.get_template('b/justdict.html')
        tmpl2 = self.mod_env.get_template('b/justdict.html')
        assert tmpl1.render() == tmpl2.render()

    def test_deflated_zip_compile(self):
        self.compile_down(zip='deflated')
        self._test_common()

    def test_stored_zip_compile(self):
        self.compile_down(zip='stored')
        self._test_common()

    def test_filesystem_compile(self):
        self.compile_down(zip=None)
        self._test_common()

    def test_weak_references(self):
        self.compile_down()
        tmpl = self.mod_env.get_template('a/test.html')
        key = loaders.ModuleLoader.get_template_key('a/test.html')
        name = self.mod_env.loader.module.__name__

        assert hasattr(self.mod_env.loader.module, key)
        assert name in sys.modules

        # unset all, ensure the module is gone from sys.modules
        self.mod_env = tmpl = None

        try:
            import gc
            gc.collect()
        except:
            pass

        assert name not in sys.modules

    def test_byte_compilation(self):
        log = self.compile_down(py_compile=True)
        assert 'Byte-compiled "a/test.html"' in log
        tmpl1 = self.mod_env.get_template('a/test.html')
        mod = self.mod_env.loader.module. \
            tmpl_3c4ddf650c1a73df961a6d3d2ce2752f1b8fd490
        assert mod.__file__.endswith('.pyc')
Example #27
0
users = map(User, [u"John Doe", u"Jane Doe", u"Peter Somewhat"])
articles = map(Article, range(20))
navigation = [
    ("index", "Index"),
    ("about", "About"),
    ("foo?bar=1", "Foo with Bar"),
    ("foo?bar=2&s=x", "Foo with X"),
    ("blah", "Blub Blah"),
    ("hehe", "Haha"),
] * 5

context = dict(users=users, articles=articles, page_navigation=navigation)


jinja_template = jinja_env.get_template("index.html")
mako_template = mako_lookup.get_template("index.html")
genshi_template = genshi_loader.load("index.html")


def test_jinja():
    jinja_template.render(context)


def test_mako():
    mako_template.render_unicode(**context)


from djangoext import django_loader, DjangoContext

Example #28
0
from ambari_jinja2.loaders import DictLoader

env = Environment(
    loader=DictLoader(
        {
            "child.html": u"""\
{% extends master_layout or 'master.html' %}
{% include helpers = 'helpers.html' %}
{% macro get_the_answer() %}42{% endmacro %}
{% title = 'Hello World' %}
{% block body %}
    {{ get_the_answer() }}
    {{ helpers.conspirate() }}
{% endblock %}
""",
            "master.html": u"""\
<!doctype html>
<title>{{ title }}</title>
{% block body %}{% endblock %}
""",
            "helpers.html": u"""\
{% macro conspirate() %}23{% endmacro %}
""",
        }
    )
)


tmpl = env.get_template("child.html")
print tmpl.render()