Skip to content
Myr

test_ext.py

This file

Path

tests/test_ext.py

467 lines · 17.4 KiB · Python

Last changed by

Merge branch 'master' of github.com:mitsuhiko/jinja2Armin Ronacherbefore adoption67d015e

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    jinja2.testsuite.ext4    ~~~~~~~~~~~~~~~~~~~~56    Tests for the extensions.78    :copyright: (c) 2010 by the Jinja Team.9    :license: BSD, see LICENSE for more details.10"""11import re12import pytest1314from jinja2 import Environment, DictLoader, contextfunction, nodes15from jinja2.exceptions import TemplateAssertionError16from jinja2.ext import Extension17from jinja2.lexer import Token, count_newlines18from jinja2._compat import BytesIO, itervalues, text_type1920importable_object = 232122_gettext_re = re.compile(r'_\((.*?)\)(?s)')232425i18n_templates = {26    'master.html': '<title>{{ page_title|default(_("missing")) }}</title>'27                   '{% block body %}{% endblock %}',28    'child.html': '{% extends "master.html" %}{% block body %}'29                  '{% trans %}watch out{% endtrans %}{% endblock %}',30    'plural.html': '{% trans user_count %}One user online{% pluralize %}'31                   '{{ user_count }} users online{% endtrans %}',32    'plural2.html': '{% trans user_count=get_user_count() %}{{ user_count }}s'33                    '{% pluralize %}{{ user_count }}p{% endtrans %}',34    'stringformat.html': '{{ _("User: %(num)s")|format(num=user_count) }}'35}3637newstyle_i18n_templates = {38    'master.html': '<title>{{ page_title|default(_("missing")) }}</title>'39                   '{% block body %}{% endblock %}',40    'child.html': '{% extends "master.html" %}{% block body %}'41                  '{% trans %}watch out{% endtrans %}{% endblock %}',42    'plural.html': '{% trans user_count %}One user online{% pluralize %}'43                   '{{ user_count }} users online{% endtrans %}',44    'stringformat.html': '{{ _("User: %(num)s", num=user_count) }}',45    'ngettext.html': '{{ ngettext("%(num)s apple", "%(num)s apples", apples) }}',46    'ngettext_long.html': '{% trans num=apples %}{{ num }} apple{% pluralize %}'47                          '{{ num }} apples{% endtrans %}',48    'transvars1.html': '{% trans %}User: {{ num }}{% endtrans %}',49    'transvars2.html': '{% trans num=count %}User: {{ num }}{% endtrans %}',50    'transvars3.html': '{% trans count=num %}User: {{ count }}{% endtrans %}',51    'novars.html': '{% trans %}%(hello)s{% endtrans %}',52    'vars.html': '{% trans %}{{ foo }}%(foo)s{% endtrans %}',53    'explicitvars.html': '{% trans foo="42" %}%(foo)s{% endtrans %}'54}555657languages = {58    'de': {59        'missing':                      u'fehlend',60        'watch out':                    u'pass auf',61        'One user online':              u'Ein Benutzer online',62        '%(user_count)s users online':  u'%(user_count)s Benutzer online',63        'User: %(num)s':                u'Benutzer: %(num)s',64        'User: %(count)s':              u'Benutzer: %(count)s',65        '%(num)s apple':                u'%(num)s Apfel',66        '%(num)s apples':               u'%(num)s Äpfel'67    }68}697071@contextfunction72def gettext(context, string):73    language = context.get('LANGUAGE', 'en')74    return languages.get(language, {}).get(string, string)757677@contextfunction78def ngettext(context, s, p, n):79    language = context.get('LANGUAGE', 'en')80    if n != 1:81        return languages.get(language, {}).get(p, p)82    return languages.get(language, {}).get(s, s)838485i18n_env = Environment(86    loader=DictLoader(i18n_templates),87    extensions=['jinja2.ext.i18n']88)89i18n_env.globals.update({90    '_':            gettext,91    'gettext':      gettext,92    'ngettext':     ngettext93})9495newstyle_i18n_env = Environment(96    loader=DictLoader(newstyle_i18n_templates),97    extensions=['jinja2.ext.i18n']98)99newstyle_i18n_env.install_gettext_callables(gettext, ngettext, newstyle=True)100101102class ExampleExtension(Extension):103    tags = set(['test'])104    ext_attr = 42105106    def parse(self, parser):107        return nodes.Output([self.call_method('_dump', [108            nodes.EnvironmentAttribute('sandboxed'),109            self.attr('ext_attr'),110            nodes.ImportedName(__name__ + '.importable_object'),111            nodes.ContextReference()112        ])]).set_lineno(next(parser.stream).lineno)113114    def _dump(self, sandboxed, ext_attr, imported_object, context):115        return '%s|%s|%s|%s' % (116            sandboxed,117            ext_attr,118            imported_object,119            context.blocks120        )121122123class PreprocessorExtension(Extension):124125    def preprocess(self, source, name, filename=None):126        return source.replace('[[TEST]]', '({{ foo }})')127128129class StreamFilterExtension(Extension):130131    def filter_stream(self, stream):132        for token in stream:133            if token.type == 'data':134                for t in self.interpolate(token):135                    yield t136            else:137                yield token138139    def interpolate(self, token):140        pos = 0141        end = len(token.value)142        lineno = token.lineno143        while 1:144            match = _gettext_re.search(token.value, pos)145            if match is None:146                break147            value = token.value[pos:match.start()]148            if value:149                yield Token(lineno, 'data', value)150            lineno += count_newlines(token.value)151            yield Token(lineno, 'variable_begin', None)152            yield Token(lineno, 'name', 'gettext')153            yield Token(lineno, 'lparen', None)154            yield Token(lineno, 'string', match.group(1))155            yield Token(lineno, 'rparen', None)156            yield Token(lineno, 'variable_end', None)157            pos = match.end()158        if pos < end:159            yield Token(lineno, 'data', token.value[pos:])160161162@pytest.mark.ext163class TestExtensions():164165    def test_extend_late(self):166        env = Environment()167        env.add_extension('jinja2.ext.autoescape')168        t = env.from_string(169            '{% autoescape true %}{{ "<test>" }}{% endautoescape %}')170        assert t.render() == '&lt;test&gt;'171172    def test_loop_controls(self):173        env = Environment(extensions=['jinja2.ext.loopcontrols'])174175        tmpl = env.from_string('''176            {%- for item in [1, 2, 3, 4] %}177                {%- if item % 2 == 0 %}{% continue %}{% endif -%}178                {{ item }}179            {%- endfor %}''')180        assert tmpl.render() == '13'181182        tmpl = env.from_string('''183            {%- for item in [1, 2, 3, 4] %}184                {%- if item > 2 %}{% break %}{% endif -%}185                {{ item }}186            {%- endfor %}''')187        assert tmpl.render() == '12'188189    def test_do(self):190        env = Environment(extensions=['jinja2.ext.do'])191        tmpl = env.from_string('''192            {%- set items = [] %}193            {%- for char in "foo" %}194                {%- do items.append(loop.index0 ~ char) %}195            {%- endfor %}{{ items|join(', ') }}''')196        assert tmpl.render() == '0f, 1o, 2o'197198    def test_with(self):199        env = Environment(extensions=['jinja2.ext.with_'])200        tmpl = env.from_string('''\201        {% with a=42, b=23 -%}202            {{ a }} = {{ b }}203        {% endwith -%}204            {{ a }} = {{ b }}\205        ''')206        assert [x.strip() for x in tmpl.render(a=1, b=2).splitlines()] \207            == ['42 = 23', '1 = 2']208209    def test_extension_nodes(self):210        env = Environment(extensions=[ExampleExtension])211        tmpl = env.from_string('{% test %}')212        assert tmpl.render() == 'False|42|23|{}'213214    def test_identifier(self):215        assert ExampleExtension.identifier == __name__ + '.ExampleExtension'216217    def test_rebinding(self):218        original = Environment(extensions=[ExampleExtension])219        overlay = original.overlay()220        for env in original, overlay:221            for ext in itervalues(env.extensions):222                assert ext.environment is env223224    def test_preprocessor_extension(self):225        env = Environment(extensions=[PreprocessorExtension])226        tmpl = env.from_string('{[[TEST]]}')227        assert tmpl.render(foo=42) == '{(42)}'228229    def test_streamfilter_extension(self):230        env = Environment(extensions=[StreamFilterExtension])231        env.globals['gettext'] = lambda x: x.upper()232        tmpl = env.from_string('Foo _(bar) Baz')233        out = tmpl.render()234        assert out == 'Foo BAR Baz'235236    def test_extension_ordering(self):237        class T1(Extension):238            priority = 1239240        class T2(Extension):241            priority = 2242        env = Environment(extensions=[T1, T2])243        ext = list(env.iter_extensions())244        assert ext[0].__class__ is T1245        assert ext[1].__class__ is T2246247248@pytest.mark.ext249class TestInternationalization():250251    def test_trans(self):252        tmpl = i18n_env.get_template('child.html')253        assert tmpl.render(LANGUAGE='de') == '<title>fehlend</title>pass auf'254255    def test_trans_plural(self):256        tmpl = i18n_env.get_template('plural.html')257        assert tmpl.render(LANGUAGE='de', user_count=1) \258            == 'Ein Benutzer online'259        assert tmpl.render(LANGUAGE='de', user_count=2) == '2 Benutzer online'260261    def test_trans_plural_with_functions(self):262        tmpl = i18n_env.get_template('plural2.html')263264        def get_user_count():265            get_user_count.called += 1266            return 1267        get_user_count.called = 0268        assert tmpl.render(LANGUAGE='de', get_user_count=get_user_count) \269            == '1s'270        assert get_user_count.called == 1271272    def test_complex_plural(self):273        tmpl = i18n_env.from_string(274            '{% trans foo=42, count=2 %}{{ count }} item{% '275            'pluralize count %}{{ count }} items{% endtrans %}')276        assert tmpl.render() == '2 items'277        pytest.raises(TemplateAssertionError, i18n_env.from_string,278                      '{% trans foo %}...{% pluralize bar %}...{% endtrans %}')279280    def test_trans_stringformatting(self):281        tmpl = i18n_env.get_template('stringformat.html')282        assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'283284    def test_extract(self):285        from jinja2.ext import babel_extract286        source = BytesIO('''287        {{ gettext('Hello World') }}288        {% trans %}Hello World{% endtrans %}289        {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}290        '''.encode('ascii'))  # make python 3 happy291        assert list(babel_extract(source,292                                  ('gettext', 'ngettext', '_'), [], {})) == [293            (2, 'gettext', u'Hello World', []),294            (3, 'gettext', u'Hello World', []),295            (4, 'ngettext', (u'%(users)s user', u'%(users)s users', None), [])296        ]297298    def test_comment_extract(self):299        from jinja2.ext import babel_extract300        source = BytesIO('''301        {# trans first #}302        {{ gettext('Hello World') }}303        {% trans %}Hello World{% endtrans %}{# trans second #}304        {#: third #}305        {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}306        '''.encode('utf-8'))  # make python 3 happy307        assert list(babel_extract(source,308                                  ('gettext', 'ngettext', '_'),309                                  ['trans', ':'], {})) == [310            (3, 'gettext', u'Hello World', ['first']),311            (4, 'gettext', u'Hello World', ['second']),312            (6, 'ngettext', (u'%(users)s user', u'%(users)s users', None),313             ['third'])314        ]315316317@pytest.mark.ext318class TestNewstyleInternationalization():319320    def test_trans(self):321        tmpl = newstyle_i18n_env.get_template('child.html')322        assert tmpl.render(LANGUAGE='de') == '<title>fehlend</title>pass auf'323324    def test_trans_plural(self):325        tmpl = newstyle_i18n_env.get_template('plural.html')326        assert tmpl.render(LANGUAGE='de', user_count=1) \327            == 'Ein Benutzer online'328        assert tmpl.render(LANGUAGE='de', user_count=2) == '2 Benutzer online'329330    def test_complex_plural(self):331        tmpl = newstyle_i18n_env.from_string(332            '{% trans foo=42, count=2 %}{{ count }} item{% '333            'pluralize count %}{{ count }} items{% endtrans %}')334        assert tmpl.render() == '2 items'335        pytest.raises(TemplateAssertionError, i18n_env.from_string,336                      '{% trans foo %}...{% pluralize bar %}...{% endtrans %}')337338    def test_trans_stringformatting(self):339        tmpl = newstyle_i18n_env.get_template('stringformat.html')340        assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'341342    def test_newstyle_plural(self):343        tmpl = newstyle_i18n_env.get_template('ngettext.html')344        assert tmpl.render(LANGUAGE='de', apples=1) == '1 Apfel'345        assert tmpl.render(LANGUAGE='de', apples=5) == u'5 Äpfel'346347    def test_autoescape_support(self):348        env = Environment(extensions=['jinja2.ext.autoescape',349                                      'jinja2.ext.i18n'])350        env.install_gettext_callables(351            lambda x: u'<strong>Wert: %(name)s</strong>',352            lambda s, p, n: s, newstyle=True)353        t = env.from_string('{% autoescape ae %}{{ gettext("foo", name='354                            '"<test>") }}{% endautoescape %}')355        assert t.render(ae=True) == '<strong>Wert: &lt;test&gt;</strong>'356        assert t.render(ae=False) == '<strong>Wert: <test></strong>'357358    def test_num_used_twice(self):359        tmpl = newstyle_i18n_env.get_template('ngettext_long.html')360        assert tmpl.render(apples=5, LANGUAGE='de') == u'5 Äpfel'361362    def test_num_called_num(self):363        source = newstyle_i18n_env.compile('''364            {% trans num=3 %}{{ num }} apple{% pluralize365            %}{{ num }} apples{% endtrans %}366        ''', raw=True)367        # quite hacky, but the only way to properly test that.  The idea is368        # that the generated code does not pass num twice (although that369        # would work) for better performance.  This only works on the370        # newstyle gettext of course371        assert re.search(r"l_ngettext, u?'\%\(num\)s apple', u?'\%\(num\)s "372                         r"apples', 3", source) is not None373374    def test_trans_vars(self):375        t1 = newstyle_i18n_env.get_template('transvars1.html')376        t2 = newstyle_i18n_env.get_template('transvars2.html')377        t3 = newstyle_i18n_env.get_template('transvars3.html')378        assert t1.render(num=1, LANGUAGE='de') == 'Benutzer: 1'379        assert t2.render(count=23, LANGUAGE='de') == 'Benutzer: 23'380        assert t3.render(num=42, LANGUAGE='de') == 'Benutzer: 42'381382    def test_novars_vars_escaping(self):383        t = newstyle_i18n_env.get_template('novars.html')384        assert t.render() == '%(hello)s'385        t = newstyle_i18n_env.get_template('vars.html')386        assert t.render(foo='42') == '42%(foo)s'387        t = newstyle_i18n_env.get_template('explicitvars.html')388        assert t.render() == '%(foo)s'389390391@pytest.mark.ext392class TestAutoEscape():393394    def test_scoped_setting(self):395        env = Environment(extensions=['jinja2.ext.autoescape'],396                          autoescape=True)397        tmpl = env.from_string('''398            {{ "<HelloWorld>" }}399            {% autoescape false %}400                {{ "<HelloWorld>" }}401            {% endautoescape %}402            {{ "<HelloWorld>" }}403        ''')404        assert tmpl.render().split() == \405            [u'&lt;HelloWorld&gt;', u'<HelloWorld>', u'&lt;HelloWorld&gt;']406407        env = Environment(extensions=['jinja2.ext.autoescape'],408                          autoescape=False)409        tmpl = env.from_string('''410            {{ "<HelloWorld>" }}411            {% autoescape true %}412                {{ "<HelloWorld>" }}413            {% endautoescape %}414            {{ "<HelloWorld>" }}415        ''')416        assert tmpl.render().split() == \417            [u'<HelloWorld>', u'&lt;HelloWorld&gt;', u'<HelloWorld>']418419    def test_nonvolatile(self):420        env = Environment(extensions=['jinja2.ext.autoescape'],421                          autoescape=True)422        tmpl = env.from_string('{{ {"foo": "<test>"}|xmlattr|escape }}')423        assert tmpl.render() == ' foo="&lt;test&gt;"'424        tmpl = env.from_string('{% autoescape false %}{{ {"foo": "<test>"}'425                               '|xmlattr|escape }}{% endautoescape %}')426        assert tmpl.render() == ' foo=&#34;&amp;lt;test&amp;gt;&#34;'427428    def test_volatile(self):429        env = Environment(extensions=['jinja2.ext.autoescape'],430                          autoescape=True)431        tmpl = env.from_string('{% autoescape foo %}{{ {"foo": "<test>"}'432                               '|xmlattr|escape }}{% endautoescape %}')433        assert tmpl.render(foo=False) == ' foo=&#34;&amp;lt;test&amp;gt;&#34;'434        assert tmpl.render(foo=True) == ' foo="&lt;test&gt;"'435436    def test_scoping(self):437        env = Environment(extensions=['jinja2.ext.autoescape'])438        tmpl = env.from_string(439            '{% autoescape true %}{% set x = "<x>" %}{{ x }}'440            '{% endautoescape %}{{ x }}{{ "<y>" }}')441        assert tmpl.render(x=1) == '&lt;x&gt;1<y>'442443    def test_volatile_scoping(self):444        env = Environment(extensions=['jinja2.ext.autoescape'])445        tmplsource = '''446        {% autoescape val %}447            {% macro foo(x) %}448                [{{ x }}]449            {% endmacro %}450            {{ foo().__class__.__name__ }}451        {% endautoescape %}452        {{ '<testing>' }}453        '''454        tmpl = env.from_string(tmplsource)455        assert tmpl.render(val=True).split()[0] == 'Markup'456        assert tmpl.render(val=False).split()[0] == text_type.__name__457458        # looking at the source we should see <testing> there in raw459        # (and then escaped as well)460        env = Environment(extensions=['jinja2.ext.autoescape'])461        pysource = env.compile(tmplsource, raw=True)462        assert '<testing>\\n' in pysource463464        env = Environment(extensions=['jinja2.ext.autoescape'],465                          autoescape=True)466        pysource = env.compile(tmplsource, raw=True)467        assert '&lt;testing&gt;\\n' in pysource