declarative-mocks 0.4.2__tar.gz → 0.5.0__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.
Files changed (20) hide show
  1. {declarative_mocks-0.4.2 → declarative_mocks-0.5.0}/PKG-INFO +79 -22
  2. {declarative_mocks-0.4.2 → declarative_mocks-0.5.0}/README.md +76 -20
  3. {declarative_mocks-0.4.2 → declarative_mocks-0.5.0}/pyproject.toml +3 -2
  4. declarative_mocks-0.5.0/src/dmock/__init__.py +26 -0
  5. declarative_mocks-0.5.0/src/dmock/_interaction.py +1784 -0
  6. {declarative_mocks-0.4.2 → declarative_mocks-0.5.0}/src/dmock/_mock.py +88 -29
  7. {declarative_mocks-0.4.2 → declarative_mocks-0.5.0}/src/dmock/_protocols.py +5 -3
  8. {declarative_mocks-0.4.2 → declarative_mocks-0.5.0}/src/dmock/_pytest_plugin.py +7 -6
  9. {declarative_mocks-0.4.2 → declarative_mocks-0.5.0}/src/dmock/_registry.py +55 -2
  10. declarative_mocks-0.5.0/src/dmock/_spy.py +513 -0
  11. {declarative_mocks-0.4.2 → declarative_mocks-0.5.0}/src/dmock/_types.py +34 -2
  12. declarative_mocks-0.5.0/src/dmock/checks/__init__.py +13 -0
  13. declarative_mocks-0.5.0/src/dmock/checks/_check.py +174 -0
  14. declarative_mocks-0.5.0/src/dmock/exceptions/__init__.py +20 -0
  15. {declarative_mocks-0.4.2/src/dmock → declarative_mocks-0.5.0/src/dmock/exceptions}/_exceptions.py +41 -18
  16. {declarative_mocks-0.4.2/src/dmock → declarative_mocks-0.5.0/src/dmock/matchers}/__init__.py +6 -26
  17. {declarative_mocks-0.4.2/src/dmock → declarative_mocks-0.5.0/src/dmock/matchers}/_matchers.py +265 -76
  18. declarative_mocks-0.4.2/src/dmock/_expectation.py +0 -553
  19. {declarative_mocks-0.4.2 → declarative_mocks-0.5.0}/LICENSE +0 -0
  20. {declarative_mocks-0.4.2 → declarative_mocks-0.5.0}/src/dmock/py.typed +0 -0
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: declarative-mocks
3
- Version: 0.4.2
3
+ Version: 0.5.0
4
4
  Summary: Declare mock behavior as ordered expectations. Simple, typed, gomock-inspired DSL over unittest.mock
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
7
- Keywords: mock,mocking,testing,unittest,pytest
7
+ Keywords: mock,mocking,spying,testing,unittest,pytest
8
8
  Author: Dimitry Churilov
9
9
  Author-email: d.mdx3r@gmail.com
10
10
  Requires-Python: >=3.11
@@ -19,6 +19,7 @@ Classifier: Programming Language :: Python :: 3.11
19
19
  Classifier: Programming Language :: Python :: 3.12
20
20
  Classifier: Programming Language :: Python :: 3.13
21
21
  Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3.15
22
23
  Classifier: Topic :: Software Development :: Testing
23
24
  Classifier: Topic :: Software Development :: Testing :: Mocking
24
25
  Classifier: Typing :: Typed
@@ -29,7 +30,7 @@ Description-Content-Type: text/markdown
29
30
 
30
31
  ![Checks](https://github.com/MDx3R/declarative-mocks/actions/workflows/ci.yml/badge.svg)
31
32
  ![PyPI](https://img.shields.io/pypi/v/declarative-mocks.svg)
32
- ![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)
33
+ ![Python 3.11+](https://img.shields.io/badge/python-3.11%20%7C%203.12%20%7C%203.13%20%7C%203.14%20%7C%203.15-blue.svg)
33
34
  ![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)
34
35
 
35
36
  # declarative-mocks
@@ -81,7 +82,8 @@ assert name.startswith("a")
81
82
  Here's an example of how **dmock** improves your tests:
82
83
 
83
84
  ```python
84
- from dmock import DeclarativeMock, IsNow, StartsWith
85
+ from dmock import DeclarativeMock
86
+ from dmock.matchers import IsNow, StartsWith
85
87
 
86
88
  service = DeclarativeMock(Directory)
87
89
  service.expect(Directory.lookup, StartsWith("a")).returns(
@@ -113,6 +115,9 @@ api.expect(ApiClient.next_page).returns({"items": [1], "cursor": "a"})
113
115
  # or you could use the string form to produce a lenient expectation: any arguments, any outcome
114
116
  api.expect("next_page").returns({"items": [2], "cursor": None})
115
117
  # first call → first dict; second call → second dict
118
+ # Same args → registration order; different args → matched by args.
119
+ # Chain .expect(...) or use in_order(...) to enforce strict order across different calls:
120
+ api.expect("next_page", limit=5).returns({"items": []}).once().expect("close").raises(TimeoutError)
116
121
 
117
122
  calc = DeclarativeMock(Calculator)
118
123
  calc.expect("price", 100).runs(lambda x: x - 1).returns(99)
@@ -123,7 +128,8 @@ assert calc.price(100) == 99 # from .returns(99)
123
128
  `expect(...)` with no further arguments matches a call with no arguments. A keyword matches only that keyword:
124
129
 
125
130
  ```python
126
- from dmock import Anything, DeclarativeMock
131
+ from dmock import DeclarativeMock
132
+ from dmock.matchers import Anything
127
133
 
128
134
  m = DeclarativeMock(Worker)
129
135
  m.expect("run") # called with no arguments
@@ -134,7 +140,8 @@ m.expect("run", job_id=123).returns("queued") # this is keyword only
134
140
  `ANY_ARGS` and `ANY_KWARGS` match any positional and keyword arguments, including none:
135
141
 
136
142
  ```python
137
- from dmock import ANY_ARGS, ANY_KWARGS, DeclarativeMock
143
+ from dmock import DeclarativeMock
144
+ from dmock.matchers import ANY_ARGS, ANY_KWARGS
138
145
 
139
146
  m = DeclarativeMock(Worker)
140
147
  m.expect("run", ANY_ARGS, ANY_KWARGS).returns(0) # any positional and keyword args, including none
@@ -162,13 +169,16 @@ calc.verify()
162
169
  Async methods use the same DSL. `runs()` accepts a sync or an async function:
163
170
 
164
171
  ```python
165
- from dmock import Anything, DeclarativeMock
172
+ from dmock import DeclarativeMock
173
+ from dmock.matchers import Anything
166
174
 
167
175
  mock = DeclarativeMock(MyService)
168
176
  mock.expect(MyService.aprocess_order, Anything()).returns("ok")
169
177
  assert await mock.aprocess_order(1) == "ok"
170
178
 
171
- mock.expect(MyService.aprocess_order, Anything()).runs(lambda order_id: f"sync-{order_id}")
179
+ mock.expect(MyService.aprocess_order, Anything()).runs(
180
+ lambda order_id: f"sync-{order_id}"
181
+ )
172
182
  assert await mock.aprocess_order(7) == "sync-7"
173
183
 
174
184
  async def async_fn(order_id: int) -> str:
@@ -181,9 +191,10 @@ assert await mock.aprocess_order(9) == "async-9"
181
191
  The matcher set is rich enough that even the most complicated call stays as **one declarative expectation**. Prefixes, partial mappings, lengths, order, and formats compose in place:
182
192
 
183
193
  ```python
184
- from dmock import (
194
+ from typing import Any
195
+ from dmock import DeclarativeMock
196
+ from dmock.matchers import (
185
197
  AnyOrder,
186
- DeclarativeMock,
187
198
  Equals,
188
199
  GreaterThan,
189
200
  HasLen,
@@ -193,7 +204,9 @@ from dmock import (
193
204
  )
194
205
 
195
206
  class EventBus:
196
- def publish(self, *, topic: str, headers: dict, payload: dict) -> bool: ...
207
+ def publish(
208
+ self, *, topic: str, headers: dict[str, Any], payload: dict[str, Any]
209
+ ) -> bool: ...
197
210
 
198
211
  bus = DeclarativeMock(EventBus)
199
212
  bus.expect(
@@ -208,12 +221,14 @@ bus.expect(
208
221
  payload=PartialMapping(
209
222
  {
210
223
  "order_id": GreaterThan(0),
211
- "items": HasLen(GreaterThan(0))
212
- & AnyOrder(
213
- [
214
- PartialMapping({"sku": "SKU-AAA", "qty": 1}),
215
- PartialMapping({"sku": "SKU-BBB", "qty": 2}),
216
- ]
224
+ "items": (
225
+ HasLen(GreaterThan(0))
226
+ & AnyOrder(
227
+ [
228
+ PartialMapping({"sku": "SKU-AAA", "qty": 1}),
229
+ PartialMapping({"sku": "SKU-BBB", "qty": 2}),
230
+ ]
231
+ )
217
232
  ),
218
233
  }
219
234
  ),
@@ -239,16 +254,58 @@ assert bus.publish(
239
254
  bus.verify()
240
255
  ```
241
256
 
242
- **dmock** is built on `unittest.mock`, has zero runtime dependencies, and doesn't patch anything. Unregistered calls fail immediately. Nothing on live modules or instances is rewritten.
257
+ **dmock** also supports pass-through spies using the same declarative DSL:
258
+
259
+ ```python
260
+ from dmock import DeclarativeSpy
261
+ from dmock.checks import Check
262
+
263
+ class Store:
264
+ def __init__(self) -> None:
265
+ self.items: dict[str, str] = {}
266
+ self.dirty = False
267
+
268
+ def save(self, key: str, value: str) -> bool:
269
+ self.items[key] = value
270
+ self.dirty = False
271
+ return True
272
+
273
+ def fetch(self, key: str) -> str:
274
+ return self.items[key]
275
+
276
+ store = Store()
277
+ spy = DeclarativeSpy(store)
278
+
279
+ (
280
+ spy.observe(Store.save, "a", "A")
281
+ .returns(
282
+ True,
283
+ condition=Check[bool](
284
+ lambda _: store.items.get("a") == "A",
285
+ lambda _: not store.dirty,
286
+ ),
287
+ )
288
+ .once()
289
+ .observe(Store.fetch, "a")
290
+ .returns("A")
291
+ .once()
292
+ )
293
+
294
+ assert spy.save("a", "A") is True
295
+ assert spy.fetch("a") == "A"
296
+ spy.verify()
297
+ ```
298
+
299
+ **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.
243
300
 
244
301
  Look up the dmock source code and tests yourself, it's full of examples!
245
302
 
246
303
  ## Limitations & non-goals
247
304
 
248
- - **No signature binding at runtime.** `expect("method", …)` checks that `method` exists on the spec, not that the argument list matches the real signature at runtime.
249
- - **No automatic** `verify()` **outside pytest.** The pytest plugin checks every mock when the test finishes. Other runners still need an explicit `verify()`.
250
- - **No spies and no patching.** The library does not wrap live objects, modules, or `sys.modules`. Just construct a `DeclarativeMock` and pass it in.
251
- - **Not thread-safe.** Concurrent use of one mock from multiple threads is out of scope.
305
+ - **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.
306
+ - **No automatic** `verify()` **outside pytest.** The pytest plugin checks every mock and spy when the test finishes. Other runners still need an explicit `verify()`.
307
+ - **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.
308
+ - **Not thread-safe.** Concurrent use of one mock or spy from multiple threads is out of scope.
252
309
 
253
310
  ## Roadmap
254
311
 
@@ -1,6 +1,6 @@
1
1
  ![Checks](https://github.com/MDx3R/declarative-mocks/actions/workflows/ci.yml/badge.svg)
2
2
  ![PyPI](https://img.shields.io/pypi/v/declarative-mocks.svg)
3
- ![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)
3
+ ![Python 3.11+](https://img.shields.io/badge/python-3.11%20%7C%203.12%20%7C%203.13%20%7C%203.14%20%7C%203.15-blue.svg)
4
4
  ![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)
5
5
 
6
6
  # declarative-mocks
@@ -52,7 +52,8 @@ assert name.startswith("a")
52
52
  Here's an example of how **dmock** improves your tests:
53
53
 
54
54
  ```python
55
- from dmock import DeclarativeMock, IsNow, StartsWith
55
+ from dmock import DeclarativeMock
56
+ from dmock.matchers import IsNow, StartsWith
56
57
 
57
58
  service = DeclarativeMock(Directory)
58
59
  service.expect(Directory.lookup, StartsWith("a")).returns(
@@ -84,6 +85,9 @@ api.expect(ApiClient.next_page).returns({"items": [1], "cursor": "a"})
84
85
  # or you could use the string form to produce a lenient expectation: any arguments, any outcome
85
86
  api.expect("next_page").returns({"items": [2], "cursor": None})
86
87
  # first call → first dict; second call → second dict
88
+ # Same args → registration order; different args → matched by args.
89
+ # Chain .expect(...) or use in_order(...) to enforce strict order across different calls:
90
+ api.expect("next_page", limit=5).returns({"items": []}).once().expect("close").raises(TimeoutError)
87
91
 
88
92
  calc = DeclarativeMock(Calculator)
89
93
  calc.expect("price", 100).runs(lambda x: x - 1).returns(99)
@@ -94,7 +98,8 @@ assert calc.price(100) == 99 # from .returns(99)
94
98
  `expect(...)` with no further arguments matches a call with no arguments. A keyword matches only that keyword:
95
99
 
96
100
  ```python
97
- from dmock import Anything, DeclarativeMock
101
+ from dmock import DeclarativeMock
102
+ from dmock.matchers import Anything
98
103
 
99
104
  m = DeclarativeMock(Worker)
100
105
  m.expect("run") # called with no arguments
@@ -105,7 +110,8 @@ m.expect("run", job_id=123).returns("queued") # this is keyword only
105
110
  `ANY_ARGS` and `ANY_KWARGS` match any positional and keyword arguments, including none:
106
111
 
107
112
  ```python
108
- from dmock import ANY_ARGS, ANY_KWARGS, DeclarativeMock
113
+ from dmock import DeclarativeMock
114
+ from dmock.matchers import ANY_ARGS, ANY_KWARGS
109
115
 
110
116
  m = DeclarativeMock(Worker)
111
117
  m.expect("run", ANY_ARGS, ANY_KWARGS).returns(0) # any positional and keyword args, including none
@@ -133,13 +139,16 @@ calc.verify()
133
139
  Async methods use the same DSL. `runs()` accepts a sync or an async function:
134
140
 
135
141
  ```python
136
- from dmock import Anything, DeclarativeMock
142
+ from dmock import DeclarativeMock
143
+ from dmock.matchers import Anything
137
144
 
138
145
  mock = DeclarativeMock(MyService)
139
146
  mock.expect(MyService.aprocess_order, Anything()).returns("ok")
140
147
  assert await mock.aprocess_order(1) == "ok"
141
148
 
142
- mock.expect(MyService.aprocess_order, Anything()).runs(lambda order_id: f"sync-{order_id}")
149
+ mock.expect(MyService.aprocess_order, Anything()).runs(
150
+ lambda order_id: f"sync-{order_id}"
151
+ )
143
152
  assert await mock.aprocess_order(7) == "sync-7"
144
153
 
145
154
  async def async_fn(order_id: int) -> str:
@@ -152,9 +161,10 @@ assert await mock.aprocess_order(9) == "async-9"
152
161
  The matcher set is rich enough that even the most complicated call stays as **one declarative expectation**. Prefixes, partial mappings, lengths, order, and formats compose in place:
153
162
 
154
163
  ```python
155
- from dmock import (
164
+ from typing import Any
165
+ from dmock import DeclarativeMock
166
+ from dmock.matchers import (
156
167
  AnyOrder,
157
- DeclarativeMock,
158
168
  Equals,
159
169
  GreaterThan,
160
170
  HasLen,
@@ -164,7 +174,9 @@ from dmock import (
164
174
  )
165
175
 
166
176
  class EventBus:
167
- def publish(self, *, topic: str, headers: dict, payload: dict) -> bool: ...
177
+ def publish(
178
+ self, *, topic: str, headers: dict[str, Any], payload: dict[str, Any]
179
+ ) -> bool: ...
168
180
 
169
181
  bus = DeclarativeMock(EventBus)
170
182
  bus.expect(
@@ -179,12 +191,14 @@ bus.expect(
179
191
  payload=PartialMapping(
180
192
  {
181
193
  "order_id": GreaterThan(0),
182
- "items": HasLen(GreaterThan(0))
183
- & AnyOrder(
184
- [
185
- PartialMapping({"sku": "SKU-AAA", "qty": 1}),
186
- PartialMapping({"sku": "SKU-BBB", "qty": 2}),
187
- ]
194
+ "items": (
195
+ HasLen(GreaterThan(0))
196
+ & AnyOrder(
197
+ [
198
+ PartialMapping({"sku": "SKU-AAA", "qty": 1}),
199
+ PartialMapping({"sku": "SKU-BBB", "qty": 2}),
200
+ ]
201
+ )
188
202
  ),
189
203
  }
190
204
  ),
@@ -210,16 +224,58 @@ assert bus.publish(
210
224
  bus.verify()
211
225
  ```
212
226
 
213
- **dmock** is built on `unittest.mock`, has zero runtime dependencies, and doesn't patch anything. Unregistered calls fail immediately. Nothing on live modules or instances is rewritten.
227
+ **dmock** also supports pass-through spies using the same declarative DSL:
228
+
229
+ ```python
230
+ from dmock import DeclarativeSpy
231
+ from dmock.checks import Check
232
+
233
+ class Store:
234
+ def __init__(self) -> None:
235
+ self.items: dict[str, str] = {}
236
+ self.dirty = False
237
+
238
+ def save(self, key: str, value: str) -> bool:
239
+ self.items[key] = value
240
+ self.dirty = False
241
+ return True
242
+
243
+ def fetch(self, key: str) -> str:
244
+ return self.items[key]
245
+
246
+ store = Store()
247
+ spy = DeclarativeSpy(store)
248
+
249
+ (
250
+ spy.observe(Store.save, "a", "A")
251
+ .returns(
252
+ True,
253
+ condition=Check[bool](
254
+ lambda _: store.items.get("a") == "A",
255
+ lambda _: not store.dirty,
256
+ ),
257
+ )
258
+ .once()
259
+ .observe(Store.fetch, "a")
260
+ .returns("A")
261
+ .once()
262
+ )
263
+
264
+ assert spy.save("a", "A") is True
265
+ assert spy.fetch("a") == "A"
266
+ spy.verify()
267
+ ```
268
+
269
+ **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.
214
270
 
215
271
  Look up the dmock source code and tests yourself, it's full of examples!
216
272
 
217
273
  ## Limitations & non-goals
218
274
 
219
- - **No signature binding at runtime.** `expect("method", …)` checks that `method` exists on the spec, not that the argument list matches the real signature at runtime.
220
- - **No automatic** `verify()` **outside pytest.** The pytest plugin checks every mock when the test finishes. Other runners still need an explicit `verify()`.
221
- - **No spies and no patching.** The library does not wrap live objects, modules, or `sys.modules`. Just construct a `DeclarativeMock` and pass it in.
222
- - **Not thread-safe.** Concurrent use of one mock from multiple threads is out of scope.
275
+ - **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.
276
+ - **No automatic** `verify()` **outside pytest.** The pytest plugin checks every mock and spy when the test finishes. Other runners still need an explicit `verify()`.
277
+ - **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.
278
+ - **Not thread-safe.** Concurrent use of one mock or spy from multiple threads is out of scope.
223
279
 
224
280
  ## Roadmap
225
281
 
@@ -1,13 +1,13 @@
1
1
  [project]
2
2
  name = "declarative-mocks"
3
- version = "0.4.2"
3
+ version = "0.5.0"
4
4
  description = "Declare mock behavior as ordered expectations. Simple, typed, gomock-inspired DSL over unittest.mock"
5
5
  authors = [{ name = "Dimitry Churilov", email = "d.mdx3r@gmail.com" }]
6
6
  license = "MIT"
7
7
  license-files = ["LICENSE"]
8
8
  readme = "README.md"
9
9
  requires-python = ">=3.11"
10
- keywords = ["mock", "mocking", "testing", "unittest", "pytest"]
10
+ keywords = ["mock", "mocking", "spying", "testing", "unittest", "pytest"]
11
11
  classifiers = [
12
12
  "Framework :: Pytest",
13
13
  "Intended Audience :: Developers",
@@ -20,6 +20,7 @@ classifiers = [
20
20
  "Programming Language :: Python :: 3.12",
21
21
  "Programming Language :: Python :: 3.13",
22
22
  "Programming Language :: Python :: 3.14",
23
+ "Programming Language :: Python :: 3.15",
23
24
  "Topic :: Software Development :: Testing",
24
25
  "Topic :: Software Development :: Testing :: Mocking",
25
26
  "Typing :: Typed",
@@ -0,0 +1,26 @@
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._interaction import Expectation, Observation, in_order
8
+ from dmock._mock import DeclarativeMock, dmock
9
+ from dmock._spy import DeclarativeSpy, dspy
10
+
11
+
12
+ try:
13
+ __version__ = version("declarative-mocks")
14
+ except PackageNotFoundError: # pragma: no cover
15
+ __version__ = "0.0.0+unknown"
16
+
17
+
18
+ __all__ = [
19
+ "DeclarativeMock",
20
+ "DeclarativeSpy",
21
+ "Expectation",
22
+ "Observation",
23
+ "dmock",
24
+ "dspy",
25
+ "in_order",
26
+ ]