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
Provenance
- Commit
32027ea- Tree
d0ace44- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
9a7dd7b
4 files changed+131 added−113 removed
modified:jinja2/environment.py+18 added-11 removed
39 unmodified lines40 # imported on the first exception in the exception handler.41 _make_traceback = None42 43 44-def 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.44+def 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.48+49+ :param cls: Environment class to create.50+ :param args: Positional arguments passed to environment.51 """52+ key = (cls, args)53+54 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 env60 61 62 def create_cache(size):63 """Return the cache class for the given size."""855 unmodified lines919 ...920 StopIteration921 """922 923+ #: Type of environment to create when creating a template directly924+ #: rather than through an existing environment.925+ environment_class = Environment926+927 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 lines943 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 linesmodified:jinja2/nativetypes.py+9 added-5 removed
210 unmodified lines211 if outdent_later:212 self.outdent()213 214 215+class NativeEnvironment(Environment):216+ """An environment that renders templates to native Python types."""217+218+ code_generator_class = NativeCodeGenerator219+220+221 class NativeTemplate(Template):222+ environment_class = NativeEnvironment223+224 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 parsed10 unmodified lines238 239 return self.environment.handle_exception(exc_info, True)240 241 234-class NativeEnvironment(Environment):235- """An environment that renders templates to native Python types."""236-237- code_generator_class = NativeCodeGenerator238- template_class = NativeTemplate242+NativeEnvironment.template_class = NativeTemplatemodified:tests/test_nativetypes.py+101 added-97 removed
1 unmodified line2 3 from jinja2._compat import text_type4 from jinja2.exceptions import UndefinedError5 from jinja2.nativetypes import NativeEnvironment6+from jinja2.nativetypes import NativeTemplate7 from jinja2.runtime import Undefined8 9 10 @pytest.fixture11 def env():12 return NativeEnvironment()13 14 14-class TestNativeEnvironment(object):15- def test_is_defined_native_return(self, env):16- t = env.from_string('{{ missing is defined }}')17- assert not t.render()15+def test_is_defined_native_return(env):16+ t = env.from_string('{{ missing is defined }}')17+ assert not t.render()18 19- def test_undefined_native_return(self, env):20- t = env.from_string('{{ missing }}')21- assert isinstance(t.render(), Undefined)19 23- def test_adding_undefined_native_return(self, env):24- t = env.from_string('{{ 3 + missing }}')20+def test_undefined_native_return(env):21+ t = env.from_string('{{ missing }}')22+ assert isinstance(t.render(), Undefined)23 26- with pytest.raises(UndefinedError):27- t.render()24 29- 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 == 325+def test_adding_undefined_native_return(env):26+ t = env.from_string('{{ 3 + missing }}')27 35- 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()30 41- 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']"31 47- 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'32+def 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 == 337 53- 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 == 123438 59- 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 == 139+def 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']44 65- 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 True45 71- t = env.from_string("{{ boolval }}")72- result = t.render(boolval=False)73- assert isinstance(result, bool)74- assert result is False46+def 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']"51 76- t = env.from_string("{{ 1 == 1 }}")77- result = t.render()78- assert isinstance(result, bool)79- assert result is True52 81- t = env.from_string("{{ 2 + 2 == 5 }}")82- result = t.render()83- assert isinstance(result, bool)84- assert result is False53+def 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'58 86- t = env.from_string("{{ None == None }}")87- result = t.render()88- assert isinstance(result, bool)89- assert result is True59 60+def 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 == 123465 96- def test_variable_dunder(self, env):97- t = env.from_string("{{ x.__class__ }}")98- result = t.render(x=True)99- assert isinstance(result, type)66 101- def test_constant_dunder(self, env):102- t = env.from_string("{{ true.__class__ }}")103- result = t.render()104- assert isinstance(result, type)67+def 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 == 172 106- 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'>"]73 74+@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]"82+def 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 expect87 118- def test_string_top_level(self, env):119- t = env.from_string("'Jinja'")120- result = t.render()121- assert result == 'Jinja'88 123- 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")89+def test_variable_dunder(env):90+ t = env.from_string("{{ x.__class__ }}")91+ result = t.render(x=True)92+ assert isinstance(result, type)93 94+95+def test_constant_dunder(env):96+ t = env.from_string("{{ true.__class__ }}")97+ result = t.render()98+ assert isinstance(result, type)99+100+101+def 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'>"}106+107+108+def 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]"113+114+115+def test_string_top_level(env):116+ t = env.from_string("'Jinja'")117+ result = t.render()118+ assert result == 'Jinja'119+120+121+def 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")126+127+129- 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\""128+def 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\""132+133+134+def test_spontaneous_env():135+ t = NativeTemplate("{{ true }}")136+ assert isinstance(t.environment, NativeEnvironment)modified:CHANGES.rst+3 added
53 unmodified lines54 :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`63 64 631 unmodified lines