Skip to content

Commit

Permalink
test for echo default behavior on getattr
Browse files Browse the repository at this point in the history
  • Loading branch information
vreuter committed May 14, 2019
1 parent a416802 commit bafbea5
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
10 changes: 4 additions & 6 deletions attmap/attmap_echo.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,12 @@ def __getattr__(self, item, default=None):
return super(self.__class__, self).__getattr__(item, default)
except (AttributeError, TypeError):
# If not, triage and cope accordingly.
if item.startswith("_OrderedDict") or (item.startswith("__") and item.endswith("__")):
# Accommodate security-through-obscurity approach used by some libraries.
if item.startswith("_OrderedDict") or \
(item.startswith("__") and item.endswith("__")):
# Accommodate security-through-obscurity approach of some libs.
error_reason = "Protected-looking attribute: {}".format(item)
raise AttributeError(error_reason)
if default is not None:
# For compatibility with ordinary getattr() call, allow default value.
return default
return item
return default if default is not None else item

@property
def _lower_type_bound(self):
Expand Down
11 changes: 11 additions & 0 deletions tests/test_echo.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,14 @@ def test_echo_is_type_dependent_and_access_dependent(
assert key not in m
with ExpectContext(expected, getter) as ctx:
ctx(m, key)


@pytest.mark.parametrize(
["data", "name", "defval"],
[({}, "b", "arbval"), ({"a": 1}, "c", "random")])
def test_echo_respects_default(data, name, defval):
assert name != defval # Pretest so that assertions actually have meaning.
m = AttMapEcho(data)
assert name == getattr(m, name)
assert name == getattr(m, name, defval)
assert defval == m.__getattr__(name, defval)

0 comments on commit bafbea5

Please sign in to comment.