declarative-mocks 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,278 @@
1
+ Metadata-Version: 2.4
2
+ Name: declarative-mocks
3
+ Version: 0.1.0
4
+ Summary: Declare mock behavior as ordered expectations. Simple, typed, gomock-inspired DSL over unittest.mock
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Keywords: mock,mocking,testing,unittest,pytest
8
+ Author: Dimitry Churilov
9
+ Author-email: d.mdx3r@gmail.com
10
+ Requires-Python: >=3.11
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Software Development :: Testing
20
+ Classifier: Topic :: Software Development :: Testing :: Mocking
21
+ Classifier: Typing :: Typed
22
+ Project-URL: Homepage, https://github.com/MDx3R/declarative-mocks
23
+ Project-URL: Issues, https://github.com/MDx3R/declarative-mocks/issues
24
+ Project-URL: Repository, https://github.com/MDx3R/declarative-mocks
25
+ Description-Content-Type: text/markdown
26
+
27
+ [![Checks](https://github.com/MDx3R/declarative-mocks/actions/workflows/ci.yml/badge.svg)](https://github.com/MDx3R/declarative-mocks/actions/workflows/ci.yml)
28
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%20%7C%203.12%20%7C%203.13%20%7C%203.14-blue.svg)](https://www.python.org/downloads/)
29
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
30
+
31
+ # declarative-mocks
32
+
33
+ **Declare mock behavior as ordered expectations** - readable tests with explicit call patterns, return sequences, and side effects, built on `unittest.mock`.
34
+
35
+ ## Features
36
+
37
+ ---
38
+
39
+ - **Fluent expectations** - register calls with arguments (positional vs keyword aware), matchers (`Anything`, `ANY_ARGS` / `ANY_KWARGS`, …), and outcomes in order.
40
+ - **Return sequences** - chain multiple `.returns()` / `.raises()` / `.runs()` for successive matching calls.
41
+ - **Call-count controls** - one quantifier per `expect(...)` (`.once()`, `.times(n)`, `.between(min, max)`, `.never()`, and more).
42
+ - **Spec-backed mocks** - aligned with `Mock(spec=…)` semantics for safer, clearer tests.
43
+ - **Async without ceremony** - `expect()` on `async def` methods is the same DSL; `runs()` accepts both sync and async callables.
44
+ - **No extra runtime dependencies** - only the standard library at runtime.
45
+
46
+ ## Installation
47
+
48
+ ---
49
+
50
+ The first PyPI release is being prepared. Until then, install from source:
51
+
52
+ ```bash
53
+ poetry install
54
+ ```
55
+
56
+ The intended published command:
57
+
58
+ ```bash
59
+ pip install declarative-mocks
60
+ ```
61
+
62
+ ## The idea: before and after
63
+
64
+ ---
65
+
66
+ **Before - `unittest.mock`:** behavior is spread across `return_value`, `side_effect`, and ad hoc assertions; ordering and “what happens on the third call?” are easy to lose in a long test.
67
+
68
+ ```python
69
+ from unittest.mock import Mock
70
+
71
+ service = Mock(spec=MyService)
72
+ service.fetch_user.side_effect = [
73
+ {"id": 1, "name": "Ada"},
74
+ {"id": 1, "name": "Ada"},
75
+ ConnectionError("retry"),
76
+ ]
77
+ # … exercise code …
78
+ # Assertions about call order and counts are often manual and verbose.
79
+ ```
80
+
81
+ **After - `dmock`:** the same story is **declared** next to the mock: ordered expectations, explicit outcomes, and a single verification step.
82
+
83
+ ```python
84
+ from dmock import DeclarativeMock
85
+
86
+ service = DeclarativeMock(MyService)
87
+ service.expect("fetch_user").returns({"id": 1, "name": "Ada"}).returns({"id": 1, "name": "Ada"})
88
+ service.expect("fetch_user").raises(ConnectionError("retry"))
89
+ # … exercise code …
90
+ service.verify()
91
+ ```
92
+
93
+ ## How it compares
94
+
95
+ ---
96
+
97
+ The goals are the same as above: a strictly typed expectation DSL, a whitelist mock you construct, call order as a graph, and async wrapping every method in AsyncMock yourself. Against [mockito-python](https://github.com/kaste/mockito-python) and [flexmock](https://github.com/flexmock/flexmock) that looks like this.
98
+
99
+ ### Static analysis
100
+
101
+ That only matters if you type-check tests. Tests deserve the same quality bar as production code - maybe more, now that agents write so much of the suite.
102
+
103
+ `mockito-python` is strong on features, but the installed package has **no `py.typed` marker and no `.pyi` stubs**. Then `mypy tests` fails on `import mockito` (`missing library stubs or py.typed marker`) unless you set `ignore_missing_imports = True`. That is [issue #58](https://github.com/kaste/mockito-python/issues/58): the reporter was already ignoring the package; the maintainer called full typing “some significant work.” The ignore makes mypy succeed by treating mockito as `Any`, so `when` / `thenReturn` / `verify` themselves are not checked.
104
+
105
+ `flexmock` **is** typed (`py.typed` since 0.11.3), but it addresses methods **by string** (`should_receive("fetch_user")`), so the name is still not checked statically.
106
+
107
+ `dmock` is the only one of the three that is **strictly typed** (`py.typed`) **and** uses real attribute names on the mock (`mock.fetch_user(...)`), validated against the spec at construction/`expect()` time.
108
+
109
+ ### Shorter setup and verify
110
+
111
+ With dmock you write the call once. `verify()` does not repeat it:
112
+
113
+ ```python
114
+ mock.expect("fetch_user", 1).returns(user).once()
115
+ # … exercise code …
116
+ mock.verify()
117
+ ```
118
+
119
+ mockito splits **configuration and verification** into two expressions that repeat the call:
120
+
121
+ ```python
122
+ when(service).fetch_user(1).thenReturn(user)
123
+ # … exercise code …
124
+ verify(service, times=1).fetch_user(1)
125
+ ```
126
+
127
+ flexmock uses a four-link chain and a string method name:
128
+
129
+ ```python
130
+ flexmock(service).should_receive("fetch_user").with_args(1).and_return(user).once()
131
+ ```
132
+
133
+ ### A whitelist mock you construct
134
+
135
+ `DeclarativeMock(MyService)` is an object you **hold and pass in**. Unregistered calls fail immediately. Nothing on live modules or instances is rewritten.
136
+
137
+ mockito's usual `when(obj)` **does** rewrite methods on `obj` (module, class, or instance). The docs say you must `unstub()` afterwards, or use `with` / a pytest fixture, or stubs leak into later tests. `mock()` can create an injectable dummy instead, but it still sits in the same global registry.
138
+
139
+ flexmock also replaces attributes on existing objects (`should_receive`). Restore is automatic under pytest and unittest - there is no `unstub()` you call by hand.
140
+
141
+ ### Call order as a dependency graph
142
+
143
+ `.not_before(...)` and `in_order(...)` are checked **at the violating call**, not after the fact at `verify()`. Dependencies may cross mock instances. Cycles are rejected at configuration time with `ConfigurationError`.
144
+
145
+ ### Async without caveats
146
+
147
+ This argument holds **against flexmock**, not against mockito.
148
+
149
+ flexmock still has **no first-class async API** (no `async` / `await` / `coroutine` in the changelog or API reference). The documented workaround is to return an `AsyncMock` or `asyncio.Future` yourself.
150
+
151
+ mockito added first-class async/await stubbing in **2.0.0**. Their remaining caveat: introspection metadata such as `inspect.iscoroutinefunction` on stub wrappers is implemented **only on Python 3.12+**.
152
+
153
+ `dmock` installs a real nested `async def` dispatcher, so `inspect.iscoroutinefunction(mock.aprocess_order)` is true on **every supported Python** (3.11-3.14).
154
+
155
+ ## Usage examples
156
+
157
+ ---
158
+
159
+ ### 1. Nested return values (successive `.returns()`)
160
+
161
+ Each `.returns()` applies to the next matching call in order - handy for paginated or multi-step flows without a hand-built `side_effect` list.
162
+
163
+ ```python
164
+ from dmock import DeclarativeMock
165
+
166
+ api = DeclarativeMock(ApiClient)
167
+ api.expect("next_page").returns({"items": [1], "cursor": "a"})
168
+ api.expect("next_page").returns({"items": [2], "cursor": None})
169
+
170
+ # first call → first dict; second call → second dict
171
+ ```
172
+
173
+ ### 2. Outcome sequences with `.runs()` and `.returns()`
174
+
175
+ Chained outcomes apply to **successive matching calls**, not to a single call. `.runs(fn).returns(value)` means: first call runs `fn` (its return value is the result); second call returns `value`. A quantifier (`.once()`, `.at_least(n)`, …) applies to the **whole** `expect(...)` chain, not to the last outcome. A second quantifier on the same chain raises `ConfigurationError`.
176
+
177
+ If you omit a quantifier, the count is exactly the number of chained outcomes (minimum 1). `.runs(fn)` alone is **one** call; a second match is unexpected. The last outcome repeats only when the quantifier allows more calls than outcomes - for example `.runs(fn).at_least(1)` to run the callable on every matching call.
178
+
179
+ ```python
180
+ from dmock import DeclarativeMock
181
+
182
+ calc = DeclarativeMock(Calculator)
183
+ calc.expect("price", 100).runs(lambda x: x - 1).returns(99)
184
+
185
+ assert calc.price(100) == 99 # from the lambda
186
+ assert calc.price(100) == 99 # from .returns(99)
187
+ ```
188
+
189
+ ### 3. Strict argument matching (positional vs keyword)
190
+
191
+ `expect("method")` with **no** extra args means “called with no arguments” - not “anything.” Use matchers when you need to accept arbitrary values.
192
+
193
+ ```python
194
+ from dmock import Anything, DeclarativeMock
195
+
196
+ m = DeclarativeMock(Worker)
197
+
198
+ # any single positional arg
199
+ m.expect("run", Anything()).returns(0)
200
+
201
+ # keyword-specific expectation
202
+ m.expect("run", job_id=123).returns("queued")
203
+ ```
204
+
205
+ ### 4. Variadic arguments (`ANY_ARGS`, `ANY_KWARGS`)
206
+
207
+ To match **any** positional and keyword arguments (including none), use the dedicated wildcards instead of repeating `Anything()`.
208
+
209
+ ```python
210
+ from dmock import ANY_ARGS, ANY_KWARGS, DeclarativeMock
211
+
212
+ m = DeclarativeMock(Worker)
213
+ m.expect("run", ANY_ARGS, ANY_KWARGS).returns(0)
214
+ ```
215
+
216
+ ### 5. Async methods
217
+
218
+ `expect()` on an `async def` spec method needs no extra type. Await the call as usual. `runs()` accepts a sync callable or an `async def`; both work.
219
+
220
+ ```python
221
+ from dmock import Anything, DeclarativeMock
222
+
223
+ mock = DeclarativeMock(MyService)
224
+ mock.expect("aprocess_order", Anything()).returns("ok")
225
+ assert await mock.aprocess_order(1) == "ok"
226
+
227
+ mock.expect("aprocess_order", Anything()).runs(lambda order_id: f"sync-{order_id}")
228
+ assert await mock.aprocess_order(7) == "sync-7"
229
+
230
+ async def async_fn(order_id: int) -> str:
231
+ return f"async-{order_id}"
232
+
233
+ mock.expect("aprocess_order", Anything()).runs(async_fn)
234
+ assert await mock.aprocess_order(9) == "async-9"
235
+ ```
236
+
237
+ For full DSL details and edge cases, see **`SPEC.md`** and **`REFERENCE.md`**.
238
+
239
+ ## Limitations & non-goals
240
+
241
+ ---
242
+
243
+ - **No signature binding.** `expect("method", …)` checks that `method` exists on the spec, not that the argument list matches the real signature.
244
+ - **No automatic `verify()`.** You call `verify()` yourself (a pytest hook is on the roadmap).
245
+ - **No spies and no patching.** The library does not wrap live objects, modules, or `sys.modules`. Construct a `DeclarativeMock` and pass it in.
246
+ - **Not thread-safe.** Concurrent use of one mock from multiple threads is out of scope.
247
+
248
+ ## Roadmap
249
+
250
+ ---
251
+
252
+ After 0.1.0, in no particular order:
253
+
254
+ - **pytest auto-`verify()`** - a plugin or fixture that runs `verify()` at the end of each test (gomock-style `Finish` on teardown), so you do not have to remember the call.
255
+ - **Per-outcome counts (maybe)** - repeat a `.returns()` / `.raises()` / `.runs()` without chaining it n times (today `.returns(1).returns(1).returns(1).returns(2)`).
256
+ - **Rich matchers** - more than `Anything` / `AnythingOfType` / `MatchedBy`: regex, numeric bounds, datetime (and ISO strings), containers, truthy/falsy, plus `and` / `or` / `not`. In the spirit of [anys](https://github.com/jwodder/anys).
257
+
258
+ Other ideas belong in GitHub Issues.
259
+
260
+ ## Development
261
+
262
+ ---
263
+
264
+ ```bash
265
+ poetry install
266
+ ruff check .
267
+ ruff format --check .
268
+ mypy src tests
269
+ pytest
270
+ pytest --cov --cov-report=term-missing
271
+ ```
272
+
273
+ See **[CONTRIBUTING.md](CONTRIBUTING.md)** for setup, commits, and tests. Agents follow **[AGENTS.md](AGENTS.md)**.
274
+
275
+ ## License
276
+
277
+ MIT
278
+
@@ -0,0 +1,11 @@
1
+ dmock/__init__.py,sha256=_DXB28RdEU853TLYB5YppQCJkvJ5axAmxwHeyGSLhH0,958
2
+ dmock/_exceptions.py,sha256=QWljNz_TAdvPEUI8yBqPuXCdPWQ016k2NROYLgozyQ0,5157
3
+ dmock/_expectation.py,sha256=r1suBmh61KeR7wzvmFJ6s4N1UGB8gD-_HwdumXAVcRc,16737
4
+ dmock/_matchers.py,sha256=XmOZYHuNt7H6v7Bc6CIZkotqMn12YdjcIHQg038a4QM,5298
5
+ dmock/_mock.py,sha256=_zk7UsCy0pfQbY9axv2ftazt96E4Tjxg044WVI30kzQ,9551
6
+ dmock/_types.py,sha256=DpkiDxlLfUs7VO-A3-6vha-qqw6dQWLU5fpyMNPkOsw,4437
7
+ dmock/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ declarative_mocks-0.1.0.dist-info/METADATA,sha256=iz6VUQOFVBg9hIhTWBFWqAC28-SL-s6M1WuCeDD9d-Q,11737
9
+ declarative_mocks-0.1.0.dist-info/WHEEL,sha256=EGEvSphFYqXKs23-kQBeyNoJP1nrT8ZJKQoi5p5DYL8,88
10
+ declarative_mocks-0.1.0.dist-info/licenses/LICENSE,sha256=JiZ9SxOFDKPV2TVArK2YvoZshvMnenmvrFVVlKVNvlo,1073
11
+ declarative_mocks-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.4.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dimitry Churilov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
dmock/__init__.py ADDED
@@ -0,0 +1,45 @@
1
+ """Declarative wrapper around unittest.mock with a DSL for tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, version
6
+
7
+ from dmock._exceptions import (
8
+ ConfigurationError,
9
+ DeclarativeMockError,
10
+ UnexpectedCallError,
11
+ UnsatisfiedExpectationError,
12
+ )
13
+ from dmock._expectation import Expectation, in_order
14
+ from dmock._matchers import (
15
+ ANY_ARGS,
16
+ ANY_KWARGS,
17
+ Anything,
18
+ AnythingOfType,
19
+ MatchedBy,
20
+ Matcher,
21
+ )
22
+ from dmock._mock import DeclarativeMock
23
+
24
+
25
+ try:
26
+ __version__ = version("declarative-mocks")
27
+ except PackageNotFoundError: # pragma: no cover
28
+ __version__ = "0.0.0+unknown"
29
+
30
+
31
+ __all__ = [
32
+ "ANY_ARGS",
33
+ "ANY_KWARGS",
34
+ "Anything",
35
+ "AnythingOfType",
36
+ "ConfigurationError",
37
+ "DeclarativeMock",
38
+ "DeclarativeMockError",
39
+ "Expectation",
40
+ "MatchedBy",
41
+ "Matcher",
42
+ "UnexpectedCallError",
43
+ "UnsatisfiedExpectationError",
44
+ "in_order",
45
+ ]
dmock/_exceptions.py ADDED
@@ -0,0 +1,166 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+
6
+ if TYPE_CHECKING:
7
+ from collections.abc import Sequence
8
+
9
+ from dmock._expectation import Expectation
10
+ from dmock._types import RecordedCall
11
+
12
+
13
+ class DeclarativeMockError(Exception):
14
+ """Base for all dmock errors."""
15
+
16
+
17
+ class UnexpectedCallError(DeclarativeMockError):
18
+ """A call matched no registered expectation.
19
+
20
+ Raised at dispatch time: missing ``expect``, argument mismatch, exhausted
21
+ expectation, out-of-order call, or ``never()``. Catch this type; the
22
+ traceback may show a more specific subclass.
23
+ """
24
+
25
+
26
+ class UnregisteredCallError(UnexpectedCallError):
27
+ """Attribute has no registered expectation (whitelist miss)."""
28
+
29
+ def __init__(self, name: str, history: Sequence[RecordedCall]) -> None:
30
+ self.name = name
31
+ self.history = tuple(history)
32
+ super().__init__()
33
+
34
+ def __str__(self) -> str:
35
+ return _with_history(
36
+ f"Unexpected call: {self.name!r} has no registered expectation.",
37
+ self.history,
38
+ )
39
+
40
+
41
+ class NoMatchingCallError(UnexpectedCallError):
42
+ """Call matched no non-exhausted expectation for this name."""
43
+
44
+ def __init__(
45
+ self,
46
+ call: RecordedCall,
47
+ rejected: Sequence[Expectation],
48
+ history: Sequence[RecordedCall],
49
+ ) -> None:
50
+ self.call = call
51
+ self.rejected = tuple(rejected)
52
+ self.history = tuple(history)
53
+ super().__init__()
54
+
55
+ def __str__(self) -> str:
56
+ header = (
57
+ f"Unexpected call: {self.call.name!r} called with "
58
+ f"args={self.call.args!r}, kwargs={self.call.kwargs!r}"
59
+ )
60
+ candidates = "\n".join(
61
+ f" {exp!r} - {self._reason(exp)}" for exp in self.rejected
62
+ )
63
+ return _with_history(
64
+ f"{header} - no matching non-exhausted expectation.\n"
65
+ f"Candidates:\n{candidates}",
66
+ self.history,
67
+ )
68
+
69
+ def _reason(self, exp: Expectation) -> str:
70
+ if exp.is_exhausted():
71
+ maximum = exp.quantifier.max_calls
72
+ bound = "*" if maximum is None else str(maximum)
73
+ return f"exhausted ({exp.call_count}/{bound} calls)"
74
+
75
+ return "args mismatch"
76
+
77
+
78
+ class BlockedCallError(UnexpectedCallError):
79
+ """Call matched an expectation whose prerequisites are not yet satisfied."""
80
+
81
+ def __init__(
82
+ self,
83
+ call: RecordedCall,
84
+ expectation: Expectation,
85
+ blocked: Sequence[Expectation],
86
+ history: Sequence[RecordedCall],
87
+ ) -> None:
88
+ self.call = call
89
+ self.expectation = expectation
90
+ self.blocked = tuple(blocked)
91
+ self.history = tuple(history)
92
+ super().__init__()
93
+
94
+ def __str__(self) -> str:
95
+ reasons = "; ".join(self._blocked_reason(req) for req in self.blocked)
96
+ return _with_history(
97
+ f"Out-of-order call: {self.call.name!r} called with "
98
+ f"args={self.call.args!r}, kwargs={self.call.kwargs!r}\n"
99
+ f" {self.expectation!r} - {reasons}",
100
+ self.history,
101
+ )
102
+
103
+ @staticmethod
104
+ def _blocked_reason(req: Expectation) -> str:
105
+ return (
106
+ f"blocked by {req.method_name} "
107
+ f"(expected {req.quantifier.description}, got {req.call_count})"
108
+ )
109
+
110
+
111
+ class ExceededCallError(UnexpectedCallError):
112
+ """A matching call exceeded the expectation's quantifier upper bound."""
113
+
114
+ def __init__(self, method_name: str, calls: int, max_calls: int) -> None:
115
+ self.method_name = method_name
116
+ self.calls = calls
117
+ self.max_calls = max_calls
118
+ super().__init__()
119
+
120
+ def __str__(self) -> str:
121
+ return (
122
+ f"Unexpected call to {self.method_name!r}: "
123
+ f"called {self.calls} time(s), "
124
+ f"max allowed is {self.max_calls}."
125
+ )
126
+
127
+
128
+ class UnsatisfiedExpectationError(DeclarativeMockError):
129
+ """Raised by :meth:`~dmock.DeclarativeMock.verify` when a quantifier is unmet."""
130
+
131
+ def __init__(
132
+ self,
133
+ expectations: Sequence[Expectation],
134
+ history: Sequence[RecordedCall],
135
+ ) -> None:
136
+ self.expectations = tuple(expectations)
137
+ self.history = tuple(history)
138
+ super().__init__()
139
+
140
+ def __str__(self) -> str:
141
+ lines = "\n".join(
142
+ f" {exp!r} - expected {exp.quantifier.description}, got {exp.call_count}"
143
+ for exp in self.expectations
144
+ )
145
+ return _with_history(f"Unsatisfied expectations:\n{lines}", self.history)
146
+
147
+
148
+ class ConfigurationError(DeclarativeMockError):
149
+ """Invalid expectation setup (conflicting quantifiers, reserved names, cycles)."""
150
+
151
+
152
+ def _with_history(message: str, history: Sequence[RecordedCall]) -> str:
153
+ if not history:
154
+ return message
155
+
156
+ lines = "\n".join(
157
+ f" {index}. {_format_call(call)}"
158
+ for index, call in enumerate(history, start=1)
159
+ )
160
+ return f"{message}\nCall history:\n{lines}"
161
+
162
+
163
+ def _format_call(call: RecordedCall) -> str:
164
+ parts = [repr(a) for a in call.args]
165
+ parts.extend(f"{key}={value!r}" for key, value in call.kwargs.items())
166
+ return f"{call.name}({', '.join(parts)})"