preserve `__slots__` on Undefined classes
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Matt Davis · committed by David Lord · parent 39d9fff · Browse files · 4 files·+69 added−21 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+69 added−21 removed
- tests:+50 added−8 removed
- other:+19 added−13 removed
Provenance
- Commit
d4fb0e8- Tree
ee58c9e- Author
Matt Davis <nitzmahone@redhat.com>- Committer
David Lord <davidism@gmail.com>- Parent
39d9fff
4 files changed+69 added−21 removed
modified:src/jinja2/runtime.py+17 added-13 removed
858 unmodified lines859 raise self._undefined_exception(self._undefined_message)860 861 @internalcode862 def __getattr__(self, name: str) -> t.Any:863- if name[:2] == "__":863+ # Raise AttributeError on requests for names that appear to be unimplemented864+ # dunder methods to keep Python's internal protocol probing behaviors working865+ # properly in cases where another exception type could cause unexpected or866+ # difficult-to-diagnose failures.867+ if name[:2] == "__" and name[-2:] == "__":868 raise AttributeError(name)869 870 return self._fail_with_undefined_error()871 115 unmodified lines987 988 def __html__(self) -> str:989 return str(self)990 987- def __getattr__(self, _: str) -> "ChainableUndefined":991+ def __getattr__(self, name: str) -> "ChainableUndefined":992+ # Raise AttributeError on requests for names that appear to be unimplemented993+ # dunder methods to avoid confusing Python with truthy non-method objects that994+ # do not implement the protocol being probed for. e.g., copy.copy(Undefined())995+ # fails spectacularly if getattr(Undefined(), '__setstate__') returns an996+ # Undefined object instead of raising AttributeError to signal that it does not997+ # support that style of object initialization.998+ if name[:2] == "__" and name[-2:] == "__":999+ raise AttributeError(name)1000+1001 return self1002 990- __getitem__ = __getattr__ # type: ignore1003+ def __getitem__(self, _name: str) -> "ChainableUndefined": # type: ignore[override]1004+ return self1005 1006 1007 class DebugUndefined(Undefined):1008 """An undefined that returns the debug info when printed.50 unmodified lines1059 __slots__ = ()1060 __iter__ = __str__ = __len__ = Undefined._fail_with_undefined_error1061 __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error1062 __contains__ = Undefined._fail_with_undefined_error1049-1050-1051-# Remove slots attributes, after the metaclass is applied they are1052-# unneeded and contain wrong data for subclasses.1053-del (1054- Undefined.__slots__,1055- ChainableUndefined.__slots__,1056- DebugUndefined.__slots__,1057- StrictUndefined.__slots__,1058-)modified:tests/test_api.py-8 removed
321 unmodified lines322 und2 = Undefined(name="y")323 assert und1 == und2324 assert und1 != 42325 assert hash(und1) == hash(und2) == hash(Undefined())326- with pytest.raises(AttributeError):327- getattr(Undefined, "__slots__") # noqa: B009326 327 def test_chainable_undefined(self):328 env = Environment(undefined=ChainableUndefined)329 # The following tests are copied from test_default_undefined2 unmodified lines332 assert env.from_string("{{ missing is not defined }}").render() == "True"333 assert env.from_string("{{ foo.missing }}").render(foo=42) == ""334 assert env.from_string("{{ not missing }}").render() == "True"335 pytest.raises(UndefinedError, env.from_string("{{ missing - 1}}").render)338- with pytest.raises(AttributeError):339- getattr(ChainableUndefined, "__slots__") # noqa: B009336 337 # The following tests ensure subclass functionality works as expected338 assert env.from_string('{{ missing.bar["baz"] }}').render() == ""339 assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() == "foo"23 unmodified lines363 assert (364 str(DebugUndefined(hint=undefined_hint))365 == f"{{{{ undefined value printed: {undefined_hint} }}}}"366 )371- with pytest.raises(AttributeError):372- getattr(DebugUndefined, "__slots__") # noqa: B009367 368 def test_strict_undefined(self):369 env = Environment(undefined=StrictUndefined)370 pytest.raises(UndefinedError, env.from_string("{{ missing }}").render)8 unmodified lines379 assert (380 env.from_string('{{ missing|default("default", true) }}').render()381 == "default"382 )389- with pytest.raises(AttributeError):390- getattr(StrictUndefined, "__slots__") # noqa: B009383 assert env.from_string('{{ "foo" if false }}').render() == ""384 385 def test_indexing_gives_undefined(self):386 t = Template("{{ var[42].foo }}")41 unmodified linesmodified:tests/test_runtime.py+50 added
1+import copy2 import itertools3+import pickle4 5+import pytest6+7+from jinja2 import ChainableUndefined8+from jinja2 import DebugUndefined9+from jinja2 import StrictUndefined10 from jinja2 import Template11+from jinja2 import TemplateRuntimeError12+from jinja2 import Undefined13 from jinja2.runtime import LoopContext14 15 TEST_IDX_TEMPLATE_STR_1 = (16 "[{% for i in lst|reverse %}(len={{ loop.length }},"64 unmodified lines81 t = Template("{{ calc() }}")82 out = t.render(calc=Calc())83 # Would be "1" if context argument was passed.84 assert out == "0"85+86+87+_undefined_types = (Undefined, ChainableUndefined, DebugUndefined, StrictUndefined)88+89+90+@pytest.mark.parametrize("undefined_type", _undefined_types)91+def test_undefined_copy(undefined_type):92+ undef = undefined_type("a hint", ["foo"], "a name", TemplateRuntimeError)93+ copied = copy.copy(undef)94+95+ assert copied is not undef96+ assert copied._undefined_hint is undef._undefined_hint97+ assert copied._undefined_obj is undef._undefined_obj98+ assert copied._undefined_name is undef._undefined_name99+ assert copied._undefined_exception is undef._undefined_exception100+101+102+@pytest.mark.parametrize("undefined_type", _undefined_types)103+def test_undefined_deepcopy(undefined_type):104+ undef = undefined_type("a hint", ["foo"], "a name", TemplateRuntimeError)105+ copied = copy.deepcopy(undef)106+107+ assert copied._undefined_hint is undef._undefined_hint108+ assert copied._undefined_obj is not undef._undefined_obj109+ assert copied._undefined_obj == undef._undefined_obj110+ assert copied._undefined_name is undef._undefined_name111+ assert copied._undefined_exception is undef._undefined_exception112+113+114+@pytest.mark.parametrize("undefined_type", _undefined_types)115+def test_undefined_pickle(undefined_type):116+ undef = undefined_type("a hint", ["foo"], "a name", TemplateRuntimeError)117+ copied = pickle.loads(pickle.dumps(undef))118+119+ assert copied._undefined_hint is not undef._undefined_hint120+ assert copied._undefined_hint == undef._undefined_hint121+ assert copied._undefined_obj is not undef._undefined_obj122+ assert copied._undefined_obj == undef._undefined_obj123+ assert copied._undefined_name is not undef._undefined_name124+ assert copied._undefined_name == undef._undefined_name125+ assert copied._undefined_exception is undef._undefined_exceptionmodified:CHANGES.rst+2 added
20 unmodified lines21 - ``|int`` filter handles ``OverflowError`` from scientific notation.22 :issue:`1921`23 - Make compiling deterministic for tuple unpacking in a ``{% set ... %}``24 call. :issue:`2021`25+- Fix dunder protocol (`copy`/`pickle`/etc) interaction with ``Undefined``26+ objects. :issue:`2025`27 28 29 Version 3.1.430 -------------994 unmodified lines