Skip to content

Commit adf5a8f

Browse files
committed
feat: add decoy.next preview API
1 parent 07ea0d6 commit adf5a8f

21 files changed

+2164
-228
lines changed

decoy/errors.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@ def create(cls) -> "MockNameRequiredError":
2525
return cls("Mocks without `cls` or `func` require a `name`.")
2626

2727

28+
class MockSpecInvalidError(TypeError):
29+
"""An value passed as a mock spec is not valid."""
30+
31+
2832
class MissingRehearsalError(ValueError):
2933
"""An error raised when a Decoy method is called without rehearsal(s).
3034
@@ -44,6 +48,14 @@ def create(cls) -> "MissingRehearsalError":
4448
return cls("Rehearsal not found.")
4549

4650

51+
class NotAMockError(TypeError):
52+
"""A Decoy method was called without a mock."""
53+
54+
55+
class ThenDoActionNotCallableError(TypeError):
56+
"""A value passed to `then_do` is not callable."""
57+
58+
4759
class MockNotAsyncError(TypeError):
4860
"""An error raised when an asynchronous function is used with a synchronous mock.
4961
@@ -55,6 +67,10 @@ class MockNotAsyncError(TypeError):
5567
"""
5668

5769

70+
class SignatureMismatchError(TypeError):
71+
"""Arguments did not match the signature of the mock."""
72+
73+
5874
class VerifyError(AssertionError):
5975
"""An error raised when actual calls do not match rehearsals given to `verify`.
6076
@@ -100,3 +116,12 @@ def create(
100116
result.times = times
101117

102118
return result
119+
120+
121+
class VerifyOrderError(VerifyError):
122+
"""An error raised when the order of calls do not match expectations.
123+
124+
See [spying with verify][] for more details.
125+
126+
[spying with verify]: usage/verify.md
127+
"""

decoy/next/__init__.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
"""Decoy mocking library.
2+
3+
Use Decoy to create stubs and spies
4+
to isolate your code under test.
5+
"""
6+
7+
from ._internal.decoy import Decoy
8+
from ._internal.mock import AsyncMock, Mock
9+
from ._internal.verify import Verify
10+
from ._internal.when import Stub, When
11+
12+
__all__ = [
13+
"AsyncMock",
14+
"Decoy",
15+
"Mock",
16+
"Stub",
17+
"Verify",
18+
"When",
19+
]

decoy/next/_internal/__init__.py

Whitespace-only changes.

decoy/next/_internal/decoy.py

Lines changed: 233 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,233 @@
1+
import collections.abc
2+
import contextlib
3+
from typing import Any, Callable, Literal, TypeVar, overload
4+
5+
from .errors import createNotAMockError, createVerifyOrderError
6+
from .inspect import (
7+
ensure_spec,
8+
ensure_spec_name,
9+
get_spec_module_name,
10+
is_async_callable,
11+
)
12+
from .mock import AsyncMock, Mock, create_mock, ensure_mock
13+
from .state import DecoyState
14+
from .values import MatchOptions
15+
from .verify import Verify
16+
from .when import When
17+
18+
ClassT = TypeVar("ClassT")
19+
FuncT = TypeVar("FuncT", bound=Callable[..., Any])
20+
SpecT = TypeVar("SpecT")
21+
22+
23+
class Decoy:
24+
"""Decoy mock factory and state container.
25+
26+
Use the `create` context manager to create a new Decoy instance
27+
and reset it after your test.
28+
If you use the [`decoy` pytest fixture][decoy.pytest_plugin.decoy],
29+
this is done automatically.
30+
31+
See the [setup guide][] for more details.
32+
33+
!!! example
34+
```python
35+
with Decoy.create() as decoy:
36+
...
37+
```
38+
39+
[setup guide]: ../index.md#setup
40+
"""
41+
42+
@classmethod
43+
@contextlib.contextmanager
44+
def create(cls) -> collections.abc.Iterator["Decoy"]:
45+
"""Create a Decoy instance for testing that will reset after usage.
46+
47+
This method is used by the [pytest plugin][decoy.pytest_plugin].
48+
"""
49+
decoy = cls()
50+
try:
51+
yield decoy
52+
finally:
53+
decoy.reset()
54+
55+
def __init__(self) -> None:
56+
self._state = DecoyState()
57+
58+
@overload
59+
def mock(self, *, cls: Callable[..., ClassT]) -> ClassT: ...
60+
61+
@overload
62+
def mock(self, *, func: FuncT) -> FuncT: ...
63+
64+
@overload
65+
def mock(self, *, name: str, is_async: Literal[True]) -> AsyncMock: ...
66+
67+
@overload
68+
def mock(self, *, name: str, is_async: bool = False) -> Mock: ...
69+
70+
def mock(
71+
self,
72+
*,
73+
cls: Callable[..., ClassT] | None = None,
74+
func: FuncT | None = None,
75+
name: str | None = None,
76+
is_async: bool = False,
77+
) -> ClassT | FuncT | AsyncMock | Mock:
78+
"""Create a mock. See the [mock creation guide][] for more details.
79+
80+
[mock creation guide]: ./create.md
81+
82+
Arguments:
83+
cls: A class definition that the mock should imitate.
84+
func: A function definition the mock should imitate.
85+
name: A name to use for the mock. If you do not use
86+
`cls` or `func`, you must add a `name`.
87+
is_async: Force the returned mock to be asynchronous. This argument
88+
only applies if you don't use `cls` nor `func`.
89+
90+
Returns:
91+
A mock typecast as the object it's imitating, if any.
92+
93+
!!! example
94+
```python
95+
def test_get_something(decoy: Decoy):
96+
db = decoy.mock(cls=Database)
97+
# ...
98+
```
99+
"""
100+
spec = ensure_spec(cls, func)
101+
name = ensure_spec_name(spec, name)
102+
parent_name = get_spec_module_name(spec)
103+
is_async = is_async_callable(spec, is_async)
104+
105+
return create_mock(
106+
spec=spec,
107+
name=name,
108+
parent_name=parent_name,
109+
is_async=is_async,
110+
state=self._state,
111+
)
112+
113+
def when(
114+
self,
115+
mock: SpecT,
116+
*,
117+
times: int | None = None,
118+
ignore_extra_args: bool = False,
119+
is_entered: bool | None = None,
120+
) -> When[SpecT, SpecT]:
121+
"""Configure a mock as a stub.
122+
123+
See [stubbing usage guide](when.md) for more details.
124+
125+
Arguments:
126+
mock: The mock to configure.
127+
times: Limit the number of times the behavior is triggered.
128+
ignore_extra_args: Only partially match arguments.
129+
is_entered: Limit the behavior to when the mock is entered using `with`.
130+
131+
Returns:
132+
A stub interface to configure matching arguments.
133+
134+
!!! example
135+
```python
136+
db = decoy.mock(cls=Database)
137+
decoy.when(db.exists).called_with("some-id").then_return(True)
138+
```
139+
"""
140+
mock_info = ensure_mock(mock)
141+
match_options = MatchOptions(times, ignore_extra_args, is_entered)
142+
143+
if not mock_info:
144+
mock_info = self._state.peek_last_attribute_mock(mock)
145+
146+
if not mock_info:
147+
raise createNotAMockError("when", mock)
148+
149+
return When(self._state, mock_info, match_options)
150+
151+
def verify(
152+
self,
153+
mock: SpecT,
154+
*,
155+
times: int | None = None,
156+
ignore_extra_args: bool = False,
157+
is_entered: bool | None = None,
158+
) -> Verify[SpecT]:
159+
"""Verify a mock was called in a particular manner.
160+
161+
See [verification usage guide](verify.md) for more details.
162+
163+
Arguments:
164+
mock: The mock to verify.
165+
times: Limit the number of times the call is expected.
166+
ignore_extra_args: Only partially match arguments.
167+
is_entered: Verify call happens when the mock is entered using `with`.
168+
169+
Raises:
170+
VerifyError: The verification was not satisfied.
171+
172+
!!! example
173+
```python
174+
def test_create_something(decoy: Decoy):
175+
gen_id = decoy.mock(func=generate_unique_id)
176+
177+
# ...
178+
179+
decoy.verify(gen_id).called_with("model-prefix_")
180+
```
181+
"""
182+
mock_info = ensure_mock(mock)
183+
match_options = MatchOptions(times, ignore_extra_args, is_entered)
184+
185+
if not mock_info:
186+
mock_info = self._state.peek_last_attribute_mock(mock)
187+
188+
if not mock_info:
189+
raise createNotAMockError("verify", mock)
190+
191+
return Verify(
192+
self._state,
193+
mock_info,
194+
match_options,
195+
)
196+
197+
@contextlib.contextmanager
198+
def verify_order(self) -> collections.abc.Iterator[None]:
199+
"""Verify a sequence of interactions.
200+
201+
All verifications in the sequence must be individually satisfied
202+
before the sequence is checked.
203+
204+
See [verification usage guide](verify.md) for more details.
205+
206+
Raises:
207+
VerifyOrderError: The sequence was not satisfied.
208+
209+
!!! example
210+
```python
211+
def test_greet(decoy: Decoy):
212+
verify_greeting = decoy.mock(name="verify_greeting")
213+
greet = decoy.mock(name="greet")
214+
215+
# ...
216+
217+
with decoy.verify_order():
218+
decoy.verify(verify_greeting).called_with("hello world")
219+
decoy.verify(greet).called_with("hello world")
220+
```
221+
"""
222+
with self._state.verify_order() as verify_order_result:
223+
yield
224+
225+
if not verify_order_result.is_success:
226+
raise createVerifyOrderError(
227+
verify_order_result.verifications,
228+
verify_order_result.all_events,
229+
)
230+
231+
def reset(self) -> None:
232+
"""Reset the decoy instance."""
233+
self._state.reset()

0 commit comments

Comments
 (0)