Skip to content

Commit 6240f14

Browse files
committed
feat: add decoy.next preview API
1 parent c622a24 commit 6240f14

23 files changed

+1958
-220
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: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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, VerifyAttributes
8+
from ._internal.mock import AsyncMock, Mock
9+
from ._internal.verify import AttributesVerify, Verify
10+
from ._internal.when import Stub, When
11+
12+
__all__ = [
13+
"AsyncMock",
14+
"AttributesVerify",
15+
"Decoy",
16+
"Mock",
17+
"Stub",
18+
"Verify",
19+
"VerifyAttributes",
20+
"When",
21+
]

decoy/next/_internal/__init__.py

Whitespace-only changes.

decoy/next/_internal/decoy.py

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

0 commit comments

Comments
 (0)