|
| 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