declarative-mocks 0.3.0__tar.gz → 0.4.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.3.0 → declarative_mocks-0.4.1}/PKG-INFO +91 -21
- {declarative_mocks-0.3.0 → declarative_mocks-0.4.1}/README.md +87 -20
- {declarative_mocks-0.3.0 → declarative_mocks-0.4.1}/pyproject.toml +8 -2
- {declarative_mocks-0.3.0 → declarative_mocks-0.4.1}/src/dmock/__init__.py +26 -0
- {declarative_mocks-0.3.0 → declarative_mocks-0.4.1}/src/dmock/_expectation.py +40 -22
- {declarative_mocks-0.3.0 → declarative_mocks-0.4.1}/src/dmock/_matchers.py +587 -10
- {declarative_mocks-0.3.0 → declarative_mocks-0.4.1}/src/dmock/_mock.py +5 -5
- declarative_mocks-0.4.1/src/dmock/_pytest_plugin.py +47 -0
- declarative_mocks-0.4.1/src/dmock/_registry.py +66 -0
- {declarative_mocks-0.3.0 → declarative_mocks-0.4.1}/LICENSE +0 -0
- {declarative_mocks-0.3.0 → declarative_mocks-0.4.1}/src/dmock/_exceptions.py +0 -0
- {declarative_mocks-0.3.0 → declarative_mocks-0.4.1}/src/dmock/_protocols.py +0 -0
- {declarative_mocks-0.3.0 → declarative_mocks-0.4.1}/src/dmock/_types.py +0 -0
- {declarative_mocks-0.3.0 → declarative_mocks-0.4.1}/src/dmock/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: declarative-mocks
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.1
|
|
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
|
|
@@ -8,7 +8,10 @@ Keywords: mock,mocking,testing,unittest,pytest
|
|
|
8
8
|
Author: Dimitry Churilov
|
|
9
9
|
Author-email: d.mdx3r@gmail.com
|
|
10
10
|
Requires-Python: >=3.11
|
|
11
|
+
Classifier: Framework :: Pytest
|
|
11
12
|
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
15
|
Classifier: Operating System :: OS Independent
|
|
13
16
|
Classifier: Programming Language :: Python :: 3
|
|
14
17
|
Classifier: Programming Language :: Python :: 3 :: Only
|
|
@@ -48,7 +51,8 @@ _dmock_ requires Python 3.11+.
|
|
|
48
51
|
Normally you would set a return value, then check the object field by field and assert the call separately:
|
|
49
52
|
|
|
50
53
|
```python
|
|
51
|
-
from dataclasses import dataclass
|
|
54
|
+
from dataclasses import dataclass, field
|
|
55
|
+
from datetime import datetime
|
|
52
56
|
from unittest.mock import Mock
|
|
53
57
|
|
|
54
58
|
@dataclass
|
|
@@ -56,6 +60,7 @@ class User:
|
|
|
56
60
|
id: int
|
|
57
61
|
name: str
|
|
58
62
|
email: str
|
|
63
|
+
created_at: datetime = field(default_factory=datetime.now)
|
|
59
64
|
|
|
60
65
|
class Directory:
|
|
61
66
|
def lookup(self, name: str) -> User: ...
|
|
@@ -67,29 +72,32 @@ user = service.lookup("ada")
|
|
|
67
72
|
assert isinstance(user.id, int)
|
|
68
73
|
assert user.name.startswith("A")
|
|
69
74
|
assert "@" in user.email
|
|
75
|
+
assert abs((datetime.now() - user.created_at).total_seconds()) < 5
|
|
70
76
|
service.lookup.assert_called_once_with("ada")
|
|
71
77
|
```
|
|
72
78
|
|
|
73
|
-
Here's an example of how
|
|
79
|
+
Here's an example of how **dmock** improves your tests:
|
|
74
80
|
|
|
75
81
|
```python
|
|
76
|
-
from dmock import AnythingOfType, Contains, DeclarativeMock, StartsWith
|
|
82
|
+
from dmock import AnythingOfType, Contains, DeclarativeMock, IsNow, StartsWith
|
|
77
83
|
|
|
78
84
|
service = DeclarativeMock(Directory)
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
# service.expect("lookup", "ada").returns(User(id=1, name="Ada", email="ada@example.com"))
|
|
85
|
+
service.expect(Directory.lookup, StartsWith("a")).returns(
|
|
86
|
+
User(id=1, name="Ada", email="ada@example.com")
|
|
87
|
+
)
|
|
83
88
|
|
|
84
89
|
assert service.lookup("ada") == User(
|
|
85
|
-
id=
|
|
86
|
-
name=
|
|
87
|
-
email=
|
|
90
|
+
id=1,
|
|
91
|
+
name="Ada",
|
|
92
|
+
email="ada@example.com",
|
|
93
|
+
created_at=IsNow(),
|
|
88
94
|
)
|
|
95
|
+
|
|
96
|
+
# verify is automatic with pytest
|
|
89
97
|
service.verify()
|
|
90
98
|
```
|
|
91
99
|
|
|
92
|
-
That's not all!
|
|
100
|
+
That's not all! **dmock** can do so much more than that, for example:
|
|
93
101
|
|
|
94
102
|
Successive outcomes apply to the next matching call, in order:
|
|
95
103
|
|
|
@@ -97,7 +105,10 @@ Successive outcomes apply to the next matching call, in order:
|
|
|
97
105
|
from dmock import DeclarativeMock
|
|
98
106
|
|
|
99
107
|
api = DeclarativeMock(ApiClient)
|
|
100
|
-
|
|
108
|
+
# Using `ApiClient.next_page` helps a type checker to check
|
|
109
|
+
# the `expect` arguments and the values passed to `.returns` and `.runs`
|
|
110
|
+
api.expect(ApiClient.next_page).returns({"items": [1], "cursor": "a"})
|
|
111
|
+
# or you could use the string form to produce a lenient expectation: any arguments, any outcome
|
|
101
112
|
api.expect("next_page").returns({"items": [2], "cursor": None})
|
|
102
113
|
# first call → first dict; second call → second dict
|
|
103
114
|
|
|
@@ -115,7 +126,7 @@ from dmock import Anything, DeclarativeMock
|
|
|
115
126
|
m = DeclarativeMock(Worker)
|
|
116
127
|
m.expect("run") # called with no arguments
|
|
117
128
|
m.expect("run", Anything()).returns(0) # any single positional arg
|
|
118
|
-
m.expect("run", job_id=123).returns("queued") # this keyword only
|
|
129
|
+
m.expect("run", job_id=123).returns("queued") # this is keyword only
|
|
119
130
|
```
|
|
120
131
|
|
|
121
132
|
`ANY_ARGS` and `ANY_KWARGS` match any positional and keyword arguments, including none:
|
|
@@ -158,15 +169,74 @@ assert await mock.aprocess_order(1) == "ok"
|
|
|
158
169
|
mock.expect(MyService.aprocess_order, Anything()).runs(lambda order_id: f"sync-{order_id}")
|
|
159
170
|
assert await mock.aprocess_order(7) == "sync-7"
|
|
160
171
|
|
|
161
|
-
|
|
162
172
|
async def async_fn(order_id: int) -> str:
|
|
163
173
|
return f"async-{order_id}"
|
|
164
174
|
|
|
165
|
-
|
|
166
175
|
mock.expect(MyService.aprocess_order, Anything()).runs(async_fn)
|
|
167
176
|
assert await mock.aprocess_order(9) == "async-9"
|
|
168
177
|
```
|
|
169
178
|
|
|
179
|
+
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:
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
from dmock import (
|
|
183
|
+
AnyOrder,
|
|
184
|
+
DeclarativeMock,
|
|
185
|
+
Equals,
|
|
186
|
+
GreaterThan,
|
|
187
|
+
HasLen,
|
|
188
|
+
IsUUID,
|
|
189
|
+
PartialMapping,
|
|
190
|
+
StartsWith,
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
class EventBus:
|
|
194
|
+
def publish(self, *, topic: str, headers: dict, payload: dict) -> bool: ...
|
|
195
|
+
|
|
196
|
+
bus = DeclarativeMock(EventBus)
|
|
197
|
+
bus.expect(
|
|
198
|
+
"publish",
|
|
199
|
+
topic=StartsWith("orders.events."),
|
|
200
|
+
headers=PartialMapping(
|
|
201
|
+
{
|
|
202
|
+
"x-correlation-id": IsUUID(),
|
|
203
|
+
"x-origin-service": Equals("checkout-service"),
|
|
204
|
+
}
|
|
205
|
+
),
|
|
206
|
+
payload=PartialMapping(
|
|
207
|
+
{
|
|
208
|
+
"order_id": GreaterThan(0),
|
|
209
|
+
"items": HasLen(GreaterThan(0))
|
|
210
|
+
& AnyOrder(
|
|
211
|
+
[
|
|
212
|
+
PartialMapping({"sku": "SKU-AAA", "qty": 1}),
|
|
213
|
+
PartialMapping({"sku": "SKU-BBB", "qty": 2}),
|
|
214
|
+
]
|
|
215
|
+
),
|
|
216
|
+
}
|
|
217
|
+
),
|
|
218
|
+
).returns(True)
|
|
219
|
+
|
|
220
|
+
assert bus.publish(
|
|
221
|
+
topic="orders.events.completed",
|
|
222
|
+
headers={
|
|
223
|
+
"x-correlation-id": "12345678-1234-4234-8234-123456789abc",
|
|
224
|
+
"x-origin-service": "checkout-service",
|
|
225
|
+
"x-extra": "ignored",
|
|
226
|
+
},
|
|
227
|
+
payload={
|
|
228
|
+
"order_id": 884,
|
|
229
|
+
"items": [
|
|
230
|
+
{"sku": "SKU-BBB", "qty": 2, "note": "second"},
|
|
231
|
+
{"sku": "SKU-AAA", "qty": 1},
|
|
232
|
+
],
|
|
233
|
+
"currency": "USD",
|
|
234
|
+
},
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
bus.verify()
|
|
238
|
+
```
|
|
239
|
+
|
|
170
240
|
**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.
|
|
171
241
|
|
|
172
242
|
Look up the dmock source code and tests yourself, it's full of examples!
|
|
@@ -174,16 +244,15 @@ Look up the dmock source code and tests yourself, it's full of examples!
|
|
|
174
244
|
## Limitations & non-goals
|
|
175
245
|
|
|
176
246
|
- **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.
|
|
177
|
-
- **No automatic** `verify()
|
|
247
|
+
- **No automatic** `verify()` **outside pytest.** The pytest plugin checks every mock when the test finishes. Other runners still need an explicit `verify()`.
|
|
178
248
|
- **No spies and no patching.** The library does not wrap live objects, modules, or `sys.modules`. Just construct a `DeclarativeMock` and pass it in.
|
|
179
249
|
- **Not thread-safe.** Concurrent use of one mock from multiple threads is out of scope.
|
|
180
250
|
|
|
181
251
|
## Roadmap
|
|
182
252
|
|
|
183
|
-
|
|
253
|
+
Nothing is planned for 0.5.0, feel free to suggest!
|
|
184
254
|
|
|
185
|
-
- **
|
|
186
|
-
- **Per-outcome counts (maybe)** - repeat a `.returns()` / `.raises()` / `.runs()` without chaining it n times (today `.returns(1).returns(1).returns(1).returns(2)`).
|
|
255
|
+
- **Other test runners (low priority)** - unittest and similar runners do not verify mocks on teardown the way the pytest plugin does.
|
|
187
256
|
|
|
188
257
|
Other ideas belong in GitHub Issues.
|
|
189
258
|
|
|
@@ -195,7 +264,8 @@ ruff check .
|
|
|
195
264
|
ruff format --check .
|
|
196
265
|
mypy src tests
|
|
197
266
|
pytest
|
|
198
|
-
|
|
267
|
+
coverage run -m pytest
|
|
268
|
+
coverage report
|
|
199
269
|
```
|
|
200
270
|
|
|
201
271
|
See **[CONTRIBUTING.md](CONTRIBUTING.md)** for setup, commits, and tests. Agents follow **[AGENTS.md](AGENTS.md)**.
|
|
@@ -22,7 +22,8 @@ _dmock_ requires Python 3.11+.
|
|
|
22
22
|
Normally you would set a return value, then check the object field by field and assert the call separately:
|
|
23
23
|
|
|
24
24
|
```python
|
|
25
|
-
from dataclasses import dataclass
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from datetime import datetime
|
|
26
27
|
from unittest.mock import Mock
|
|
27
28
|
|
|
28
29
|
@dataclass
|
|
@@ -30,6 +31,7 @@ class User:
|
|
|
30
31
|
id: int
|
|
31
32
|
name: str
|
|
32
33
|
email: str
|
|
34
|
+
created_at: datetime = field(default_factory=datetime.now)
|
|
33
35
|
|
|
34
36
|
class Directory:
|
|
35
37
|
def lookup(self, name: str) -> User: ...
|
|
@@ -41,29 +43,32 @@ user = service.lookup("ada")
|
|
|
41
43
|
assert isinstance(user.id, int)
|
|
42
44
|
assert user.name.startswith("A")
|
|
43
45
|
assert "@" in user.email
|
|
46
|
+
assert abs((datetime.now() - user.created_at).total_seconds()) < 5
|
|
44
47
|
service.lookup.assert_called_once_with("ada")
|
|
45
48
|
```
|
|
46
49
|
|
|
47
|
-
Here's an example of how
|
|
50
|
+
Here's an example of how **dmock** improves your tests:
|
|
48
51
|
|
|
49
52
|
```python
|
|
50
|
-
from dmock import AnythingOfType, Contains, DeclarativeMock, StartsWith
|
|
53
|
+
from dmock import AnythingOfType, Contains, DeclarativeMock, IsNow, StartsWith
|
|
51
54
|
|
|
52
55
|
service = DeclarativeMock(Directory)
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
# service.expect("lookup", "ada").returns(User(id=1, name="Ada", email="ada@example.com"))
|
|
56
|
+
service.expect(Directory.lookup, StartsWith("a")).returns(
|
|
57
|
+
User(id=1, name="Ada", email="ada@example.com")
|
|
58
|
+
)
|
|
57
59
|
|
|
58
60
|
assert service.lookup("ada") == User(
|
|
59
|
-
id=
|
|
60
|
-
name=
|
|
61
|
-
email=
|
|
61
|
+
id=1,
|
|
62
|
+
name="Ada",
|
|
63
|
+
email="ada@example.com",
|
|
64
|
+
created_at=IsNow(),
|
|
62
65
|
)
|
|
66
|
+
|
|
67
|
+
# verify is automatic with pytest
|
|
63
68
|
service.verify()
|
|
64
69
|
```
|
|
65
70
|
|
|
66
|
-
That's not all!
|
|
71
|
+
That's not all! **dmock** can do so much more than that, for example:
|
|
67
72
|
|
|
68
73
|
Successive outcomes apply to the next matching call, in order:
|
|
69
74
|
|
|
@@ -71,7 +76,10 @@ Successive outcomes apply to the next matching call, in order:
|
|
|
71
76
|
from dmock import DeclarativeMock
|
|
72
77
|
|
|
73
78
|
api = DeclarativeMock(ApiClient)
|
|
74
|
-
|
|
79
|
+
# Using `ApiClient.next_page` helps a type checker to check
|
|
80
|
+
# the `expect` arguments and the values passed to `.returns` and `.runs`
|
|
81
|
+
api.expect(ApiClient.next_page).returns({"items": [1], "cursor": "a"})
|
|
82
|
+
# or you could use the string form to produce a lenient expectation: any arguments, any outcome
|
|
75
83
|
api.expect("next_page").returns({"items": [2], "cursor": None})
|
|
76
84
|
# first call → first dict; second call → second dict
|
|
77
85
|
|
|
@@ -89,7 +97,7 @@ from dmock import Anything, DeclarativeMock
|
|
|
89
97
|
m = DeclarativeMock(Worker)
|
|
90
98
|
m.expect("run") # called with no arguments
|
|
91
99
|
m.expect("run", Anything()).returns(0) # any single positional arg
|
|
92
|
-
m.expect("run", job_id=123).returns("queued") # this keyword only
|
|
100
|
+
m.expect("run", job_id=123).returns("queued") # this is keyword only
|
|
93
101
|
```
|
|
94
102
|
|
|
95
103
|
`ANY_ARGS` and `ANY_KWARGS` match any positional and keyword arguments, including none:
|
|
@@ -132,15 +140,74 @@ assert await mock.aprocess_order(1) == "ok"
|
|
|
132
140
|
mock.expect(MyService.aprocess_order, Anything()).runs(lambda order_id: f"sync-{order_id}")
|
|
133
141
|
assert await mock.aprocess_order(7) == "sync-7"
|
|
134
142
|
|
|
135
|
-
|
|
136
143
|
async def async_fn(order_id: int) -> str:
|
|
137
144
|
return f"async-{order_id}"
|
|
138
145
|
|
|
139
|
-
|
|
140
146
|
mock.expect(MyService.aprocess_order, Anything()).runs(async_fn)
|
|
141
147
|
assert await mock.aprocess_order(9) == "async-9"
|
|
142
148
|
```
|
|
143
149
|
|
|
150
|
+
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:
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
from dmock import (
|
|
154
|
+
AnyOrder,
|
|
155
|
+
DeclarativeMock,
|
|
156
|
+
Equals,
|
|
157
|
+
GreaterThan,
|
|
158
|
+
HasLen,
|
|
159
|
+
IsUUID,
|
|
160
|
+
PartialMapping,
|
|
161
|
+
StartsWith,
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
class EventBus:
|
|
165
|
+
def publish(self, *, topic: str, headers: dict, payload: dict) -> bool: ...
|
|
166
|
+
|
|
167
|
+
bus = DeclarativeMock(EventBus)
|
|
168
|
+
bus.expect(
|
|
169
|
+
"publish",
|
|
170
|
+
topic=StartsWith("orders.events."),
|
|
171
|
+
headers=PartialMapping(
|
|
172
|
+
{
|
|
173
|
+
"x-correlation-id": IsUUID(),
|
|
174
|
+
"x-origin-service": Equals("checkout-service"),
|
|
175
|
+
}
|
|
176
|
+
),
|
|
177
|
+
payload=PartialMapping(
|
|
178
|
+
{
|
|
179
|
+
"order_id": GreaterThan(0),
|
|
180
|
+
"items": HasLen(GreaterThan(0))
|
|
181
|
+
& AnyOrder(
|
|
182
|
+
[
|
|
183
|
+
PartialMapping({"sku": "SKU-AAA", "qty": 1}),
|
|
184
|
+
PartialMapping({"sku": "SKU-BBB", "qty": 2}),
|
|
185
|
+
]
|
|
186
|
+
),
|
|
187
|
+
}
|
|
188
|
+
),
|
|
189
|
+
).returns(True)
|
|
190
|
+
|
|
191
|
+
assert bus.publish(
|
|
192
|
+
topic="orders.events.completed",
|
|
193
|
+
headers={
|
|
194
|
+
"x-correlation-id": "12345678-1234-4234-8234-123456789abc",
|
|
195
|
+
"x-origin-service": "checkout-service",
|
|
196
|
+
"x-extra": "ignored",
|
|
197
|
+
},
|
|
198
|
+
payload={
|
|
199
|
+
"order_id": 884,
|
|
200
|
+
"items": [
|
|
201
|
+
{"sku": "SKU-BBB", "qty": 2, "note": "second"},
|
|
202
|
+
{"sku": "SKU-AAA", "qty": 1},
|
|
203
|
+
],
|
|
204
|
+
"currency": "USD",
|
|
205
|
+
},
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
bus.verify()
|
|
209
|
+
```
|
|
210
|
+
|
|
144
211
|
**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.
|
|
145
212
|
|
|
146
213
|
Look up the dmock source code and tests yourself, it's full of examples!
|
|
@@ -148,16 +215,15 @@ Look up the dmock source code and tests yourself, it's full of examples!
|
|
|
148
215
|
## Limitations & non-goals
|
|
149
216
|
|
|
150
217
|
- **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.
|
|
151
|
-
- **No automatic** `verify()
|
|
218
|
+
- **No automatic** `verify()` **outside pytest.** The pytest plugin checks every mock when the test finishes. Other runners still need an explicit `verify()`.
|
|
152
219
|
- **No spies and no patching.** The library does not wrap live objects, modules, or `sys.modules`. Just construct a `DeclarativeMock` and pass it in.
|
|
153
220
|
- **Not thread-safe.** Concurrent use of one mock from multiple threads is out of scope.
|
|
154
221
|
|
|
155
222
|
## Roadmap
|
|
156
223
|
|
|
157
|
-
|
|
224
|
+
Nothing is planned for 0.5.0, feel free to suggest!
|
|
158
225
|
|
|
159
|
-
- **
|
|
160
|
-
- **Per-outcome counts (maybe)** - repeat a `.returns()` / `.raises()` / `.runs()` without chaining it n times (today `.returns(1).returns(1).returns(1).returns(2)`).
|
|
226
|
+
- **Other test runners (low priority)** - unittest and similar runners do not verify mocks on teardown the way the pytest plugin does.
|
|
161
227
|
|
|
162
228
|
Other ideas belong in GitHub Issues.
|
|
163
229
|
|
|
@@ -169,7 +235,8 @@ ruff check .
|
|
|
169
235
|
ruff format --check .
|
|
170
236
|
mypy src tests
|
|
171
237
|
pytest
|
|
172
|
-
|
|
238
|
+
coverage run -m pytest
|
|
239
|
+
coverage report
|
|
173
240
|
```
|
|
174
241
|
|
|
175
242
|
See **[CONTRIBUTING.md](CONTRIBUTING.md)** for setup, commits, and tests. Agents follow **[AGENTS.md](AGENTS.md)**.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "declarative-mocks"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.4.1"
|
|
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"
|
|
@@ -9,7 +9,10 @@ readme = "README.md"
|
|
|
9
9
|
requires-python = ">=3.11"
|
|
10
10
|
keywords = ["mock", "mocking", "testing", "unittest", "pytest"]
|
|
11
11
|
classifiers = [
|
|
12
|
+
"Framework :: Pytest",
|
|
12
13
|
"Intended Audience :: Developers",
|
|
14
|
+
"License :: OSI Approved :: MIT License",
|
|
15
|
+
"Development Status :: 5 - Production/Stable",
|
|
13
16
|
"Operating System :: OS Independent",
|
|
14
17
|
"Programming Language :: Python :: 3",
|
|
15
18
|
"Programming Language :: Python :: 3 :: Only",
|
|
@@ -28,6 +31,9 @@ Homepage = "https://github.com/MDx3R/declarative-mocks"
|
|
|
28
31
|
Repository = "https://github.com/MDx3R/declarative-mocks"
|
|
29
32
|
Issues = "https://github.com/MDx3R/declarative-mocks/issues"
|
|
30
33
|
|
|
34
|
+
[project.entry-points.pytest11]
|
|
35
|
+
dmock = "dmock._pytest_plugin"
|
|
36
|
+
|
|
31
37
|
[tool.poetry]
|
|
32
38
|
packages = [{ include = "dmock", from = "src" }]
|
|
33
39
|
|
|
@@ -131,4 +137,4 @@ branch = true
|
|
|
131
137
|
[tool.coverage.report]
|
|
132
138
|
show_missing = true
|
|
133
139
|
fail_under = 90
|
|
134
|
-
exclude_lines = ["pragma: no cover", "if TYPE_CHECKING:"]
|
|
140
|
+
exclude_lines = ["pragma: no cover", "if TYPE_CHECKING:", "@overload"]
|
|
@@ -17,25 +17,35 @@ from dmock._matchers import (
|
|
|
17
17
|
AWARE_DATETIME,
|
|
18
18
|
EMPTY,
|
|
19
19
|
FALSY,
|
|
20
|
+
IS_DATACLASS,
|
|
21
|
+
IS_UUID,
|
|
20
22
|
NAIVE_DATETIME,
|
|
21
23
|
TRUTHY,
|
|
22
24
|
And,
|
|
25
|
+
AnyOrder,
|
|
23
26
|
Anything,
|
|
24
27
|
AnythingOfType,
|
|
25
28
|
Approx,
|
|
26
29
|
Args,
|
|
27
30
|
Attr,
|
|
31
|
+
CollectionOf,
|
|
28
32
|
Contains,
|
|
29
33
|
Empty,
|
|
30
34
|
EndsWith,
|
|
31
35
|
Equals,
|
|
32
36
|
GreaterEquals,
|
|
33
37
|
GreaterThan,
|
|
38
|
+
HasLen,
|
|
34
39
|
In,
|
|
35
40
|
Includes,
|
|
41
|
+
InstanceOf,
|
|
36
42
|
Is,
|
|
43
|
+
IsDataclass,
|
|
44
|
+
IsNow,
|
|
45
|
+
IsUUID,
|
|
37
46
|
LessEquals,
|
|
38
47
|
LessThan,
|
|
48
|
+
MappingOf,
|
|
39
49
|
MatchedBy,
|
|
40
50
|
Matcher,
|
|
41
51
|
Maybe,
|
|
@@ -43,11 +53,14 @@ from dmock._matchers import (
|
|
|
43
53
|
Not,
|
|
44
54
|
Nothing,
|
|
45
55
|
Or,
|
|
56
|
+
PartialMapping,
|
|
46
57
|
Range,
|
|
47
58
|
Regex,
|
|
48
59
|
RegexFullmatch,
|
|
49
60
|
RegexMatch,
|
|
50
61
|
RegexSearch,
|
|
62
|
+
SequenceOf,
|
|
63
|
+
SetOf,
|
|
51
64
|
StartsWith,
|
|
52
65
|
)
|
|
53
66
|
from dmock._mock import DeclarativeMock, dmock
|
|
@@ -65,14 +78,18 @@ __all__ = [
|
|
|
65
78
|
"AWARE_DATETIME",
|
|
66
79
|
"EMPTY",
|
|
67
80
|
"FALSY",
|
|
81
|
+
"IS_DATACLASS",
|
|
82
|
+
"IS_UUID",
|
|
68
83
|
"NAIVE_DATETIME",
|
|
69
84
|
"TRUTHY",
|
|
70
85
|
"And",
|
|
86
|
+
"AnyOrder",
|
|
71
87
|
"Anything",
|
|
72
88
|
"AnythingOfType",
|
|
73
89
|
"Approx",
|
|
74
90
|
"Args",
|
|
75
91
|
"Attr",
|
|
92
|
+
"CollectionOf",
|
|
76
93
|
"ConfigurationError",
|
|
77
94
|
"Contains",
|
|
78
95
|
"DeclarativeMock",
|
|
@@ -83,11 +100,17 @@ __all__ = [
|
|
|
83
100
|
"Expectation",
|
|
84
101
|
"GreaterEquals",
|
|
85
102
|
"GreaterThan",
|
|
103
|
+
"HasLen",
|
|
86
104
|
"In",
|
|
87
105
|
"Includes",
|
|
106
|
+
"InstanceOf",
|
|
88
107
|
"Is",
|
|
108
|
+
"IsDataclass",
|
|
109
|
+
"IsNow",
|
|
110
|
+
"IsUUID",
|
|
89
111
|
"LessEquals",
|
|
90
112
|
"LessThan",
|
|
113
|
+
"MappingOf",
|
|
91
114
|
"MatchedBy",
|
|
92
115
|
"Matcher",
|
|
93
116
|
"Maybe",
|
|
@@ -95,11 +118,14 @@ __all__ = [
|
|
|
95
118
|
"Not",
|
|
96
119
|
"Nothing",
|
|
97
120
|
"Or",
|
|
121
|
+
"PartialMapping",
|
|
98
122
|
"Range",
|
|
99
123
|
"Regex",
|
|
100
124
|
"RegexFullmatch",
|
|
101
125
|
"RegexMatch",
|
|
102
126
|
"RegexSearch",
|
|
127
|
+
"SequenceOf",
|
|
128
|
+
"SetOf",
|
|
103
129
|
"StartsWith",
|
|
104
130
|
"UnexpectedCallError",
|
|
105
131
|
"UnsatisfiedExpectationError",
|
|
@@ -5,7 +5,6 @@ from typing import TYPE_CHECKING, Generic, Self, final, overload
|
|
|
5
5
|
|
|
6
6
|
from dmock._exceptions import ConfigurationError, ExceededCallError
|
|
7
7
|
from dmock._matchers import (
|
|
8
|
-
Matcher,
|
|
9
8
|
_AnyArgsSentinel, # pyright: ignore[reportPrivateUsage]
|
|
10
9
|
_AnyKwargsSentinel, # pyright: ignore[reportPrivateUsage]
|
|
11
10
|
)
|
|
@@ -29,13 +28,6 @@ if TYPE_CHECKING:
|
|
|
29
28
|
from dmock._types import Outcome, Quantifier
|
|
30
29
|
|
|
31
30
|
|
|
32
|
-
def _value_matches(expected: object, actual: object) -> bool:
|
|
33
|
-
if isinstance(expected, Matcher):
|
|
34
|
-
return expected.matches(actual)
|
|
35
|
-
|
|
36
|
-
return expected == actual
|
|
37
|
-
|
|
38
|
-
|
|
39
31
|
@final
|
|
40
32
|
class Expectation(Generic[P, R]):
|
|
41
33
|
"""A single expected call: fluent builder for outcomes and quantifiers.
|
|
@@ -78,15 +70,20 @@ class Expectation(Generic[P, R]):
|
|
|
78
70
|
|
|
79
71
|
# -- Fluent outcome builders --
|
|
80
72
|
|
|
81
|
-
def returns(self, value: R) -> Self:
|
|
73
|
+
def returns(self, value: R, *, repeat: int = 1) -> Self:
|
|
82
74
|
"""Declare the return value for the next matching call.
|
|
83
75
|
|
|
84
76
|
Args:
|
|
85
77
|
value: Object returned as-is (tuples are not unpacked).
|
|
78
|
+
repeat: How many successive calls receive this outcome. Must be
|
|
79
|
+
at least 1.
|
|
86
80
|
|
|
87
81
|
Returns:
|
|
88
82
|
This expectation, for chaining.
|
|
89
83
|
|
|
84
|
+
Raises:
|
|
85
|
+
ConfigurationError: If `repeat` is less than 1.
|
|
86
|
+
|
|
90
87
|
Examples:
|
|
91
88
|
>>> from dmock import DeclarativeMock
|
|
92
89
|
>>> class Service:
|
|
@@ -97,18 +94,27 @@ class Expectation(Generic[P, R]):
|
|
|
97
94
|
>>> mock.fetch("a")
|
|
98
95
|
'A'
|
|
99
96
|
"""
|
|
100
|
-
self.
|
|
97
|
+
self._append_outcome(ReturnOutcome(value), repeat)
|
|
101
98
|
return self
|
|
102
99
|
|
|
103
|
-
def raises(
|
|
100
|
+
def raises(
|
|
101
|
+
self,
|
|
102
|
+
exc: BaseException | type[BaseException],
|
|
103
|
+
*,
|
|
104
|
+
repeat: int = 1,
|
|
105
|
+
) -> Self:
|
|
104
106
|
"""Declare that the next matching call raises `exc`.
|
|
105
107
|
|
|
106
108
|
Args:
|
|
107
109
|
exc: Exception instance, or a type instantiated with no arguments.
|
|
110
|
+
repeat: How many successive calls raise `exc`. Must be at least 1.
|
|
108
111
|
|
|
109
112
|
Returns:
|
|
110
113
|
This expectation, for chaining.
|
|
111
114
|
|
|
115
|
+
Raises:
|
|
116
|
+
ConfigurationError: If `repeat` is less than 1.
|
|
117
|
+
|
|
112
118
|
Examples:
|
|
113
119
|
>>> from dmock import DeclarativeMock
|
|
114
120
|
>>> class Service:
|
|
@@ -121,16 +127,16 @@ class Expectation(Generic[P, R]):
|
|
|
121
127
|
...
|
|
122
128
|
KeyError
|
|
123
129
|
"""
|
|
124
|
-
self.
|
|
130
|
+
self._append_outcome(RaiseOutcome(exc), repeat)
|
|
125
131
|
return self
|
|
126
132
|
|
|
127
133
|
@overload
|
|
128
|
-
def runs(self, func: Callable[P, R]) -> Self: ...
|
|
134
|
+
def runs(self, func: Callable[P, R], *, repeat: int = 1) -> Self: ...
|
|
129
135
|
|
|
130
136
|
@overload
|
|
131
|
-
def runs(self, func: Callable[P, Awaitable[R]]) -> Self: ...
|
|
137
|
+
def runs(self, func: Callable[P, Awaitable[R]], *, repeat: int = 1) -> Self: ...
|
|
132
138
|
|
|
133
|
-
def runs(self, func: Callable[P, R | Awaitable[R]]) -> Self:
|
|
139
|
+
def runs(self, func: Callable[P, R | Awaitable[R]], *, repeat: int = 1) -> Self:
|
|
134
140
|
"""Call `func` with the actual arguments for the next matching call.
|
|
135
141
|
|
|
136
142
|
The return value of `func` becomes the result of that call. Chaining
|
|
@@ -139,10 +145,14 @@ class Expectation(Generic[P, R]):
|
|
|
139
145
|
|
|
140
146
|
Args:
|
|
141
147
|
func: Called as ``func(*args, **kwargs)`` of the matching invocation.
|
|
148
|
+
repeat: How many successive calls invoke `func`. Must be at least 1.
|
|
142
149
|
|
|
143
150
|
Returns:
|
|
144
151
|
This expectation, for chaining.
|
|
145
152
|
|
|
153
|
+
Raises:
|
|
154
|
+
ConfigurationError: If `repeat` is less than 1.
|
|
155
|
+
|
|
146
156
|
Examples:
|
|
147
157
|
>>> from dmock import DeclarativeMock
|
|
148
158
|
>>> class Service:
|
|
@@ -161,9 +171,21 @@ class Expectation(Generic[P, R]):
|
|
|
161
171
|
>>> mock.fetch("a")
|
|
162
172
|
'from-returns'
|
|
163
173
|
"""
|
|
164
|
-
self.
|
|
174
|
+
self._append_outcome(RunOutcome(func), repeat)
|
|
165
175
|
return self
|
|
166
176
|
|
|
177
|
+
def _append_outcome(self, outcome: Outcome, repeat: int) -> None:
|
|
178
|
+
"""Append `outcome` once per `repeat`.
|
|
179
|
+
|
|
180
|
+
Raises:
|
|
181
|
+
ConfigurationError: If `repeat` is less than 1.
|
|
182
|
+
"""
|
|
183
|
+
if repeat < 1:
|
|
184
|
+
raise ConfigurationError(f"repeat requires repeat >= 1, got {repeat}.")
|
|
185
|
+
|
|
186
|
+
for _ in range(repeat):
|
|
187
|
+
self._outcomes.append(outcome)
|
|
188
|
+
|
|
167
189
|
# -- Fluent quantifiers --
|
|
168
190
|
|
|
169
191
|
def once(self) -> Self:
|
|
@@ -437,10 +459,7 @@ class Expectation(Generic[P, R]):
|
|
|
437
459
|
if len(args) != len(self._expected_args):
|
|
438
460
|
return False
|
|
439
461
|
|
|
440
|
-
if not all(
|
|
441
|
-
_value_matches(e, a)
|
|
442
|
-
for e, a in zip(self._expected_args, args, strict=True)
|
|
443
|
-
):
|
|
462
|
+
if not all(e == a for e, a in zip(self._expected_args, args, strict=True)):
|
|
444
463
|
return False
|
|
445
464
|
|
|
446
465
|
if not self._has_any_kwargs:
|
|
@@ -448,8 +467,7 @@ class Expectation(Generic[P, R]):
|
|
|
448
467
|
return False
|
|
449
468
|
|
|
450
469
|
if not all(
|
|
451
|
-
|
|
452
|
-
for k in self._expected_kwargs
|
|
470
|
+
self._expected_kwargs[k] == kwargs[k] for k in self._expected_kwargs
|
|
453
471
|
):
|
|
454
472
|
return False
|
|
455
473
|
|