| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import copy |
| 4 |
import pickle |
| 5 |
|
| 6 |
import pytest |
| 7 |
import jinja2 |
| 8 |
import jinja2.utils |
| 9 |
|
| 10 |
from ansible._internal._templating._jinja_common import MarkerError, Marker |
| 11 |
|
| 12 |
|
| 13 |
# NB: this module is named with a trailing underscore to work around a PyCharm/pydevd bug: |
| 14 |
# https://youtrack.jetbrains.com/issue/PY-70408/Debugger-skips-all-breakpoints-in-a-single-test-file |
| 15 |
|
| 16 |
|
| 17 |
def get_dunder_methods_to_intercept() -> list[str]: |
| 18 |
""" |
| 19 |
Return a list of dunder methods on Jinja's StrictUndefined that should be overridden by Ansible's Marker. |
| 20 |
When new methods are added in future Python/Jinja versions, they need to be added to Marker or the ignore_names list below. |
| 21 |
""" |
| 22 |
dunder_names = set(name for name in dir(jinja2.StrictUndefined) if name.startswith('__') and name.endswith('__')) |
| 23 |
|
| 24 |
strict_undefined_intercepted_method_names = set( |
| 25 |
name for name in dir(jinja2.StrictUndefined) |
| 26 |
if getattr(jinja2.StrictUndefined, name) is jinja2.StrictUndefined._fail_with_undefined_error and name != '_fail_with_undefined_error' |
| 27 |
) |
| 28 |
|
| 29 |
# Some attributes/methods are necessary for core Python interactions and must not be intercepted, thus they are excluded from this test. |
| 30 |
ignore_names = { |
| 31 |
'__class__', |
| 32 |
'__dir__', |
| 33 |
'__doc__', |
| 34 |
'__firstlineno__', |
| 35 |
'__getattr__', # tested separately since it is intercepted with a custom method |
| 36 |
'__getattribute__', |
| 37 |
'__getitem__', # tested separately since it is intercepted with a custom method |
| 38 |
'__getstate__', |
| 39 |
'__init__', |
| 40 |
'__init_subclass__', |
| 41 |
'__module__', |
| 42 |
'__new__', |
| 43 |
'__reduce__', |
| 44 |
'__reduce_ex__', |
| 45 |
'__setattr__', # tested separately since it is intercepted with a custom method |
| 46 |
'__slots__', # tested separately since it's not a method |
| 47 |
'__sizeof__', |
| 48 |
'__static_attributes__', |
| 49 |
'__subclasshook__', |
| 50 |
} |
| 51 |
|
| 52 |
# Some methods not intercepted by Jinja's StrictUndefined should be intercepted by Marker. |
| 53 |
additional_method_names = { |
| 54 |
'__aiter__', |
| 55 |
'__delattr__', |
| 56 |
'__format__', |
| 57 |
'__repr__', |
| 58 |
'__setitem__', |
| 59 |
} |
| 60 |
|
| 61 |
assert not strict_undefined_intercepted_method_names - dunder_names # ensure Jinja intercepted methods have not been overlooked |
| 62 |
assert not ignore_names & additional_method_names # ensure no overap between ignore_names and additional_method_names |
| 63 |
|
| 64 |
return sorted(dunder_names - ignore_names | additional_method_names) |
| 65 |
|
| 66 |
|
| 67 |
def test_jinja_undefined_shape(): |
| 68 |
""" |
| 69 |
Assert that the internal shape of Jinja's StrictUndefined matches Marker's expectations. |
| 70 |
If this test fails, it likely means Jinja has changed something about the internals of Undefined in a way we'll need to address. |
| 71 |
""" |
| 72 |
assert jinja2.StrictUndefined in Marker.__bases__ # ensure we're directly inheriting the base we're validating |
| 73 |
|
| 74 |
required_attrs = ( |
| 75 |
'_undefined_message', |
| 76 |
'_undefined_name', |
| 77 |
'_fail_with_undefined_error', |
| 78 |
) |
| 79 |
|
| 80 |
assert all(hasattr(jinja2.StrictUndefined, a) for a in required_attrs) |
| 81 |
|
| 82 |
assert isinstance(jinja2.StrictUndefined.__slots__, tuple) # we don't actually care what's slotted, just that the attr exists (or has been patched back on) |
| 83 |
|
| 84 |
|
| 85 |
@pytest.mark.parametrize("name", get_dunder_methods_to_intercept()) |
| 86 |
def test_marker_methods(marker: Marker, name: str) -> None: |
| 87 |
"""Verify all expected dunder methods on Marker raise a MarkerError.""" |
| 88 |
method = getattr(marker, name) |
| 89 |
|
| 90 |
with pytest.raises(MarkerError) as err: |
| 91 |
method() |
| 92 |
|
| 93 |
assert err.value.source is marker |
| 94 |
|
| 95 |
|
| 96 |
def test_getattr_attribute_error(marker: Marker) -> None: |
| 97 |
"""Verify unknown dunder attributes on Marker raise an AttributeError.""" |
| 98 |
with pytest.raises(AttributeError) as err: |
| 99 |
getattr(marker, '__does_not_exist__') |
| 100 |
|
| 101 |
assert err.value.obj is marker |
| 102 |
assert err.value.name == '__does_not_exist__' |
| 103 |
|
| 104 |
|
| 105 |
def test_getattr_propagation(marker: Marker) -> None: |
| 106 |
"""Verify unknown non-dunder attributes on Marker return self.""" |
| 107 |
assert marker.does_not_exist is marker |
| 108 |
|
| 109 |
|
| 110 |
def test_getitem_propagation(marker: Marker) -> None: |
| 111 |
"""Verify items return self.""" |
| 112 |
assert marker['does_not_exist'] is marker |
| 113 |
|
| 114 |
|
| 115 |
def test_setattr(marker: Marker) -> None: |
| 116 |
"""Verify setattr raises MarkerError.""" |
| 117 |
with pytest.raises(MarkerError) as err: |
| 118 |
marker.something = True |
| 119 |
|
| 120 |
assert err.value.source is marker |
| 121 |
|
| 122 |
|
| 123 |
def test_setitem(marker: Marker) -> None: |
| 124 |
"""Verify setitem raises MarkerError.""" |
| 125 |
with pytest.raises(MarkerError) as err: |
| 126 |
marker['something'] = True |
| 127 |
|
| 128 |
assert err.value.source is marker |
| 129 |
|
| 130 |
|
| 131 |
def test_slots(marker: Marker) -> None: |
| 132 |
"""Verify all Marker instances are slotted.""" |
| 133 |
assert isinstance(marker.__slots__, tuple) |
| 134 |
assert not hasattr(marker, '__dict__') |
| 135 |
|
| 136 |
|
| 137 |
def marker_attrs(marker: Marker) -> list[str]: |
| 138 |
"""Returns a list of internal attributes for a Marker type (using known prefixes).""" |
| 139 |
return [name for name in dir(marker) if name.startswith('_undefined_') or name.startswith('_marker_')] |
| 140 |
|
| 141 |
|
| 142 |
def test_copy(marker: Marker) -> None: |
| 143 |
"""Verify copying an Marker works.""" |
| 144 |
copied = copy.copy(marker) |
| 145 |
|
| 146 |
assert copied is not marker |
| 147 |
|
| 148 |
for attribute_name in marker_attrs(marker): |
| 149 |
assert getattr(copied, attribute_name) is getattr(marker, attribute_name), attribute_name |
| 150 |
|
| 151 |
|
| 152 |
def test_deepcopy(marker: Marker) -> None: |
| 153 |
"""Verify deep copying an Marker works.""" |
| 154 |
copied = copy.deepcopy(marker) |
| 155 |
|
| 156 |
assert copied is not marker |
| 157 |
|
| 158 |
for attribute_name in marker_attrs(marker): |
| 159 |
copied_value = getattr(copied, attribute_name) |
| 160 |
marker_value = getattr(marker, attribute_name) |
| 161 |
|
| 162 |
if attribute_name == '_undefined_exception': |
| 163 |
# The `_undefined_exception` attribute is a type, so the identity remains unchanged. |
| 164 |
assert copied_value is marker_value, attribute_name |
| 165 |
elif attribute_name == '_undefined_obj' and marker_value is jinja2.utils.missing: |
| 166 |
# The `_undefined_obj` attribute defaults to the `jinja2.utils.missing`, a singleton of `jinja2.utils.MissingType`. |
| 167 |
assert copied_value is marker_value, attribute_name |
| 168 |
elif type(marker_value) in (str, type(None)): |
| 169 |
# Values of type `str` or `None` should be equal. |
| 170 |
assert copied_value == marker_value, attribute_name |
| 171 |
else: |
| 172 |
# All other types should be actual copies. |
| 173 |
assert copied_value is not marker_value, attribute_name |
| 174 |
|
| 175 |
|
| 176 |
def test_pickle(marker: Marker) -> None: |
| 177 |
"""Verify pickling a Marker works.""" |
| 178 |
pickled = pickle.loads(pickle.dumps(marker)) |
| 179 |
|
| 180 |
assert pickled is not marker |
| 181 |
|
| 182 |
for attribute_name in marker_attrs(marker): |
| 183 |
pickled_value = getattr(pickled, attribute_name) |
| 184 |
marker_value = getattr(marker, attribute_name) |
| 185 |
|
| 186 |
if attribute_name == '_marker_captured_exception': |
| 187 |
# The `_marker_captured_exception` attribute is an `Exception` instance, which doesn't support equality comparisons, compare as a `str` instead. |
| 188 |
pickled_value = str(pickled_value) |
| 189 |
marker_value = str(marker_value) |
| 190 |
|
| 191 |
assert pickled_value == marker_value, attribute_name |