|
| 1 | +"""Decoy test double stubbing and verification library.""" |
| 2 | + |
| 3 | +from mock import AsyncMock, MagicMock |
| 4 | +from typing import cast, Any, Callable, Mapping, Optional, Sequence, Tuple, Type |
| 5 | + |
| 6 | +from .registry import Registry |
| 7 | +from .stub import Stub |
| 8 | +from .types import Call, ClassT, FuncT, ReturnT |
| 9 | + |
| 10 | + |
| 11 | +class Decoy: |
| 12 | + """Decoy test double state container.""" |
| 13 | + |
| 14 | + _registry: Registry |
| 15 | + _last_decoy_id: Optional[int] |
| 16 | + |
| 17 | + def __init__(self) -> None: |
| 18 | + """ |
| 19 | + Initialize the state container for test doubles and stubs. |
| 20 | +
|
| 21 | + You should initialize a new Decoy instance for every test. |
| 22 | +
|
| 23 | + Example: |
| 24 | + ```python |
| 25 | + import pytest |
| 26 | + from decoy import Decoy |
| 27 | +
|
| 28 | + @pytest.fixture |
| 29 | + def decoy() -> Decoy: |
| 30 | + return Decoy() |
| 31 | + ``` |
| 32 | + """ |
| 33 | + self._registry = Registry() |
| 34 | + self._last_decoy_id = None |
| 35 | + |
| 36 | + def create_decoy(self, spec: Type[ClassT], *, is_async: bool = False) -> ClassT: |
| 37 | + """ |
| 38 | + Create a class decoy for `spec`. |
| 39 | +
|
| 40 | + Arguments: |
| 41 | + spec: A class definition that the decoy should mirror. |
| 42 | + is_async: Set to `True` if the class has `await`able methods. |
| 43 | +
|
| 44 | + Returns: |
| 45 | + A `MagicMock` or `AsyncMock`, typecast as an instance of `spec`. |
| 46 | +
|
| 47 | + Example: |
| 48 | + ```python |
| 49 | + def test_get_something(decoy: Decoy): |
| 50 | + db = decoy.create_decoy(spec=Database) |
| 51 | + # ... |
| 52 | + ``` |
| 53 | +
|
| 54 | + """ |
| 55 | + decoy = MagicMock(spec=spec) if is_async is False else AsyncMock(spec=spec) |
| 56 | + decoy_id = self._registry.register_decoy(decoy) |
| 57 | + side_effect = self._create_track_call_and_act(decoy_id) |
| 58 | + |
| 59 | + decoy.configure_mock( |
| 60 | + **{ |
| 61 | + f"{method}.side_effect": side_effect |
| 62 | + for method in dir(spec) |
| 63 | + if not (method.startswith("__") and method.endswith("__")) |
| 64 | + } |
| 65 | + ) |
| 66 | + |
| 67 | + return cast(ClassT, decoy) |
| 68 | + |
| 69 | + def create_decoy_func( |
| 70 | + self, spec: Optional[FuncT] = None, *, is_async: bool = False |
| 71 | + ) -> FuncT: |
| 72 | + """ |
| 73 | + Create a function decoy for `spec`. |
| 74 | +
|
| 75 | + Arguments: |
| 76 | + spec: A function that the decoy should mirror. |
| 77 | + is_async: Set to `True` if the function is `await`able. |
| 78 | +
|
| 79 | + Returns: |
| 80 | + A `MagicMock` or `AsyncMock`, typecast as the function given for `spec`. |
| 81 | +
|
| 82 | + Example: |
| 83 | + ```python |
| 84 | + def test_create_something(decoy: Decoy): |
| 85 | + gen_id = decoy.create_decoy_func(spec=generate_unique_id) |
| 86 | + # ... |
| 87 | + ``` |
| 88 | + """ |
| 89 | + decoy = MagicMock(spec=spec) if is_async is False else AsyncMock(spec=spec) |
| 90 | + decoy_id = self._registry.register_decoy(decoy) |
| 91 | + |
| 92 | + decoy.configure_mock(side_effect=self._create_track_call_and_act(decoy_id)) |
| 93 | + |
| 94 | + return cast(FuncT, decoy) |
| 95 | + |
| 96 | + def when(self, _rehearsal_result: ReturnT) -> Stub[ReturnT]: |
| 97 | + """ |
| 98 | + Create a [Stub][decoy.stub.Stub] configuration using a rehearsal call. |
| 99 | +
|
| 100 | + See [stubbing](/#stubbing) for more details. |
| 101 | +
|
| 102 | + Arguments: |
| 103 | + _rehearsal_result: The return value of a rehearsal, used for typechecking. |
| 104 | +
|
| 105 | + Returns: |
| 106 | + A Stub to configure using `then_return` or `then_raise`. |
| 107 | +
|
| 108 | + Example: |
| 109 | + ```python |
| 110 | + db = decoy.create_decoy(spec=Database) |
| 111 | + decoy.when(db.exists("some-id")).then_return(True) |
| 112 | + ``` |
| 113 | + """ |
| 114 | + decoy_id, rehearsal = self._pop_last_rehearsal() |
| 115 | + stub = Stub[ReturnT](rehearsal=rehearsal) |
| 116 | + |
| 117 | + self._registry.register_stub(decoy_id, stub) |
| 118 | + |
| 119 | + return stub |
| 120 | + |
| 121 | + def verify(self, _rehearsal_result: ReturnT) -> None: |
| 122 | + """ |
| 123 | + Verify a decoy was called using a rehearsal. |
| 124 | +
|
| 125 | + See [verification](/#verification) for more details. |
| 126 | +
|
| 127 | + Arguments: |
| 128 | + _rehearsal_result: The return value of a rehearsal, unused. |
| 129 | +
|
| 130 | + Example: |
| 131 | + ```python |
| 132 | + def test_create_something(decoy: Decoy): |
| 133 | + gen_id = decoy.create_decoy_func(spec=generate_unique_id) |
| 134 | +
|
| 135 | + # ... |
| 136 | +
|
| 137 | + decoy.verify(gen_id("model-prefix_")) |
| 138 | + ``` |
| 139 | + """ |
| 140 | + decoy_id, rehearsal = self._pop_last_rehearsal() |
| 141 | + decoy = self._registry.get_decoy(decoy_id) |
| 142 | + |
| 143 | + if decoy is None: |
| 144 | + raise ValueError("verify must be called with a decoy rehearsal") |
| 145 | + |
| 146 | + decoy.assert_has_calls([rehearsal]) |
| 147 | + |
| 148 | + def _pop_last_rehearsal(self) -> Tuple[int, Call]: |
| 149 | + decoy_id = self._last_decoy_id |
| 150 | + |
| 151 | + if decoy_id is not None: |
| 152 | + rehearsal = self._registry.pop_decoy_last_call(decoy_id) |
| 153 | + self._last_decoy_id = None |
| 154 | + |
| 155 | + if rehearsal is not None: |
| 156 | + return (decoy_id, rehearsal) |
| 157 | + |
| 158 | + raise ValueError("when/verify must be called with a decoy rehearsal") |
| 159 | + |
| 160 | + def _create_track_call_and_act(self, decoy_id: int) -> Callable[..., Any]: |
| 161 | + def track_call_and_act( |
| 162 | + *args: Sequence[Any], **_kwargs: Mapping[str, Any] |
| 163 | + ) -> Any: |
| 164 | + self._last_decoy_id = decoy_id |
| 165 | + |
| 166 | + last_call = self._registry.peek_decoy_last_call(decoy_id) |
| 167 | + stubs = reversed(self._registry.get_decoy_stubs(decoy_id)) |
| 168 | + |
| 169 | + if last_call is not None: |
| 170 | + for stub in stubs: |
| 171 | + if stub._rehearsal == last_call: |
| 172 | + return stub._act() |
| 173 | + |
| 174 | + return None |
| 175 | + |
| 176 | + return track_call_and_act |
0 commit comments