Skip to content

Commit

Permalink
fix(spy): gracefully degrade when a class's type hints can't be resol…
Browse files Browse the repository at this point in the history
…ved at runtime (#47)

Fixes #46
  • Loading branch information
mcous authored Jul 21, 2021
1 parent f59ab66 commit 81072ed
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 14 deletions.
33 changes: 19 additions & 14 deletions decoy/spy.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,19 @@ class SpyConfig(NamedTuple):
is_async: bool = False


def _get_type_hints(obj: Any) -> Dict[str, Any]:
"""Get type hints for an object, if possible.
The builtin `typing.get_type_hints` may fail at runtime,
e.g. if a type is subscriptable according to mypy but not
according to Python.
"""
try:
return get_type_hints(obj)
except Exception:
return {}


class BaseSpy:
"""Spy object base class.
Expand Down Expand Up @@ -88,23 +101,15 @@ def __getattr__(self, name: str) -> Any:

if isclass(self._spec):
try:
# NOTE: `get_type_hints` may fail at runtime,
# e.g. if a type is subscriptable according to mypy but not
# according to Python, `get_type_hints` will raise.
# Rather than fail to create a spy with an inscrutable error,
# gracefully fallback to a specification-less spy.
hints = get_type_hints(self._spec)
child_spec = getattr(
self._spec,
name,
hints.get(name),
)
child_hint = _get_type_hints(self._spec).get(name)
except Exception:
pass
child_hint = None

child_spec = getattr(self._spec, name, child_hint)

if isinstance(child_spec, property):
hints = get_type_hints(child_spec.fget)
child_spec = hints.get("return")
child_spec = _get_type_hints(child_spec.fget).get("return")

elif isclass(self._spec) and isfunction(child_spec):
# `iscoroutinefunction` does not work for `partial` on Python < 3.8
# check before we wrap it
Expand Down
10 changes: 10 additions & 0 deletions tests/test_spy.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,9 +265,13 @@ async def test_create_nested_spy_using_non_runtime_type_hints() -> None:
class _SomeClass:
_property: "None[str]"

async def _do_something_async(self) -> None:
pass

calls = []
spy = create_spy(SpyConfig(spec=_SomeClass, handle_call=lambda c: calls.append(c)))
spy._property.do_something(7, eight=8, nine=9)
await spy._do_something_async()

assert calls == [
SpyCall(
Expand All @@ -276,6 +280,12 @@ class _SomeClass:
args=(7,),
kwargs={"eight": 8, "nine": 9},
),
SpyCall(
spy_id=id(spy._do_something_async),
spy_name="_SomeClass._do_something_async",
args=(),
kwargs={},
),
]


Expand Down

0 comments on commit 81072ed

Please sign in to comment.