Skip to content

Commit ac7756f

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

21 files changed

+2136
-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: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
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+
raise createNotAMockError("when", mock)
145+
146+
return When(self._state, mock_info, match_options)
147+
148+
def verify(
149+
self,
150+
mock: SpecT,
151+
*,
152+
times: int | None = None,
153+
ignore_extra_args: bool = False,
154+
is_entered: bool | None = None,
155+
) -> Verify[SpecT]:
156+
"""Verify a mock was called in a particular manner.
157+
158+
See [verification usage guide](verify.md) for more details.
159+
160+
Arguments:
161+
mock: The mock to verify.
162+
times: Limit the number of times the call is expected.
163+
ignore_extra_args: Only partially match arguments.
164+
is_entered: Verify call happens when the mock is entered using `with`.
165+
166+
Raises:
167+
VerifyError: The verification was not satisfied.
168+
169+
!!! example
170+
```python
171+
def test_create_something(decoy: Decoy):
172+
gen_id = decoy.mock(func=generate_unique_id)
173+
174+
# ...
175+
176+
decoy.verify(gen_id).called_with("model-prefix_")
177+
```
178+
"""
179+
mock_info = ensure_mock(mock)
180+
match_options = MatchOptions(times, ignore_extra_args, is_entered)
181+
182+
if not mock_info:
183+
mock_info = self._state.peek_last_attribute_mock(mock)
184+
185+
if not mock_info:
186+
raise createNotAMockError("verify", mock)
187+
188+
return Verify(
189+
self._state,
190+
mock_info,
191+
match_options,
192+
)
193+
194+
@contextlib.contextmanager
195+
def verify_order(self) -> collections.abc.Iterator[None]:
196+
"""Verify a sequence of interactions.
197+
198+
All verifications in the sequence must be individually satisfied
199+
before the sequence is checked.
200+
201+
See [verification usage guide](verify.md) for more details.
202+
203+
Raises:
204+
VerifyOrderError: The sequence was not satisfied.
205+
206+
!!! example
207+
```python
208+
def test_greet(decoy: Decoy):
209+
verify_greeting = decoy.mock(name="verify_greeting")
210+
greet = decoy.mock(name="greet")
211+
212+
# ...
213+
214+
with decoy.verify_order():
215+
decoy.verify(verify_greeting).called_with("hello world")
216+
decoy.verify(greet).called_with("hello world")
217+
```
218+
"""
219+
with self._state.verify_order() as verify_order_result:
220+
yield
221+
222+
if not verify_order_result.is_success:
223+
raise createVerifyOrderError(
224+
verify_order_result.verifications,
225+
verify_order_result.all_events,
226+
)
227+
228+
def reset(self) -> None:
229+
"""Reset the decoy instance."""
230+
self._state.reset()

decoy/next/_internal/errors.py

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
from typing import Literal
2+
3+
from ... import errors
4+
from .stringify import (
5+
count,
6+
join_lines,
7+
stringify_event,
8+
stringify_event_entry_list,
9+
stringify_event_list,
10+
stringify_verification_list,
11+
)
12+
from .values import Event, EventEntry, MatchOptions, VerificationEntry
13+
14+
15+
def createMockNameRequiredError() -> errors.MockNameRequiredError:
16+
"""Create a MockNameRequiredError."""
17+
return errors.MockNameRequiredError(
18+
"Mocks without `cls` or `func` require a `name`."
19+
)
20+
21+
22+
def createMockSpecInvalidError(
23+
argument_name: Literal["func", "cls"],
24+
) -> errors.MockSpecInvalidError:
25+
"""Create a MockSpecInvalidError."""
26+
expected_type = "function" if argument_name == "func" else "class"
27+
28+
return errors.MockSpecInvalidError(
29+
f"{argument_name} value must be a {expected_type}"
30+
)
31+
32+
33+
def createNotAMockError(method_name: str, actual_value: object) -> errors.NotAMockError:
34+
"""Create a NotAMockError."""
35+
return errors.NotAMockError(
36+
f"`Decoy.{method_name}` must be called with a mock, but got: {actual_value}"
37+
)
38+
39+
40+
def createThenDoActionNotCallableError() -> errors.ThenDoActionNotCallableError:
41+
"""Create a ThenDoActionNotCallableError."""
42+
return errors.ThenDoActionNotCallableError(
43+
"Value passed to `then_do` must be callable."
44+
)
45+
46+
47+
def createMockNotAsyncError() -> errors.MockNotAsyncError:
48+
"""Create a MockNotAsyncError."""
49+
return errors.MockNotAsyncError(
50+
"Synchronous mock cannot use an asynchronous callable in `then_do`."
51+
)
52+
53+
54+
def createSignatureMismatchError(
55+
source: TypeError | ValueError,
56+
) -> errors.SignatureMismatchError:
57+
"""Create a SignatureMismatchError."""
58+
return errors.SignatureMismatchError(source)
59+
60+
61+
def createVerifyError(
62+
mock_name: str,
63+
match_options: MatchOptions,
64+
expected: Event,
65+
all_events: list[EventEntry],
66+
) -> errors.VerifyError:
67+
"""Create a VerifyError."""
68+
if match_options.times is not None:
69+
heading = f"Expected exactly {count(match_options.times, 'call')}:"
70+
else:
71+
heading = "Expected at least 1 call:"
72+
73+
message = join_lines(
74+
heading,
75+
f"1.\t{stringify_event(mock_name, expected)}",
76+
(
77+
f"Found {count(len(all_events), 'call')}{'.' if len(all_events) == 0 else ':'}"
78+
),
79+
stringify_event_list(mock_name, [entry.event for entry in all_events]),
80+
)
81+
82+
return errors.VerifyError(message)
83+
84+
85+
def createVerifyOrderError(
86+
verifications: list[VerificationEntry],
87+
all_events: list[EventEntry],
88+
) -> errors.VerifyOrderError:
89+
"""Create a VerifyOrderError."""
90+
message = join_lines(
91+
"Expected call sequence:",
92+
stringify_verification_list(verifications),
93+
f"Found {len(all_events)} calls:",
94+
stringify_event_entry_list(all_events),
95+
)
96+
97+
return errors.VerifyOrderError(message)

0 commit comments

Comments
 (0)