declarative-mocks 0.4.2__tar.gz → 0.5.1__tar.gz
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.
- declarative_mocks-0.5.1/PKG-INFO +368 -0
- declarative_mocks-0.5.1/README.md +337 -0
- {declarative_mocks-0.4.2 → declarative_mocks-0.5.1}/pyproject.toml +10 -3
- {declarative_mocks-0.4.2 → declarative_mocks-0.5.1}/src/dmock/__init__.py +38 -9
- declarative_mocks-0.5.1/src/dmock/_checks.py +174 -0
- {declarative_mocks-0.4.2 → declarative_mocks-0.5.1}/src/dmock/_exceptions.py +66 -18
- declarative_mocks-0.5.1/src/dmock/_interaction.py +1803 -0
- {declarative_mocks-0.4.2 → declarative_mocks-0.5.1}/src/dmock/_matchers.py +709 -151
- {declarative_mocks-0.4.2 → declarative_mocks-0.5.1}/src/dmock/_mock.py +76 -19
- {declarative_mocks-0.4.2 → declarative_mocks-0.5.1}/src/dmock/_protocols.py +5 -3
- {declarative_mocks-0.4.2 → declarative_mocks-0.5.1}/src/dmock/_pytest_plugin.py +7 -6
- {declarative_mocks-0.4.2 → declarative_mocks-0.5.1}/src/dmock/_registry.py +55 -2
- declarative_mocks-0.5.1/src/dmock/_spy.py +580 -0
- {declarative_mocks-0.4.2 → declarative_mocks-0.5.1}/src/dmock/_types.py +35 -1
- declarative_mocks-0.4.2/PKG-INFO +0 -278
- declarative_mocks-0.4.2/README.md +0 -248
- declarative_mocks-0.4.2/src/dmock/_expectation.py +0 -553
- {declarative_mocks-0.4.2 → declarative_mocks-0.5.1}/LICENSE +0 -0
- {declarative_mocks-0.4.2 → declarative_mocks-0.5.1}/src/dmock/py.typed +0 -0
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: declarative-mocks
|
|
3
|
+
Version: 0.5.1
|
|
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,spying,testing,unittest,pytest
|
|
8
|
+
Author: Dimitry Churilov
|
|
9
|
+
Author-email: d.mdx3r@gmail.com
|
|
10
|
+
Requires-Python: >=3.11
|
|
11
|
+
Classifier: Framework :: Pytest
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
23
|
+
Classifier: Topic :: Software Development :: Testing
|
|
24
|
+
Classifier: Topic :: Software Development :: Testing :: Mocking
|
|
25
|
+
Classifier: Typing :: Typed
|
|
26
|
+
Project-URL: Homepage, https://github.com/MDx3R/declarative-mocks
|
|
27
|
+
Project-URL: Issues, https://github.com/MDx3R/declarative-mocks/issues
|
|
28
|
+
Project-URL: Repository, https://github.com/MDx3R/declarative-mocks
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+

|
|
32
|
+

|
|
33
|
+

|
|
34
|
+

|
|
35
|
+
|
|
36
|
+
# declarative-mocks
|
|
37
|
+
|
|
38
|
+
**Declare mock behavior as ordered expectations**. Write readable and maintainable tests with explicit call patterns, return sequences, and side effects using **dmock**.
|
|
39
|
+
|
|
40
|
+
It is fully documented. Public methods and matchers ship with docstring examples, and pretty much everything about API and behavior is described in [REFERENCE.md](REFERENCE.md) and [SPEC.md](SPEC.md).
|
|
41
|
+
|
|
42
|
+
## Installation
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install declarative-mocks
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
_dmock_ requires Python 3.11+.
|
|
49
|
+
|
|
50
|
+
## Usage
|
|
51
|
+
|
|
52
|
+
Normally you would set a return value, then check the object field by field and assert the call separately:
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from dataclasses import dataclass, field
|
|
56
|
+
from datetime import datetime
|
|
57
|
+
from unittest.mock import Mock
|
|
58
|
+
|
|
59
|
+
@dataclass
|
|
60
|
+
class User:
|
|
61
|
+
id: int
|
|
62
|
+
name: str
|
|
63
|
+
email: str
|
|
64
|
+
created_at: datetime = field(default_factory=datetime.now)
|
|
65
|
+
|
|
66
|
+
class Directory:
|
|
67
|
+
def lookup(self, name: str) -> User: ...
|
|
68
|
+
|
|
69
|
+
service = Mock(spec=Directory)
|
|
70
|
+
service.lookup.return_value = User(id=1, name="Ada", email="ada@example.com")
|
|
71
|
+
|
|
72
|
+
user = service.lookup("ada")
|
|
73
|
+
assert user.id == 1
|
|
74
|
+
assert user.name == "Ada"
|
|
75
|
+
assert user.email == "ada@example.com"
|
|
76
|
+
assert abs((datetime.now() - user.created_at).total_seconds()) < 5
|
|
77
|
+
name = service.lookup.call_args.args[0]
|
|
78
|
+
assert isinstance(name, str)
|
|
79
|
+
assert name.startswith("a")
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Here's an example of how **dmock** improves your tests:
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from dmock import DeclarativeMock, IsNow, StartsWith
|
|
86
|
+
|
|
87
|
+
service = DeclarativeMock(Directory)
|
|
88
|
+
service.expect(Directory.lookup, StartsWith("a")).returns(
|
|
89
|
+
User(id=1, name="Ada", email="ada@example.com")
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
assert service.lookup("ada") == User(
|
|
93
|
+
id=1,
|
|
94
|
+
name="Ada",
|
|
95
|
+
email="ada@example.com",
|
|
96
|
+
created_at=IsNow(),
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
# verify is automatic with pytest
|
|
100
|
+
service.verify()
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
That's not all! **dmock** can do so much more than that, for example:
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
from dmock import DeclarativeMock
|
|
107
|
+
|
|
108
|
+
# dmock(ApiClient) is a shorthand for DeclarativeMock(ApiClient)
|
|
109
|
+
api = DeclarativeMock(ApiClient)
|
|
110
|
+
|
|
111
|
+
# Use a method reference to help type checkers validate expected arguments
|
|
112
|
+
# and the values passed to .returns() and .runs()
|
|
113
|
+
api.expect(ApiClient.next_page).returns({"items": [1]}).returns({"items": [2]})
|
|
114
|
+
# Or use the string form to produce a lenient expectation without static type checking
|
|
115
|
+
api.expect("next_page").raises(TimeoutError)
|
|
116
|
+
|
|
117
|
+
assert api.next_page() == {"items": [1]}
|
|
118
|
+
assert api.next_page() == {"items": [2]}
|
|
119
|
+
# Third call raises TimeoutError
|
|
120
|
+
|
|
121
|
+
# Successive outcomes apply to the next matching call, in order:
|
|
122
|
+
# first .runs(), then .returns()
|
|
123
|
+
calc = DeclarativeMock(Calculator)
|
|
124
|
+
calc.expect("price", 100).runs(lambda x: x - 1).returns(99)
|
|
125
|
+
assert calc.price(100) == 99 # computed by the lambda
|
|
126
|
+
assert calc.price(100) == 99 # returned by .returns(99)
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Same args follow registration order; different args or methods match in any order unless explicitly linked:
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
from dmock import DeclarativeMock, in_order
|
|
133
|
+
|
|
134
|
+
api = DeclarativeMock(ApiClient)
|
|
135
|
+
|
|
136
|
+
# Each call matches the first non-exhausted expectation with matching args:
|
|
137
|
+
# same args are consumed in registration order, different args match in any order
|
|
138
|
+
api.expect("fetch", 1).returns("one")
|
|
139
|
+
api.expect("fetch", 2).returns("two")
|
|
140
|
+
api.expect("fetch", 1).returns("one x2")
|
|
141
|
+
assert api.fetch(2) == "two"
|
|
142
|
+
assert api.fetch(1) == "one"
|
|
143
|
+
assert api.fetch(1) == "one x2"
|
|
144
|
+
|
|
145
|
+
# Chain .expect(...) to require strict order (close cannot be called before connect)
|
|
146
|
+
api.expect("connect").returns(True).once().expect("close").returns(None).once()
|
|
147
|
+
|
|
148
|
+
# Or link expectations explicitly with in_order(...)
|
|
149
|
+
cache = DeclarativeMock(Cache)
|
|
150
|
+
fetched = api.expect("fetch", 10).returns("data").once()
|
|
151
|
+
cached = cache.expect("set", 10, "data").once()
|
|
152
|
+
in_order(fetched, cached) # works across different mocks and spies
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Argument matching is strictly explicit; positional, keyword, and wildcard shapes are distinct and must match how the call is made:
|
|
156
|
+
|
|
157
|
+
```python
|
|
158
|
+
from dmock import ANY_ARGS, ANY_KWARGS, Anything, DeclarativeMock
|
|
159
|
+
|
|
160
|
+
m = DeclarativeMock(Worker)
|
|
161
|
+
m.expect("run") # matches only a call with no arguments
|
|
162
|
+
m.expect("run", Anything()).returns(0) # matches any single positional argument
|
|
163
|
+
m.expect("run", job_id=123).returns("queued") # matches only when passed by keyword
|
|
164
|
+
# ANY_ARGS / ANY_KWARGS skip all positional / keyword checks, including none;
|
|
165
|
+
# use Anything() to match a specific position or keyword
|
|
166
|
+
m.expect("run", ANY_ARGS, ANY_KWARGS).returns(0)
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Only one quantifier per expectation is allowed, and `verify()` checks the counts:
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
from dmock import DeclarativeMock
|
|
173
|
+
|
|
174
|
+
calc = DeclarativeMock(Calculator)
|
|
175
|
+
calc.expect("price", 100).returns(99).once()
|
|
176
|
+
assert calc.price(100) == 99
|
|
177
|
+
|
|
178
|
+
# repeat=2 queues "warmup" twice; because times(4) expects 4 calls,
|
|
179
|
+
# the last outcome ("ready") repeats for the remaining two calls
|
|
180
|
+
calc.expect("status").returns("warmup", repeat=2).returns("ready").times(4)
|
|
181
|
+
assert [calc.status() for _ in range(4)] == ["warmup", "warmup", "ready", "ready"]
|
|
182
|
+
|
|
183
|
+
calc.expect("price", 300).returns(99).between(1, 3)
|
|
184
|
+
assert calc.price(300) == 99
|
|
185
|
+
|
|
186
|
+
# Must not be called; any matching call raises UnexpectedCallError immediately
|
|
187
|
+
calc.expect("price", 400).never()
|
|
188
|
+
# Optional expectation: zero calls still pass verify()
|
|
189
|
+
calc.expect("price", 500).returns(0).maybe()
|
|
190
|
+
calc.verify()
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
Async methods and properties use the same DSL:
|
|
194
|
+
|
|
195
|
+
```python
|
|
196
|
+
from dmock import Anything, DeclarativeMock
|
|
197
|
+
|
|
198
|
+
mock = DeclarativeMock(MyService)
|
|
199
|
+
|
|
200
|
+
# Stub attribute access directly (no call needed, not tracked by verify())
|
|
201
|
+
mock.property(MyService.timeout, 30)
|
|
202
|
+
assert mock.timeout == 30
|
|
203
|
+
|
|
204
|
+
# Async methods are detected automatically and awaited as usual
|
|
205
|
+
mock.expect(MyService.aprocess_order, Anything()).returns("ok")
|
|
206
|
+
assert await mock.aprocess_order(1) == "ok"
|
|
207
|
+
|
|
208
|
+
# runs() accepts both regular functions and async def callables
|
|
209
|
+
mock.expect(MyService.aprocess_order, Anything()).runs(
|
|
210
|
+
lambda order_id: f"sync-{order_id}"
|
|
211
|
+
)
|
|
212
|
+
assert await mock.aprocess_order(7) == "sync-7"
|
|
213
|
+
|
|
214
|
+
async def async_fn(order_id: int) -> str:
|
|
215
|
+
return f"async-{order_id}"
|
|
216
|
+
|
|
217
|
+
mock.expect(MyService.aprocess_order, Anything()).runs(async_fn)
|
|
218
|
+
assert await mock.aprocess_order(9) == "async-9"
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
The matcher set is rich enough that even the most complicated call stays as **one declarative expectation**:
|
|
222
|
+
|
|
223
|
+
```python
|
|
224
|
+
from dmock import (
|
|
225
|
+
AnyOrder,
|
|
226
|
+
DeclarativeMock,
|
|
227
|
+
GreaterThan,
|
|
228
|
+
HasLen,
|
|
229
|
+
IsUUID,
|
|
230
|
+
PartialMapping,
|
|
231
|
+
StartsWith,
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
bus = DeclarativeMock(EventBus)
|
|
235
|
+
bus.expect(
|
|
236
|
+
"publish",
|
|
237
|
+
topic=StartsWith("orders.events."),
|
|
238
|
+
# PartialMapping checks only the listed keys and ignores any extra ones
|
|
239
|
+
headers=PartialMapping(
|
|
240
|
+
{
|
|
241
|
+
"x-correlation-id": IsUUID(),
|
|
242
|
+
"x-origin-service": "checkout-service",
|
|
243
|
+
}
|
|
244
|
+
),
|
|
245
|
+
payload=PartialMapping(
|
|
246
|
+
{
|
|
247
|
+
"order_id": GreaterThan(0),
|
|
248
|
+
# Matchers compose with &, |, and ~
|
|
249
|
+
"items": (
|
|
250
|
+
HasLen(GreaterThan(0))
|
|
251
|
+
& AnyOrder(
|
|
252
|
+
[
|
|
253
|
+
PartialMapping({"sku": "SKU-AAA", "qty": 1}),
|
|
254
|
+
PartialMapping({"sku": "SKU-BBB", "qty": 2}),
|
|
255
|
+
]
|
|
256
|
+
)
|
|
257
|
+
),
|
|
258
|
+
}
|
|
259
|
+
),
|
|
260
|
+
).returns(True)
|
|
261
|
+
|
|
262
|
+
assert bus.publish(
|
|
263
|
+
topic="orders.events.completed",
|
|
264
|
+
headers={
|
|
265
|
+
"x-correlation-id": "12345678-1234-4234-8234-123456789abc",
|
|
266
|
+
"x-origin-service": "checkout-service",
|
|
267
|
+
"x-extra": "ignored",
|
|
268
|
+
},
|
|
269
|
+
payload={
|
|
270
|
+
"order_id": 884,
|
|
271
|
+
"items": [
|
|
272
|
+
{"sku": "SKU-BBB", "qty": 2, "note": "second"},
|
|
273
|
+
{"sku": "SKU-AAA", "qty": 1},
|
|
274
|
+
],
|
|
275
|
+
"currency": "USD",
|
|
276
|
+
},
|
|
277
|
+
)
|
|
278
|
+
bus.verify()
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
**dmock** also supports pass-through spies using the same declarative DSL:
|
|
282
|
+
|
|
283
|
+
```python
|
|
284
|
+
from dmock import Check, DeclarativeSpy
|
|
285
|
+
|
|
286
|
+
class Store:
|
|
287
|
+
def __init__(self) -> None:
|
|
288
|
+
self.items: dict[str, str] = {}
|
|
289
|
+
self.dirty = True
|
|
290
|
+
|
|
291
|
+
def save(self, key: str, value: str) -> bool:
|
|
292
|
+
self.items[key] = value
|
|
293
|
+
self.dirty = False
|
|
294
|
+
return True
|
|
295
|
+
|
|
296
|
+
def fetch(self, key: str) -> str:
|
|
297
|
+
return self.items[key]
|
|
298
|
+
|
|
299
|
+
store = Store()
|
|
300
|
+
# dspy(store) is a shorthand for DeclarativeSpy(store)
|
|
301
|
+
spy = DeclarativeSpy(store)
|
|
302
|
+
|
|
303
|
+
# Real methods still execute on store; unhooked attributes delegate directly
|
|
304
|
+
(
|
|
305
|
+
spy.observe(Store.save, "a", "A")
|
|
306
|
+
.returns(
|
|
307
|
+
True,
|
|
308
|
+
# Check verifies external state right after the real call returns
|
|
309
|
+
condition=Check[bool](
|
|
310
|
+
lambda _: store.items.get("a") == "A",
|
|
311
|
+
lambda _: not store.dirty,
|
|
312
|
+
),
|
|
313
|
+
)
|
|
314
|
+
.once()
|
|
315
|
+
# Chaining .observe(...) enforces call order, just like .expect(...)
|
|
316
|
+
.observe(Store.fetch, "a")
|
|
317
|
+
.returns("A")
|
|
318
|
+
.once()
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
assert spy.save("a", "A") is True
|
|
322
|
+
assert spy.fetch("a") == "A"
|
|
323
|
+
spy.verify()
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
**dmock** is built on `unittest.mock`, has zero runtime dependencies, and doesn't patch anything. Unregistered mock calls fail immediately. Nothing on live modules or instances is rewritten.
|
|
327
|
+
|
|
328
|
+
Look up the dmock source code and tests yourself, it's full of examples!
|
|
329
|
+
|
|
330
|
+
## Limitations & non-goals
|
|
331
|
+
|
|
332
|
+
- **No signature binding at runtime.** `expect("method", …)` and `observe("method", …)` check that `method` exists on the spec or object, not that the argument list matches the real signature at runtime.
|
|
333
|
+
- **No automatic** `verify()` **outside pytest.** The pytest plugin checks every mock and spy when the test finishes. Other runners still need an explicit `verify()`.
|
|
334
|
+
- **No global patching.** The library does not patch modules or instances. Construct a `DeclarativeMock` or wrap a live instance with `DeclarativeSpy` and pass it in.
|
|
335
|
+
- **Not thread-safe.** Concurrent use of one mock or spy from multiple threads is out of scope.
|
|
336
|
+
|
|
337
|
+
## Roadmap
|
|
338
|
+
|
|
339
|
+
Planned and under consideration for 0.6.0+:
|
|
340
|
+
|
|
341
|
+
- **Scoped patching & callable mocks** - `with DeclarativePatch(...)` (with `dpatch(...)` as a shorthand) built on `unittest.mock.patch` for patching functions, class constructors, and module attributes with declarative expectations.
|
|
342
|
+
- **Partial mocking on spies** - `spy.mock("method", *args, **kwargs)` to override specific methods on a `DeclarativeSpy` without executing the real implementation.
|
|
343
|
+
- **Async observation checks** - `async def` predicates / `AsyncCheck` in `condition=` for `async def` methods on `DeclarativeSpy`.
|
|
344
|
+
- **Detailed argument mismatch diffs** - pinpoint which argument or nested matcher key failed inside `UnexpectedCallError` candidates.
|
|
345
|
+
- **Property observations on spies** - `spy.property(...)` to observe real property reads on `DeclarativeSpy`.
|
|
346
|
+
- **Context manager & generator shortcuts** - `with` / `async with` and `yield` already work by returning an explicit context manager or generator object from `.returns(...)` / `.runs(...)`, but have no dedicated DSL shortcuts yet.
|
|
347
|
+
- **Other test runners (low priority)** - unittest and similar runners do not verify mocks on teardown the way the pytest plugin does.
|
|
348
|
+
|
|
349
|
+
Other ideas belong in GitHub Issues.
|
|
350
|
+
|
|
351
|
+
## Development
|
|
352
|
+
|
|
353
|
+
```bash
|
|
354
|
+
poetry install
|
|
355
|
+
ruff check .
|
|
356
|
+
ruff format --check .
|
|
357
|
+
mypy src tests
|
|
358
|
+
pytest
|
|
359
|
+
coverage run -m pytest
|
|
360
|
+
coverage report
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
See **[CONTRIBUTING.md](CONTRIBUTING.md)** for setup, commits, and tests. Agents follow **[AGENTS.md](AGENTS.md)**.
|
|
364
|
+
|
|
365
|
+
## License
|
|
366
|
+
|
|
367
|
+
MIT
|
|
368
|
+
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+

|
|
2
|
+

|
|
3
|
+

|
|
4
|
+

|
|
5
|
+
|
|
6
|
+
# declarative-mocks
|
|
7
|
+
|
|
8
|
+
**Declare mock behavior as ordered expectations**. Write readable and maintainable tests with explicit call patterns, return sequences, and side effects using **dmock**.
|
|
9
|
+
|
|
10
|
+
It is fully documented. Public methods and matchers ship with docstring examples, and pretty much everything about API and behavior is described in [REFERENCE.md](REFERENCE.md) and [SPEC.md](SPEC.md).
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pip install declarative-mocks
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
_dmock_ requires Python 3.11+.
|
|
19
|
+
|
|
20
|
+
## Usage
|
|
21
|
+
|
|
22
|
+
Normally you would set a return value, then check the object field by field and assert the call separately:
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from datetime import datetime
|
|
27
|
+
from unittest.mock import Mock
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class User:
|
|
31
|
+
id: int
|
|
32
|
+
name: str
|
|
33
|
+
email: str
|
|
34
|
+
created_at: datetime = field(default_factory=datetime.now)
|
|
35
|
+
|
|
36
|
+
class Directory:
|
|
37
|
+
def lookup(self, name: str) -> User: ...
|
|
38
|
+
|
|
39
|
+
service = Mock(spec=Directory)
|
|
40
|
+
service.lookup.return_value = User(id=1, name="Ada", email="ada@example.com")
|
|
41
|
+
|
|
42
|
+
user = service.lookup("ada")
|
|
43
|
+
assert user.id == 1
|
|
44
|
+
assert user.name == "Ada"
|
|
45
|
+
assert user.email == "ada@example.com"
|
|
46
|
+
assert abs((datetime.now() - user.created_at).total_seconds()) < 5
|
|
47
|
+
name = service.lookup.call_args.args[0]
|
|
48
|
+
assert isinstance(name, str)
|
|
49
|
+
assert name.startswith("a")
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Here's an example of how **dmock** improves your tests:
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from dmock import DeclarativeMock, IsNow, StartsWith
|
|
56
|
+
|
|
57
|
+
service = DeclarativeMock(Directory)
|
|
58
|
+
service.expect(Directory.lookup, StartsWith("a")).returns(
|
|
59
|
+
User(id=1, name="Ada", email="ada@example.com")
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
assert service.lookup("ada") == User(
|
|
63
|
+
id=1,
|
|
64
|
+
name="Ada",
|
|
65
|
+
email="ada@example.com",
|
|
66
|
+
created_at=IsNow(),
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
# verify is automatic with pytest
|
|
70
|
+
service.verify()
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
That's not all! **dmock** can do so much more than that, for example:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from dmock import DeclarativeMock
|
|
77
|
+
|
|
78
|
+
# dmock(ApiClient) is a shorthand for DeclarativeMock(ApiClient)
|
|
79
|
+
api = DeclarativeMock(ApiClient)
|
|
80
|
+
|
|
81
|
+
# Use a method reference to help type checkers validate expected arguments
|
|
82
|
+
# and the values passed to .returns() and .runs()
|
|
83
|
+
api.expect(ApiClient.next_page).returns({"items": [1]}).returns({"items": [2]})
|
|
84
|
+
# Or use the string form to produce a lenient expectation without static type checking
|
|
85
|
+
api.expect("next_page").raises(TimeoutError)
|
|
86
|
+
|
|
87
|
+
assert api.next_page() == {"items": [1]}
|
|
88
|
+
assert api.next_page() == {"items": [2]}
|
|
89
|
+
# Third call raises TimeoutError
|
|
90
|
+
|
|
91
|
+
# Successive outcomes apply to the next matching call, in order:
|
|
92
|
+
# first .runs(), then .returns()
|
|
93
|
+
calc = DeclarativeMock(Calculator)
|
|
94
|
+
calc.expect("price", 100).runs(lambda x: x - 1).returns(99)
|
|
95
|
+
assert calc.price(100) == 99 # computed by the lambda
|
|
96
|
+
assert calc.price(100) == 99 # returned by .returns(99)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Same args follow registration order; different args or methods match in any order unless explicitly linked:
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from dmock import DeclarativeMock, in_order
|
|
103
|
+
|
|
104
|
+
api = DeclarativeMock(ApiClient)
|
|
105
|
+
|
|
106
|
+
# Each call matches the first non-exhausted expectation with matching args:
|
|
107
|
+
# same args are consumed in registration order, different args match in any order
|
|
108
|
+
api.expect("fetch", 1).returns("one")
|
|
109
|
+
api.expect("fetch", 2).returns("two")
|
|
110
|
+
api.expect("fetch", 1).returns("one x2")
|
|
111
|
+
assert api.fetch(2) == "two"
|
|
112
|
+
assert api.fetch(1) == "one"
|
|
113
|
+
assert api.fetch(1) == "one x2"
|
|
114
|
+
|
|
115
|
+
# Chain .expect(...) to require strict order (close cannot be called before connect)
|
|
116
|
+
api.expect("connect").returns(True).once().expect("close").returns(None).once()
|
|
117
|
+
|
|
118
|
+
# Or link expectations explicitly with in_order(...)
|
|
119
|
+
cache = DeclarativeMock(Cache)
|
|
120
|
+
fetched = api.expect("fetch", 10).returns("data").once()
|
|
121
|
+
cached = cache.expect("set", 10, "data").once()
|
|
122
|
+
in_order(fetched, cached) # works across different mocks and spies
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Argument matching is strictly explicit; positional, keyword, and wildcard shapes are distinct and must match how the call is made:
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
from dmock import ANY_ARGS, ANY_KWARGS, Anything, DeclarativeMock
|
|
129
|
+
|
|
130
|
+
m = DeclarativeMock(Worker)
|
|
131
|
+
m.expect("run") # matches only a call with no arguments
|
|
132
|
+
m.expect("run", Anything()).returns(0) # matches any single positional argument
|
|
133
|
+
m.expect("run", job_id=123).returns("queued") # matches only when passed by keyword
|
|
134
|
+
# ANY_ARGS / ANY_KWARGS skip all positional / keyword checks, including none;
|
|
135
|
+
# use Anything() to match a specific position or keyword
|
|
136
|
+
m.expect("run", ANY_ARGS, ANY_KWARGS).returns(0)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Only one quantifier per expectation is allowed, and `verify()` checks the counts:
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
from dmock import DeclarativeMock
|
|
143
|
+
|
|
144
|
+
calc = DeclarativeMock(Calculator)
|
|
145
|
+
calc.expect("price", 100).returns(99).once()
|
|
146
|
+
assert calc.price(100) == 99
|
|
147
|
+
|
|
148
|
+
# repeat=2 queues "warmup" twice; because times(4) expects 4 calls,
|
|
149
|
+
# the last outcome ("ready") repeats for the remaining two calls
|
|
150
|
+
calc.expect("status").returns("warmup", repeat=2).returns("ready").times(4)
|
|
151
|
+
assert [calc.status() for _ in range(4)] == ["warmup", "warmup", "ready", "ready"]
|
|
152
|
+
|
|
153
|
+
calc.expect("price", 300).returns(99).between(1, 3)
|
|
154
|
+
assert calc.price(300) == 99
|
|
155
|
+
|
|
156
|
+
# Must not be called; any matching call raises UnexpectedCallError immediately
|
|
157
|
+
calc.expect("price", 400).never()
|
|
158
|
+
# Optional expectation: zero calls still pass verify()
|
|
159
|
+
calc.expect("price", 500).returns(0).maybe()
|
|
160
|
+
calc.verify()
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Async methods and properties use the same DSL:
|
|
164
|
+
|
|
165
|
+
```python
|
|
166
|
+
from dmock import Anything, DeclarativeMock
|
|
167
|
+
|
|
168
|
+
mock = DeclarativeMock(MyService)
|
|
169
|
+
|
|
170
|
+
# Stub attribute access directly (no call needed, not tracked by verify())
|
|
171
|
+
mock.property(MyService.timeout, 30)
|
|
172
|
+
assert mock.timeout == 30
|
|
173
|
+
|
|
174
|
+
# Async methods are detected automatically and awaited as usual
|
|
175
|
+
mock.expect(MyService.aprocess_order, Anything()).returns("ok")
|
|
176
|
+
assert await mock.aprocess_order(1) == "ok"
|
|
177
|
+
|
|
178
|
+
# runs() accepts both regular functions and async def callables
|
|
179
|
+
mock.expect(MyService.aprocess_order, Anything()).runs(
|
|
180
|
+
lambda order_id: f"sync-{order_id}"
|
|
181
|
+
)
|
|
182
|
+
assert await mock.aprocess_order(7) == "sync-7"
|
|
183
|
+
|
|
184
|
+
async def async_fn(order_id: int) -> str:
|
|
185
|
+
return f"async-{order_id}"
|
|
186
|
+
|
|
187
|
+
mock.expect(MyService.aprocess_order, Anything()).runs(async_fn)
|
|
188
|
+
assert await mock.aprocess_order(9) == "async-9"
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
The matcher set is rich enough that even the most complicated call stays as **one declarative expectation**:
|
|
192
|
+
|
|
193
|
+
```python
|
|
194
|
+
from dmock import (
|
|
195
|
+
AnyOrder,
|
|
196
|
+
DeclarativeMock,
|
|
197
|
+
GreaterThan,
|
|
198
|
+
HasLen,
|
|
199
|
+
IsUUID,
|
|
200
|
+
PartialMapping,
|
|
201
|
+
StartsWith,
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
bus = DeclarativeMock(EventBus)
|
|
205
|
+
bus.expect(
|
|
206
|
+
"publish",
|
|
207
|
+
topic=StartsWith("orders.events."),
|
|
208
|
+
# PartialMapping checks only the listed keys and ignores any extra ones
|
|
209
|
+
headers=PartialMapping(
|
|
210
|
+
{
|
|
211
|
+
"x-correlation-id": IsUUID(),
|
|
212
|
+
"x-origin-service": "checkout-service",
|
|
213
|
+
}
|
|
214
|
+
),
|
|
215
|
+
payload=PartialMapping(
|
|
216
|
+
{
|
|
217
|
+
"order_id": GreaterThan(0),
|
|
218
|
+
# Matchers compose with &, |, and ~
|
|
219
|
+
"items": (
|
|
220
|
+
HasLen(GreaterThan(0))
|
|
221
|
+
& AnyOrder(
|
|
222
|
+
[
|
|
223
|
+
PartialMapping({"sku": "SKU-AAA", "qty": 1}),
|
|
224
|
+
PartialMapping({"sku": "SKU-BBB", "qty": 2}),
|
|
225
|
+
]
|
|
226
|
+
)
|
|
227
|
+
),
|
|
228
|
+
}
|
|
229
|
+
),
|
|
230
|
+
).returns(True)
|
|
231
|
+
|
|
232
|
+
assert bus.publish(
|
|
233
|
+
topic="orders.events.completed",
|
|
234
|
+
headers={
|
|
235
|
+
"x-correlation-id": "12345678-1234-4234-8234-123456789abc",
|
|
236
|
+
"x-origin-service": "checkout-service",
|
|
237
|
+
"x-extra": "ignored",
|
|
238
|
+
},
|
|
239
|
+
payload={
|
|
240
|
+
"order_id": 884,
|
|
241
|
+
"items": [
|
|
242
|
+
{"sku": "SKU-BBB", "qty": 2, "note": "second"},
|
|
243
|
+
{"sku": "SKU-AAA", "qty": 1},
|
|
244
|
+
],
|
|
245
|
+
"currency": "USD",
|
|
246
|
+
},
|
|
247
|
+
)
|
|
248
|
+
bus.verify()
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
**dmock** also supports pass-through spies using the same declarative DSL:
|
|
252
|
+
|
|
253
|
+
```python
|
|
254
|
+
from dmock import Check, DeclarativeSpy
|
|
255
|
+
|
|
256
|
+
class Store:
|
|
257
|
+
def __init__(self) -> None:
|
|
258
|
+
self.items: dict[str, str] = {}
|
|
259
|
+
self.dirty = True
|
|
260
|
+
|
|
261
|
+
def save(self, key: str, value: str) -> bool:
|
|
262
|
+
self.items[key] = value
|
|
263
|
+
self.dirty = False
|
|
264
|
+
return True
|
|
265
|
+
|
|
266
|
+
def fetch(self, key: str) -> str:
|
|
267
|
+
return self.items[key]
|
|
268
|
+
|
|
269
|
+
store = Store()
|
|
270
|
+
# dspy(store) is a shorthand for DeclarativeSpy(store)
|
|
271
|
+
spy = DeclarativeSpy(store)
|
|
272
|
+
|
|
273
|
+
# Real methods still execute on store; unhooked attributes delegate directly
|
|
274
|
+
(
|
|
275
|
+
spy.observe(Store.save, "a", "A")
|
|
276
|
+
.returns(
|
|
277
|
+
True,
|
|
278
|
+
# Check verifies external state right after the real call returns
|
|
279
|
+
condition=Check[bool](
|
|
280
|
+
lambda _: store.items.get("a") == "A",
|
|
281
|
+
lambda _: not store.dirty,
|
|
282
|
+
),
|
|
283
|
+
)
|
|
284
|
+
.once()
|
|
285
|
+
# Chaining .observe(...) enforces call order, just like .expect(...)
|
|
286
|
+
.observe(Store.fetch, "a")
|
|
287
|
+
.returns("A")
|
|
288
|
+
.once()
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
assert spy.save("a", "A") is True
|
|
292
|
+
assert spy.fetch("a") == "A"
|
|
293
|
+
spy.verify()
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
**dmock** is built on `unittest.mock`, has zero runtime dependencies, and doesn't patch anything. Unregistered mock calls fail immediately. Nothing on live modules or instances is rewritten.
|
|
297
|
+
|
|
298
|
+
Look up the dmock source code and tests yourself, it's full of examples!
|
|
299
|
+
|
|
300
|
+
## Limitations & non-goals
|
|
301
|
+
|
|
302
|
+
- **No signature binding at runtime.** `expect("method", …)` and `observe("method", …)` check that `method` exists on the spec or object, not that the argument list matches the real signature at runtime.
|
|
303
|
+
- **No automatic** `verify()` **outside pytest.** The pytest plugin checks every mock and spy when the test finishes. Other runners still need an explicit `verify()`.
|
|
304
|
+
- **No global patching.** The library does not patch modules or instances. Construct a `DeclarativeMock` or wrap a live instance with `DeclarativeSpy` and pass it in.
|
|
305
|
+
- **Not thread-safe.** Concurrent use of one mock or spy from multiple threads is out of scope.
|
|
306
|
+
|
|
307
|
+
## Roadmap
|
|
308
|
+
|
|
309
|
+
Planned and under consideration for 0.6.0+:
|
|
310
|
+
|
|
311
|
+
- **Scoped patching & callable mocks** - `with DeclarativePatch(...)` (with `dpatch(...)` as a shorthand) built on `unittest.mock.patch` for patching functions, class constructors, and module attributes with declarative expectations.
|
|
312
|
+
- **Partial mocking on spies** - `spy.mock("method", *args, **kwargs)` to override specific methods on a `DeclarativeSpy` without executing the real implementation.
|
|
313
|
+
- **Async observation checks** - `async def` predicates / `AsyncCheck` in `condition=` for `async def` methods on `DeclarativeSpy`.
|
|
314
|
+
- **Detailed argument mismatch diffs** - pinpoint which argument or nested matcher key failed inside `UnexpectedCallError` candidates.
|
|
315
|
+
- **Property observations on spies** - `spy.property(...)` to observe real property reads on `DeclarativeSpy`.
|
|
316
|
+
- **Context manager & generator shortcuts** - `with` / `async with` and `yield` already work by returning an explicit context manager or generator object from `.returns(...)` / `.runs(...)`, but have no dedicated DSL shortcuts yet.
|
|
317
|
+
- **Other test runners (low priority)** - unittest and similar runners do not verify mocks on teardown the way the pytest plugin does.
|
|
318
|
+
|
|
319
|
+
Other ideas belong in GitHub Issues.
|
|
320
|
+
|
|
321
|
+
## Development
|
|
322
|
+
|
|
323
|
+
```bash
|
|
324
|
+
poetry install
|
|
325
|
+
ruff check .
|
|
326
|
+
ruff format --check .
|
|
327
|
+
mypy src tests
|
|
328
|
+
pytest
|
|
329
|
+
coverage run -m pytest
|
|
330
|
+
coverage report
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
See **[CONTRIBUTING.md](CONTRIBUTING.md)** for setup, commits, and tests. Agents follow **[AGENTS.md](AGENTS.md)**.
|
|
334
|
+
|
|
335
|
+
## License
|
|
336
|
+
|
|
337
|
+
MIT
|