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