Skip to content
Myr

creating a NativeTemplate creates a NativeEnvironment

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent 9a7dd7b · Browse files · 4 files+131 added−113 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+131 added−113 removed

  • tests:+101 added−97 removed
  • other:+30 added−16 removed

4 files+131 added−113 removed

modified:jinja2/environment.py+18 added-11 removed
39 unmodified lines
40# imported on the first exception in the exception handler.41_make_traceback = None424344def get_spontaneous_environment(*args):45 """Return a new spontaneous environment. A spontaneous environment is an46 unnamed and unaccessible (in theory) environment that is used for47 templates generated from a string and not from the file system.44def get_spontaneous_environment(cls, *args):45 """Return a new spontaneous environment. A spontaneous environment46 is used for templates created directly rather than through an47 existing environment.4849 :param cls: Environment class to create.50 :param args: Positional arguments passed to environment.51 """52 key = (cls, args)5354 try:50 env = _spontaneous_environments.get(args)51 except TypeError:52 return Environment(*args)53 if env is not None:55 return _spontaneous_environments[key]56 except KeyError:57 _spontaneous_environments[key] = env = cls(*args)58 env.shared = True59 return env55 _spontaneous_environments[args] = env = Environment(*args)56 env.shared = True57 return env606162def create_cache(size):63 """Return the cache class for the given size."""
855 unmodified lines
919 ...920 StopIteration921 """922923 #: Type of environment to create when creating a template directly924 #: rather than through an existing environment.925 environment_class = Environment926927 def __new__(cls, source,928 block_start_string=BLOCK_START_STRING,929 block_end_string=BLOCK_END_STRING,930 variable_start_string=VARIABLE_START_STRING,
12 unmodified lines
943 finalize=None,944 autoescape=False,945 enable_async=False):946 env = get_spontaneous_environment(947 cls.environment_class,948 block_start_string, block_end_string, variable_start_string,949 variable_end_string, comment_start_string, comment_end_string,950 line_statement_prefix, line_comment_prefix, trim_blocks,951 lstrip_blocks, newline_sequence, keep_trailing_newline,
334 unmodified lines
modified:jinja2/nativetypes.py+9 added-5 removed
210 unmodified lines
211 if outdent_later:212 self.outdent()213214215class NativeEnvironment(Environment):216 """An environment that renders templates to native Python types."""217218 code_generator_class = NativeCodeGenerator219220221class NativeTemplate(Template):222 environment_class = NativeEnvironment223224 def render(self, *args, **kwargs):225 """Render the template to produce a native Python type. If the226 result is a single node, its value is returned. Otherwise, the227 nodes are concatenated as strings. If the result can be parsed
10 unmodified lines
238239 return self.environment.handle_exception(exc_info, True)240241234class NativeEnvironment(Environment):235 """An environment that renders templates to native Python types."""236237 code_generator_class = NativeCodeGenerator238 template_class = NativeTemplate242NativeEnvironment.template_class = NativeTemplate
modified:tests/test_nativetypes.py+101 added-97 removed
1 unmodified line
23from jinja2._compat import text_type4from jinja2.exceptions import UndefinedError5from jinja2.nativetypes import NativeEnvironment6from jinja2.nativetypes import NativeTemplate7from jinja2.runtime import Undefined8910@pytest.fixture11def env():12 return NativeEnvironment()131414class TestNativeEnvironment(object):15 def test_is_defined_native_return(self, env):16 t = env.from_string('{{ missing is defined }}')17 assert not t.render()15def test_is_defined_native_return(env):16 t = env.from_string('{{ missing is defined }}')17 assert not t.render()1819 def test_undefined_native_return(self, env):20 t = env.from_string('{{ missing }}')21 assert isinstance(t.render(), Undefined)1923 def test_adding_undefined_native_return(self, env):24 t = env.from_string('{{ 3 + missing }}')20def test_undefined_native_return(env):21 t = env.from_string('{{ missing }}')22 assert isinstance(t.render(), Undefined)2326 with pytest.raises(UndefinedError):27 t.render()2429 def test_cast_int(self, env):30 t = env.from_string("{{ anumber|int }}")31 result = t.render(anumber='3')32 assert isinstance(result, int)33 assert result == 325def test_adding_undefined_native_return(env):26 t = env.from_string('{{ 3 + missing }}')2735 def test_list_add(self, env):36 t = env.from_string("{{ listone + listtwo }}")37 result = t.render(listone=['a', 'b'], listtwo=['c', 'd'])38 assert isinstance(result, list)39 assert result == ['a', 'b', 'c', 'd']28 with pytest.raises(UndefinedError):29 t.render()3041 def test_multi_expression_add(self, env):42 t = env.from_string("{{ listone }} + {{ listtwo }}")43 result = t.render(listone=['a', 'b'], listtwo=['c', 'd'])44 assert not isinstance(result, list)45 assert result == "['a', 'b'] + ['c', 'd']"3147 def test_loops(self, env):48 t = env.from_string("{% for x in listone %}{{ x }}{% endfor %}")49 result = t.render(listone=['a', 'b', 'c', 'd'])50 assert isinstance(result, text_type)51 assert result == 'abcd'32def test_cast_int(env):33 t = env.from_string("{{ value|int }}")34 result = t.render(value='3')35 assert isinstance(result, int)36 assert result == 33753 def test_loops_with_ints(self, env):54 t = env.from_string("{% for x in listone %}{{ x }}{% endfor %}")55 result = t.render(listone=[1, 2, 3, 4])56 assert isinstance(result, int)57 assert result == 12343859 def test_loop_look_alike(self, env):60 t = env.from_string("{% for x in listone %}{{ x }}{% endfor %}")61 result = t.render(listone=[1])62 assert isinstance(result, int)63 assert result == 139def test_list_add(env):40 t = env.from_string("{{ a + b }}")41 result = t.render(a=['a', 'b'], b=['c', 'd'])42 assert isinstance(result, list)43 assert result == ['a', 'b', 'c', 'd']4465 def test_booleans(self, env):66 t = env.from_string("{{ boolval }}")67 result = t.render(boolval=True)68 assert isinstance(result, bool)69 assert result is True4571 t = env.from_string("{{ boolval }}")72 result = t.render(boolval=False)73 assert isinstance(result, bool)74 assert result is False46def test_multi_expression_add(env):47 t = env.from_string("{{ a }} + {{ b }}")48 result = t.render(a=['a', 'b'], b=['c', 'd'])49 assert not isinstance(result, list)50 assert result == "['a', 'b'] + ['c', 'd']"5176 t = env.from_string("{{ 1 == 1 }}")77 result = t.render()78 assert isinstance(result, bool)79 assert result is True5281 t = env.from_string("{{ 2 + 2 == 5 }}")82 result = t.render()83 assert isinstance(result, bool)84 assert result is False53def test_loops(env):54 t = env.from_string("{% for x in value %}{{ x }}{% endfor %}")55 result = t.render(value=['a', 'b', 'c', 'd'])56 assert isinstance(result, text_type)57 assert result == 'abcd'5886 t = env.from_string("{{ None == None }}")87 result = t.render()88 assert isinstance(result, bool)89 assert result is True5960def test_loops_with_ints(env):91 t = env.from_string("{{ '' == None }}")92 result = t.render()93 assert isinstance(result, bool)94 assert result is False61 t = env.from_string("{% for x in value %}{{ x }}{% endfor %}")62 result = t.render(value=[1, 2, 3, 4])63 assert isinstance(result, int)64 assert result == 12346596 def test_variable_dunder(self, env):97 t = env.from_string("{{ x.__class__ }}")98 result = t.render(x=True)99 assert isinstance(result, type)66101 def test_constant_dunder(self, env):102 t = env.from_string("{{ true.__class__ }}")103 result = t.render()104 assert isinstance(result, type)67def test_loop_look_alike(env):68 t = env.from_string("{% for x in value %}{{ x }}{% endfor %}")69 result = t.render(value=[1])70 assert isinstance(result, int)71 assert result == 172106 def test_constant_dunder_to_string(self, env):107 t = env.from_string("{{ true.__class__|string }}")108 result = t.render()109 assert not isinstance(result, type)110 assert result in ["<type 'bool'>", "<class 'bool'>"]7374@pytest.mark.parametrize(("source", "expect"), (75 ("{{ value }}", True),76 ("{{ value }}", False),77 ("{{ 1 == 1 }}", True),78 ("{{ 2 + 2 == 5 }}", False),79 ("{{ None is none }}", True),80 ("{{ '' == None }}", False),81))112 def test_string_literal_var(self, env):113 t = env.from_string("[{{ 'all' }}]")114 result = t.render()115 assert isinstance(result, text_type)116 assert result == "[all]"82def test_booleans(env, source, expect):83 t = env.from_string(source)84 result = t.render(value=expect)85 assert isinstance(result, bool)86 assert result is expect87118 def test_string_top_level(self, env):119 t = env.from_string("'Jinja'")120 result = t.render()121 assert result == 'Jinja'88123 def test_tuple_of_variable_strings(self, env):124 t = env.from_string("'{{ a }}', 'data', '{{ b }}', b'{{ c }}'")125 result = t.render(a=1, b=2, c="bytes")126 assert isinstance(result, tuple)127 assert result == ("1", "data", "2", b"bytes")89def test_variable_dunder(env):90 t = env.from_string("{{ x.__class__ }}")91 result = t.render(x=True)92 assert isinstance(result, type)939495def test_constant_dunder(env):96 t = env.from_string("{{ true.__class__ }}")97 result = t.render()98 assert isinstance(result, type)99100101def test_constant_dunder_to_string(env):102 t = env.from_string("{{ true.__class__|string }}")103 result = t.render()104 assert not isinstance(result, type)105 assert result in {"<type 'bool'>", "<class 'bool'>"}106107108def test_string_literal_var(env):109 t = env.from_string("[{{ 'all' }}]")110 result = t.render()111 assert isinstance(result, text_type)112 assert result == "[all]"113114115def test_string_top_level(env):116 t = env.from_string("'Jinja'")117 result = t.render()118 assert result == 'Jinja'119120121def test_tuple_of_variable_strings(env):122 t = env.from_string("'{{ a }}', 'data', '{{ b }}', b'{{ c }}'")123 result = t.render(a=1, b=2, c="bytes")124 assert isinstance(result, tuple)125 assert result == ("1", "data", "2", b"bytes")126127129 def test_concat_strings_with_quotes(self, env):130 t = env.from_string("--host='{{ host }}' --user \"{{ user }}\"")131 result = t.render(host="localhost", user="Jinja")132 assert result == "--host='localhost' --user \"Jinja\""128def test_concat_strings_with_quotes(env):129 t = env.from_string("--host='{{ host }}' --user \"{{ user }}\"")130 result = t.render(host="localhost", user="Jinja")131 assert result == "--host='localhost' --user \"Jinja\""132133134def test_spontaneous_env():135 t = NativeTemplate("{{ true }}")136 assert isinstance(t.environment, NativeEnvironment)
modified:CHANGES.rst+3 added
53 unmodified lines
54 :issue:`870`55- :class:`~nativetypes.NativeTemplate` correctly handles quotes56 between expressions. ``"'{{ a }}', '{{ b }}'"`` renders as the tuple57 ``('1', '2')`` rather than the string ``'1, 2'``. :issue:`1020`58- Creating a :class:`~nativetypes.NativeTemplate` directly creates a59 :class:`~nativetypes.NativeEnvironment` instead of a default60 :class:`Environment`. :issue:`1091`61- After calling ``LRUCache.copy()``, the copy's queue methods point to62 the correct queue. :issue:`843`6364
631 unmodified lines