Skip to content

Commit d16ee12

Browse files
authored
fix: Add support for pytest-mock spy method fixing the SignatureAdapter (#392)
1 parent b936236 commit d16ee12

6 files changed

Lines changed: 64 additions & 1 deletion

File tree

docs/releases/2.1.1.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# StateMachine 2.1.1
2+
3+
*Not released yet*
4+
5+
## Bugfixes in 2.1.1
6+
7+
- Fixes [#391](https://github.com/fgmacedo/python-statemachine/issues/391) adding support to
8+
[pytest-mock](https://pytest-mock.readthedocs.io/en/latest/index.html) `spy` method.

docs/releases/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ Below are release notes through StateMachine and its patch releases.
1515
```{toctree}
1616
:maxdepth: 1
1717
18+
2.1.1
1819
2.1.0
1920
2.0.0
2021

poetry.lock

Lines changed: 19 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ pre-commit = "^2.21.0"
4545
mypy = "^0.991"
4646
black = "^22.12.0"
4747
pdbpp = "^0.10.3"
48+
pytest-mock = "^3.10.0"
4849

4950
[tool.poetry.group.docs.dependencies]
5051
Sphinx = "4.5.0"

statemachine/signature.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,16 @@ def __call__(self, *args: Any, **kwargs: Any) -> Any:
2525
ba = self.bind_expected(*args, **kwargs)
2626
return self.method(*ba.args, **ba.kwargs)
2727

28+
@classmethod
29+
def from_callable(cls, method):
30+
if hasattr(method, "__signature__"):
31+
sig = method.__signature__
32+
return SignatureAdapter(
33+
sig.parameters.values(),
34+
return_annotation=sig.return_annotation,
35+
)
36+
return super().from_callable(method)
37+
2838
def bind_expected(self, *args: Any, **kwargs: Any) -> BoundArguments: # noqa: C901
2939
"""Get a BoundArguments object, that maps the passed `args`
3040
and `kwargs` to the function's signature. It avoids to raise `TypeError`

tests/test_mock_compatibility.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from statemachine import State
2+
from statemachine import StateMachine
3+
4+
5+
def test_minimal(mocker):
6+
class Observer:
7+
def on_enter_state(self, event, model, source, target, state):
8+
...
9+
10+
obs = Observer()
11+
on_enter_state = mocker.spy(obs, "on_enter_state")
12+
13+
class Machine(StateMachine):
14+
a = State("Init", initial=True)
15+
b = State("Fin")
16+
17+
cycle = a.to(b) | b.to(a)
18+
19+
state = Machine().add_observer(obs)
20+
assert state.a.is_active
21+
22+
state.cycle()
23+
24+
assert state.b.is_active
25+
on_enter_state.assert_called_once()

0 commit comments

Comments
 (0)