declarative-mocks 0.4.0__tar.gz → 0.4.2__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: declarative-mocks
3
- Version: 0.4.0
3
+ Version: 0.4.2
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: ...
@@ -64,32 +69,37 @@ service = Mock(spec=Directory)
64
69
  service.lookup.return_value = User(id=1, name="Ada", email="ada@example.com")
65
70
 
66
71
  user = service.lookup("ada")
67
- assert isinstance(user.id, int)
68
- assert user.name.startswith("A")
69
- assert "@" in user.email
70
- service.lookup.assert_called_once_with("ada")
72
+ assert user.id == 1
73
+ assert user.name == "Ada"
74
+ assert user.email == "ada@example.com"
75
+ assert abs((datetime.now() - user.created_at).total_seconds()) < 5
76
+ name = service.lookup.call_args.args[0]
77
+ assert isinstance(name, str)
78
+ assert name.startswith("a")
71
79
  ```
72
80
 
73
- Here's an example of how _dmock_ improves your tests:
81
+ Here's an example of how **dmock** improves your tests:
74
82
 
75
83
  ```python
76
- from dmock import AnythingOfType, Contains, DeclarativeMock, StartsWith
84
+ from dmock import DeclarativeMock, IsNow, StartsWith
77
85
 
78
86
  service = DeclarativeMock(Directory)
79
- # Using `Directory.lookup` helps a type checker to checks the call arguments and the values passed to `.returns` and `.runs`
80
- service.expect(Directory.lookup, "ada").returns(User(id=1, name="Ada", email="ada@example.com"))
81
- # or you could use the string form to produce a lenient expectation: any arguments, any outcome
82
- # service.expect("lookup", "ada").returns(User(id=1, name="Ada", email="ada@example.com"))
87
+ service.expect(Directory.lookup, StartsWith("a")).returns(
88
+ User(id=1, name="Ada", email="ada@example.com")
89
+ )
83
90
 
84
91
  assert service.lookup("ada") == User(
85
- id=AnythingOfType(int),
86
- name=StartsWith("A"),
87
- email=Contains("@"),
92
+ id=1,
93
+ name="Ada",
94
+ email="ada@example.com",
95
+ created_at=IsNow(),
88
96
  )
97
+
98
+ # verify is automatic with pytest
89
99
  service.verify()
90
100
  ```
91
101
 
92
- That's not all! _dmock_ can do so much more than that, for example:
102
+ That's not all! **dmock** can do so much more than that, for example:
93
103
 
94
104
  Successive outcomes apply to the next matching call, in order:
95
105
 
@@ -97,7 +107,10 @@ Successive outcomes apply to the next matching call, in order:
97
107
  from dmock import DeclarativeMock
98
108
 
99
109
  api = DeclarativeMock(ApiClient)
100
- api.expect("next_page").returns({"items": [1], "cursor": "a"})
110
+ # Using `ApiClient.next_page` helps a type checker to check
111
+ # the `expect` arguments and the values passed to `.returns` and `.runs`
112
+ api.expect(ApiClient.next_page).returns({"items": [1], "cursor": "a"})
113
+ # or you could use the string form to produce a lenient expectation: any arguments, any outcome
101
114
  api.expect("next_page").returns({"items": [2], "cursor": None})
102
115
  # first call → first dict; second call → second dict
103
116
 
@@ -115,7 +128,7 @@ from dmock import Anything, DeclarativeMock
115
128
  m = DeclarativeMock(Worker)
116
129
  m.expect("run") # called with no arguments
117
130
  m.expect("run", Anything()).returns(0) # any single positional arg
118
- m.expect("run", job_id=123).returns("queued") # this keyword only
131
+ m.expect("run", job_id=123).returns("queued") # this is keyword only
119
132
  ```
120
133
 
121
134
  `ANY_ARGS` and `ANY_KWARGS` match any positional and keyword arguments, including none:
@@ -136,7 +149,7 @@ calc = DeclarativeMock(Calculator)
136
149
  calc.expect("price", 100).returns(99).once()
137
150
  assert calc.price(100) == 99
138
151
 
139
- calc.expect("price", 200).returns(99).times(3) # last outcome repeats for the extra calls
152
+ calc.expect("price", 200).returns(99, repeat=2).times(3) # last outcome repeats for the extra calls
140
153
  assert [calc.price(200) for _ in range(3)] == [99, 99, 99]
141
154
 
142
155
  calc.expect("price", 300).returns(99).between(1, 3)
@@ -158,15 +171,74 @@ assert await mock.aprocess_order(1) == "ok"
158
171
  mock.expect(MyService.aprocess_order, Anything()).runs(lambda order_id: f"sync-{order_id}")
159
172
  assert await mock.aprocess_order(7) == "sync-7"
160
173
 
161
-
162
174
  async def async_fn(order_id: int) -> str:
163
175
  return f"async-{order_id}"
164
176
 
165
-
166
177
  mock.expect(MyService.aprocess_order, Anything()).runs(async_fn)
167
178
  assert await mock.aprocess_order(9) == "async-9"
168
179
  ```
169
180
 
181
+ 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
+
183
+ ```python
184
+ from dmock import (
185
+ AnyOrder,
186
+ DeclarativeMock,
187
+ Equals,
188
+ GreaterThan,
189
+ HasLen,
190
+ IsUUID,
191
+ PartialMapping,
192
+ StartsWith,
193
+ )
194
+
195
+ class EventBus:
196
+ def publish(self, *, topic: str, headers: dict, payload: dict) -> bool: ...
197
+
198
+ bus = DeclarativeMock(EventBus)
199
+ bus.expect(
200
+ "publish",
201
+ topic=StartsWith("orders.events."),
202
+ headers=PartialMapping(
203
+ {
204
+ "x-correlation-id": IsUUID(),
205
+ "x-origin-service": Equals("checkout-service"),
206
+ }
207
+ ),
208
+ payload=PartialMapping(
209
+ {
210
+ "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
+ ]
217
+ ),
218
+ }
219
+ ),
220
+ ).returns(True)
221
+
222
+ assert bus.publish(
223
+ topic="orders.events.completed",
224
+ headers={
225
+ "x-correlation-id": "12345678-1234-4234-8234-123456789abc",
226
+ "x-origin-service": "checkout-service",
227
+ "x-extra": "ignored",
228
+ },
229
+ payload={
230
+ "order_id": 884,
231
+ "items": [
232
+ {"sku": "SKU-BBB", "qty": 2, "note": "second"},
233
+ {"sku": "SKU-AAA", "qty": 1},
234
+ ],
235
+ "currency": "USD",
236
+ },
237
+ )
238
+
239
+ bus.verify()
240
+ ```
241
+
170
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.
171
243
 
172
244
  Look up the dmock source code and tests yourself, it's full of examples!
@@ -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: ...
@@ -38,32 +40,37 @@ service = Mock(spec=Directory)
38
40
  service.lookup.return_value = User(id=1, name="Ada", email="ada@example.com")
39
41
 
40
42
  user = service.lookup("ada")
41
- assert isinstance(user.id, int)
42
- assert user.name.startswith("A")
43
- assert "@" in user.email
44
- service.lookup.assert_called_once_with("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")
45
50
  ```
46
51
 
47
- Here's an example of how _dmock_ improves your tests:
52
+ Here's an example of how **dmock** improves your tests:
48
53
 
49
54
  ```python
50
- from dmock import AnythingOfType, Contains, DeclarativeMock, StartsWith
55
+ from dmock import DeclarativeMock, IsNow, StartsWith
51
56
 
52
57
  service = DeclarativeMock(Directory)
53
- # Using `Directory.lookup` helps a type checker to checks the call arguments and the values passed to `.returns` and `.runs`
54
- service.expect(Directory.lookup, "ada").returns(User(id=1, name="Ada", email="ada@example.com"))
55
- # or you could use the string form to produce a lenient expectation: any arguments, any outcome
56
- # service.expect("lookup", "ada").returns(User(id=1, name="Ada", email="ada@example.com"))
58
+ service.expect(Directory.lookup, StartsWith("a")).returns(
59
+ User(id=1, name="Ada", email="ada@example.com")
60
+ )
57
61
 
58
62
  assert service.lookup("ada") == User(
59
- id=AnythingOfType(int),
60
- name=StartsWith("A"),
61
- email=Contains("@"),
63
+ id=1,
64
+ name="Ada",
65
+ email="ada@example.com",
66
+ created_at=IsNow(),
62
67
  )
68
+
69
+ # verify is automatic with pytest
63
70
  service.verify()
64
71
  ```
65
72
 
66
- That's not all! _dmock_ can do so much more than that, for example:
73
+ That's not all! **dmock** can do so much more than that, for example:
67
74
 
68
75
  Successive outcomes apply to the next matching call, in order:
69
76
 
@@ -71,7 +78,10 @@ Successive outcomes apply to the next matching call, in order:
71
78
  from dmock import DeclarativeMock
72
79
 
73
80
  api = DeclarativeMock(ApiClient)
74
- api.expect("next_page").returns({"items": [1], "cursor": "a"})
81
+ # Using `ApiClient.next_page` helps a type checker to check
82
+ # the `expect` arguments and the values passed to `.returns` and `.runs`
83
+ api.expect(ApiClient.next_page).returns({"items": [1], "cursor": "a"})
84
+ # or you could use the string form to produce a lenient expectation: any arguments, any outcome
75
85
  api.expect("next_page").returns({"items": [2], "cursor": None})
76
86
  # first call → first dict; second call → second dict
77
87
 
@@ -89,7 +99,7 @@ from dmock import Anything, DeclarativeMock
89
99
  m = DeclarativeMock(Worker)
90
100
  m.expect("run") # called with no arguments
91
101
  m.expect("run", Anything()).returns(0) # any single positional arg
92
- m.expect("run", job_id=123).returns("queued") # this keyword only
102
+ m.expect("run", job_id=123).returns("queued") # this is keyword only
93
103
  ```
94
104
 
95
105
  `ANY_ARGS` and `ANY_KWARGS` match any positional and keyword arguments, including none:
@@ -110,7 +120,7 @@ calc = DeclarativeMock(Calculator)
110
120
  calc.expect("price", 100).returns(99).once()
111
121
  assert calc.price(100) == 99
112
122
 
113
- calc.expect("price", 200).returns(99).times(3) # last outcome repeats for the extra calls
123
+ calc.expect("price", 200).returns(99, repeat=2).times(3) # last outcome repeats for the extra calls
114
124
  assert [calc.price(200) for _ in range(3)] == [99, 99, 99]
115
125
 
116
126
  calc.expect("price", 300).returns(99).between(1, 3)
@@ -132,15 +142,74 @@ assert await mock.aprocess_order(1) == "ok"
132
142
  mock.expect(MyService.aprocess_order, Anything()).runs(lambda order_id: f"sync-{order_id}")
133
143
  assert await mock.aprocess_order(7) == "sync-7"
134
144
 
135
-
136
145
  async def async_fn(order_id: int) -> str:
137
146
  return f"async-{order_id}"
138
147
 
139
-
140
148
  mock.expect(MyService.aprocess_order, Anything()).runs(async_fn)
141
149
  assert await mock.aprocess_order(9) == "async-9"
142
150
  ```
143
151
 
152
+ 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
+
154
+ ```python
155
+ from dmock import (
156
+ AnyOrder,
157
+ DeclarativeMock,
158
+ Equals,
159
+ GreaterThan,
160
+ HasLen,
161
+ IsUUID,
162
+ PartialMapping,
163
+ StartsWith,
164
+ )
165
+
166
+ class EventBus:
167
+ def publish(self, *, topic: str, headers: dict, payload: dict) -> bool: ...
168
+
169
+ bus = DeclarativeMock(EventBus)
170
+ bus.expect(
171
+ "publish",
172
+ topic=StartsWith("orders.events."),
173
+ headers=PartialMapping(
174
+ {
175
+ "x-correlation-id": IsUUID(),
176
+ "x-origin-service": Equals("checkout-service"),
177
+ }
178
+ ),
179
+ payload=PartialMapping(
180
+ {
181
+ "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
+ ]
188
+ ),
189
+ }
190
+ ),
191
+ ).returns(True)
192
+
193
+ assert bus.publish(
194
+ topic="orders.events.completed",
195
+ headers={
196
+ "x-correlation-id": "12345678-1234-4234-8234-123456789abc",
197
+ "x-origin-service": "checkout-service",
198
+ "x-extra": "ignored",
199
+ },
200
+ payload={
201
+ "order_id": 884,
202
+ "items": [
203
+ {"sku": "SKU-BBB", "qty": 2, "note": "second"},
204
+ {"sku": "SKU-AAA", "qty": 1},
205
+ ],
206
+ "currency": "USD",
207
+ },
208
+ )
209
+
210
+ bus.verify()
211
+ ```
212
+
144
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.
145
214
 
146
215
  Look up the dmock source code and tests yourself, it's full of examples!
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "declarative-mocks"
3
- version = "0.4.0"
3
+ version = "0.4.2"
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",
@@ -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.
@@ -467,10 +459,7 @@ class Expectation(Generic[P, R]):
467
459
  if len(args) != len(self._expected_args):
468
460
  return False
469
461
 
470
- if not all(
471
- _value_matches(e, a)
472
- for e, a in zip(self._expected_args, args, strict=True)
473
- ):
462
+ if not all(e == a for e, a in zip(self._expected_args, args, strict=True)):
474
463
  return False
475
464
 
476
465
  if not self._has_any_kwargs:
@@ -478,8 +467,7 @@ class Expectation(Generic[P, R]):
478
467
  return False
479
468
 
480
469
  if not all(
481
- _value_matches(self._expected_kwargs[k], kwargs[k])
482
- for k in self._expected_kwargs
470
+ self._expected_kwargs[k] == kwargs[k] for k in self._expected_kwargs
483
471
  ):
484
472
  return False
485
473
 
@@ -1,11 +1,20 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import dataclasses
3
4
  import math
4
5
  import re
5
6
  from abc import ABC, abstractmethod
6
- from collections.abc import Container, Sized
7
- from datetime import datetime
8
- from typing import TYPE_CHECKING, Protocol, SupportsFloat, TypeAlias
7
+ from collections.abc import Collection, Container, Mapping, Sequence, Set, Sized
8
+ from datetime import datetime, timedelta
9
+ from typing import (
10
+ TYPE_CHECKING,
11
+ Protocol,
12
+ SupportsFloat,
13
+ TypeAlias,
14
+ cast,
15
+ overload,
16
+ )
17
+ from uuid import UUID
9
18
 
10
19
 
11
20
  if TYPE_CHECKING:
@@ -342,28 +351,64 @@ class AnythingOfType(Matcher):
342
351
  """Matches a value that is an instance of the given type.
343
352
 
344
353
  Args:
345
- expected_type: Type accepted by ``isinstance``.
354
+ expected: Type accepted by ``isinstance``.
355
+ exact: When True, the value's type must be `expected` itself.
346
356
 
347
357
  Examples:
348
358
  >>> from dmock import AnythingOfType, DeclarativeMock
359
+ >>> True == AnythingOfType(int)
360
+ True
361
+ >>> True == AnythingOfType(int, exact=True)
362
+ False
349
363
  >>> class Service:
350
364
  ... def fetch(self, key: str) -> str: ...
351
365
  >>> mock = DeclarativeMock(Service)
352
366
  >>> mock.expect("fetch", AnythingOfType(str)).returns("ok")
353
- Expectation(fetch(AnythingOfType(str)))
367
+ Expectation(fetch(AnythingOfType(str, exact=False)))
354
368
  >>> mock.fetch("a")
355
369
  'ok'
356
370
  """
357
371
 
358
- def __init__(self, expected_type: type, /) -> None:
359
- self._expected_type = expected_type
372
+ def __init__(self, expected: type, /, *, exact: bool = False) -> None:
373
+ self._expected = expected
374
+ self._exact = exact
360
375
 
361
376
  def matches(self, value: object, /) -> bool:
362
377
  """Return whether `value` is an instance of the expected type."""
363
- return isinstance(value, self._expected_type)
378
+ return (
379
+ type(value) is self._expected
380
+ if self._exact
381
+ else isinstance(value, self._expected)
382
+ )
364
383
 
365
384
  def __repr__(self) -> str:
366
- return f"AnythingOfType({self._expected_type.__name__})"
385
+ return f"AnythingOfType({self._expected.__name__}, exact={self._exact})"
386
+
387
+
388
+ InstanceOf = AnythingOfType
389
+ """Alias of :class:`AnythingOfType`.
390
+
391
+ ``InstanceOf(expected)`` constructs that matcher. ``exact`` defaults to
392
+ False, so a subclass matches. ``exact=True`` requires
393
+ ``type(value) is expected``.
394
+
395
+ Examples:
396
+ >>> from dmock import AnythingOfType, InstanceOf
397
+ >>> InstanceOf is AnythingOfType
398
+ True
399
+ >>> True == InstanceOf(int)
400
+ True
401
+ >>> True == InstanceOf(int, exact=True)
402
+ False
403
+ >>> class Base:
404
+ ... pass
405
+ >>> class Child(Base):
406
+ ... pass
407
+ >>> Child() == InstanceOf(Base)
408
+ True
409
+ >>> Child() == InstanceOf(Base, exact=True)
410
+ False
411
+ """
367
412
 
368
413
 
369
414
  class Equals(Matcher):
@@ -624,6 +669,44 @@ class Empty(Matcher):
624
669
  EMPTY = Empty()
625
670
 
626
671
 
672
+ class HasLen(Matcher):
673
+ """Matches a sized value whose length equals `expected`.
674
+
675
+ `expected` may be an integer or a :class:`Matcher` applied to ``len``.
676
+ A value that is not :class:`collections.abc.Sized` does not match.
677
+
678
+ Args:
679
+ expected: Length, or a matcher for the length.
680
+
681
+ Examples:
682
+ >>> from dmock import DeclarativeMock, GreaterThan, HasLen
683
+ >>> [1, 2, 3] == HasLen(3)
684
+ True
685
+ >>> [1] == HasLen(GreaterThan(2))
686
+ False
687
+ >>> class Service:
688
+ ... def fetch(self, items: list[int]) -> str: ...
689
+ >>> mock = DeclarativeMock(Service)
690
+ >>> mock.expect("fetch", HasLen(1)).returns("ok")
691
+ Expectation(fetch(HasLen(1)))
692
+ >>> mock.fetch([1])
693
+ 'ok'
694
+ """
695
+
696
+ def __init__(self, expected: int | Matcher, /) -> None:
697
+ self._expected = expected
698
+
699
+ def matches(self, value: object, /) -> bool:
700
+ """Return whether `value` has the expected length."""
701
+ if not isinstance(value, Sized):
702
+ return False
703
+
704
+ return len(value) == self._expected
705
+
706
+ def __repr__(self) -> str:
707
+ return f"HasLen({self._expected!r})"
708
+
709
+
627
710
  class In(Matcher):
628
711
  """Matches a value that is a member of `expected`.
629
712
 
@@ -722,6 +805,322 @@ class Includes(Matcher):
722
805
  return f"Includes({', '.join(map(repr, self._items))})"
723
806
 
724
807
 
808
+ class CollectionOf(Matcher):
809
+ """Matches a sequence, set, or mapping of the same kind as `expected`.
810
+
811
+ Order matters for sequences. Sets and mappings ignore order. A different
812
+ kind does not match. Values of the same kind match when their elements
813
+ are equal, including when the concrete types differ.
814
+
815
+ ``str``, ``bytes``, ``bytearray``, ``memoryview``, and
816
+ :class:`collections.UserString` are sequences and are valid `expected`
817
+ values. They match any sequence of the same elements in the same order.
818
+ A ``str`` or :class:`collections.UserString` yields characters. ``bytes``,
819
+ ``bytearray``, and a ``memoryview`` of a bytes buffer yield integers, so
820
+ they match each other and a list of those integers.
821
+
822
+ Args:
823
+ expected: Sequence, set, or mapping to compare against.
824
+
825
+ Examples:
826
+ >>> from dmock import DeclarativeMock
827
+ >>> from dmock import CollectionOf
828
+ >>> (1, 2, 3) == CollectionOf([1, 2, 3])
829
+ True
830
+ >>> (1, 2, 3) == CollectionOf({1, 2, 3})
831
+ False
832
+ >>> "ab" == CollectionOf(["a", "b"])
833
+ True
834
+ >>> ["a", "b"] == CollectionOf("ab")
835
+ True
836
+ >>> b"ab" == CollectionOf(bytearray(b"ab"))
837
+ True
838
+ >>> [97, 98] == CollectionOf(b"ab")
839
+ True
840
+ >>> bytearray(b"ab") == CollectionOf(memoryview(b"ab"))
841
+ True
842
+ >>> from collections import UserString
843
+ >>> UserString("ab") == CollectionOf("ab")
844
+ True
845
+ >>> "ab" == CollectionOf(UserString("ab"))
846
+ True
847
+ >>> "ab" == CollectionOf(b"ab")
848
+ False
849
+ >>> class Service:
850
+ ... def fetch(self, items: tuple[int, ...]) -> str: ...
851
+ >>> mock = DeclarativeMock(Service)
852
+ >>> mock.expect("fetch", CollectionOf([1, 2, 3])).returns("ok")
853
+ Expectation(fetch(CollectionOf([1, 2, 3])))
854
+ >>> mock.fetch((1, 2, 3))
855
+ 'ok'
856
+ """
857
+
858
+ def __init__(self, expected: Collection[object], /) -> None:
859
+ self._expected = expected
860
+
861
+ def matches(self, value: object, /) -> bool: # noqa: PLR0911
862
+ """Return whether `value` has the same kind and the same contents."""
863
+ if not isinstance(value, Collection):
864
+ return False
865
+
866
+ value = cast("Collection[object]", value)
867
+ if len(value) != len(self._expected):
868
+ return False
869
+
870
+ if type(value) is type(self._expected):
871
+ return value == self._expected
872
+
873
+ if isinstance(value, Sequence) and isinstance(self._expected, Sequence):
874
+ return all(v == e for v, e in zip(value, self._expected, strict=True))
875
+
876
+ if isinstance(value, Set) and isinstance(self._expected, Set):
877
+ return all(v in self._expected for v in value)
878
+
879
+ if isinstance(value, Mapping) and isinstance(self._expected, Mapping):
880
+ value, self._expected = (
881
+ cast("Mapping[object, object]", value),
882
+ cast("Mapping[object, object]", self._expected),
883
+ )
884
+ return all(
885
+ k in self._expected and value[k] == self._expected[k] for k in value
886
+ )
887
+
888
+ return False
889
+
890
+ def __repr__(self) -> str:
891
+ return f"CollectionOf({self._expected!r})"
892
+
893
+
894
+ class AnyOrder(Matcher):
895
+ """Matches a collection that has the same items in any order.
896
+
897
+ Each expected item is paired with a distinct element. A matcher item is
898
+ compared with ``==``, so it is applied to that element. The collection
899
+ must have the same length. A ``str``, ``bytes``, ``bytearray``,
900
+ ``memoryview``, or :class:`collections.UserString` is a sequence of its
901
+ elements.
902
+
903
+ Args:
904
+ items: Expected items. A string is a sequence of characters.
905
+
906
+ Examples:
907
+ >>> from dmock import AnyOrder, DeclarativeMock
908
+ >>> [1, 2, 3] == AnyOrder([3, 1, 2])
909
+ True
910
+ >>> [1, 2] == AnyOrder([1, 2, 3])
911
+ False
912
+ >>> class Service:
913
+ ... def fetch(self, items: list[int]) -> str: ...
914
+ >>> mock = DeclarativeMock(Service)
915
+ >>> mock.expect("fetch", AnyOrder([1, 2])).returns("ok")
916
+ Expectation(fetch(AnyOrder([1, 2])))
917
+ >>> mock.fetch([2, 1])
918
+ 'ok'
919
+ """
920
+
921
+ def __init__(self, items: Collection[object], /) -> None:
922
+ self._items = items
923
+
924
+ def matches(self, value: object, /) -> bool:
925
+ """Return whether `value` has the same items in any order."""
926
+ if not isinstance(value, Collection):
927
+ return False
928
+
929
+ actual = list(cast("Collection[object]", value))
930
+ expected = list(self._items)
931
+ if len(actual) != len(expected):
932
+ return False
933
+
934
+ candidates = [
935
+ [index for index, candidate in enumerate(actual) if wanted == candidate]
936
+ for wanted in expected
937
+ ]
938
+ if any(not options for options in candidates):
939
+ return False
940
+
941
+ used = [False] * len(actual)
942
+
943
+ def assign(start: int) -> bool:
944
+ if start == len(expected):
945
+ return True
946
+
947
+ for index in candidates[start]:
948
+ if used[index]:
949
+ continue
950
+
951
+ used[index] = True
952
+ if assign(start + 1):
953
+ return True
954
+
955
+ used[index] = False
956
+
957
+ return False
958
+
959
+ return assign(0)
960
+
961
+ def __repr__(self) -> str:
962
+ return f"AnyOrder({list(self._items)!r})"
963
+
964
+
965
+ class SequenceOf(Matcher):
966
+ """Matches a sequence with the same elements in the same order.
967
+
968
+ A set or mapping does not match. ``str``, ``bytes``, ``bytearray``,
969
+ ``memoryview``, and :class:`collections.UserString` are sequences of
970
+ their elements, as with :class:`CollectionOf`.
971
+
972
+ Args:
973
+ expected: Sequence to compare against.
974
+
975
+ Examples:
976
+ >>> from dmock import DeclarativeMock, SequenceOf
977
+ >>> (1, 2) == SequenceOf([1, 2])
978
+ True
979
+ >>> "ab" == SequenceOf(["a", "b"])
980
+ True
981
+ >>> {1, 2} == SequenceOf([1, 2])
982
+ False
983
+ >>> class Service:
984
+ ... def fetch(self, items: tuple[int, ...]) -> str: ...
985
+ >>> mock = DeclarativeMock(Service)
986
+ >>> mock.expect("fetch", SequenceOf([1, 2])).returns("ok")
987
+ Expectation(fetch(SequenceOf([1, 2])))
988
+ >>> mock.fetch((1, 2))
989
+ 'ok'
990
+ """
991
+
992
+ def __init__(self, expected: Sequence[object], /) -> None:
993
+ self._expected = expected
994
+
995
+ def matches(self, value: object, /) -> bool:
996
+ """Return whether `value` is a sequence of the same elements."""
997
+ if not isinstance(value, Sequence):
998
+ return False
999
+
1000
+ return CollectionOf(self._expected).matches(cast("Sequence[object]", value))
1001
+
1002
+ def __repr__(self) -> str:
1003
+ return f"SequenceOf({self._expected!r})"
1004
+
1005
+
1006
+ class SetOf(Matcher):
1007
+ """Matches a set with the same elements.
1008
+
1009
+ Order is ignored. A sequence or mapping does not match.
1010
+
1011
+ Args:
1012
+ expected: Set to compare against.
1013
+
1014
+ Examples:
1015
+ >>> from dmock import DeclarativeMock, SetOf
1016
+ >>> frozenset({1, 2}) == SetOf({2, 1})
1017
+ True
1018
+ >>> [1, 2] == SetOf({1, 2})
1019
+ False
1020
+ >>> class Service:
1021
+ ... def fetch(self, items: set[int]) -> str: ...
1022
+ >>> mock = DeclarativeMock(Service)
1023
+ >>> mock.expect("fetch", SetOf({1, 2})).returns("ok")
1024
+ Expectation(fetch(SetOf({1, 2})))
1025
+ >>> mock.fetch({2, 1})
1026
+ 'ok'
1027
+ """
1028
+
1029
+ def __init__(self, expected: Set[object], /) -> None:
1030
+ self._expected = expected
1031
+
1032
+ def matches(self, value: object, /) -> bool:
1033
+ """Return whether `value` is a set of the same elements."""
1034
+ if not isinstance(value, Set):
1035
+ return False
1036
+
1037
+ return CollectionOf(self._expected).matches(cast("Set[object]", value))
1038
+
1039
+ def __repr__(self) -> str:
1040
+ return f"SetOf({self._expected!r})"
1041
+
1042
+
1043
+ class MappingOf(Matcher):
1044
+ """Matches a mapping with the same keys and values.
1045
+
1046
+ Key order is ignored. A sequence does not match. Extra keys do not match.
1047
+
1048
+ Args:
1049
+ expected: Mapping to compare against.
1050
+
1051
+ Examples:
1052
+ >>> from dmock import DeclarativeMock, MappingOf
1053
+ >>> {"b": 1, "a": 2} == MappingOf({"a": 2, "b": 1})
1054
+ True
1055
+ >>> {"a": 1, "b": 2} == MappingOf({"a": 1})
1056
+ False
1057
+ >>> class Service:
1058
+ ... def save(self, item: dict[str, int]) -> str: ...
1059
+ >>> mock = DeclarativeMock(Service)
1060
+ >>> mock.expect("save", MappingOf({"a": 1})).returns("ok")
1061
+ Expectation(save(MappingOf({'a': 1})))
1062
+ >>> mock.save({"a": 1})
1063
+ 'ok'
1064
+ """
1065
+
1066
+ def __init__(self, expected: Mapping[object, object], /) -> None:
1067
+ self._expected = expected
1068
+
1069
+ def matches(self, value: object, /) -> bool:
1070
+ """Return whether `value` is a mapping of the same pairs."""
1071
+ if not isinstance(value, Mapping):
1072
+ return False
1073
+
1074
+ return CollectionOf(self._expected).matches(
1075
+ cast("Mapping[object, object]", value)
1076
+ )
1077
+
1078
+ def __repr__(self) -> str:
1079
+ return f"MappingOf({self._expected!r})"
1080
+
1081
+
1082
+ class PartialMapping(Matcher):
1083
+ """Matches a mapping that contains every given pair.
1084
+
1085
+ Keys that are not listed are ignored. A value that is a :class:`Matcher`
1086
+ is applied to the mapped value. Other values use ``==``.
1087
+
1088
+ Args:
1089
+ expected: Pairs the mapping must contain.
1090
+
1091
+ Examples:
1092
+ >>> from dmock import DeclarativeMock, GreaterThan, PartialMapping
1093
+ >>> {"a": 1, "b": 2} == PartialMapping({"a": GreaterThan(0)})
1094
+ True
1095
+ >>> {"a": 1} == PartialMapping({"b": 1})
1096
+ False
1097
+ >>> class Service:
1098
+ ... def save(self, item: dict[str, int]) -> str: ...
1099
+ >>> mock = DeclarativeMock(Service)
1100
+ >>> mock.expect("save", PartialMapping({"status": "ok"})).returns("ok")
1101
+ Expectation(save(PartialMapping({'status': 'ok'})))
1102
+ >>> mock.save({"status": "ok", "id": 1})
1103
+ 'ok'
1104
+ """
1105
+
1106
+ def __init__(self, expected: Mapping[object, object], /) -> None:
1107
+ self._expected = expected
1108
+
1109
+ def matches(self, value: object, /) -> bool:
1110
+ """Return whether `value` contains every expected pair."""
1111
+ if not isinstance(value, Mapping):
1112
+ return False
1113
+
1114
+ value = cast("Mapping[object, object]", value)
1115
+ return all(
1116
+ key in value and expected == value[key]
1117
+ for key, expected in self._expected.items()
1118
+ )
1119
+
1120
+ def __repr__(self) -> str:
1121
+ return f"PartialMapping({self._expected!r})"
1122
+
1123
+
725
1124
  class Attr(Matcher):
726
1125
  """Matches an object that has an attribute named `attr`.
727
1126
 
@@ -1029,6 +1428,54 @@ class Approx(Matcher):
1029
1428
  )
1030
1429
 
1031
1430
 
1431
+ class IsNow(Matcher):
1432
+ """Matches a datetime close to the current time.
1433
+
1434
+ `tolerance` is a number of seconds or a :class:`datetime.timedelta`.
1435
+ The window is that wide on either side of now. A naive value is compared
1436
+ with :meth:`datetime.datetime.now`. An aware value is compared with
1437
+ ``datetime.now(value.tzinfo)``. A negative tolerance matches no datetime.
1438
+
1439
+ Args:
1440
+ tolerance: Half-width of the accepted window. Defaults to 5 seconds.
1441
+
1442
+ Examples:
1443
+ >>> from datetime import datetime, timezone
1444
+ >>> from dmock import DeclarativeMock, IsNow
1445
+ >>> datetime.now(timezone.utc) == IsNow()
1446
+ True
1447
+ >>> class Service:
1448
+ ... def save(self, at: datetime) -> str: ...
1449
+ >>> mock = DeclarativeMock(Service)
1450
+ >>> mock.expect("save", IsNow()).returns("ok")
1451
+ Expectation(save(IsNow(tolerance=5.0)))
1452
+ >>> mock.save(datetime.now(timezone.utc))
1453
+ 'ok'
1454
+ """
1455
+
1456
+ @overload
1457
+ def __init__(self, *, tolerance: timedelta = timedelta(seconds=5)) -> None: ...
1458
+ @overload
1459
+ def __init__(self, *, tolerance: SupportsFloat = 5.0) -> None: ...
1460
+
1461
+ def __init__(self, *, tolerance: SupportsFloat | timedelta = 5.0) -> None:
1462
+ if isinstance(tolerance, timedelta):
1463
+ self._tolerance = tolerance.total_seconds()
1464
+ else:
1465
+ self._tolerance = float(tolerance)
1466
+
1467
+ def matches(self, value: object, /) -> bool:
1468
+ """Return whether `value` is a datetime inside the window."""
1469
+ if not isinstance(value, datetime):
1470
+ return False
1471
+
1472
+ now = datetime.now(value.tzinfo)
1473
+ return abs((value - now).total_seconds()) <= self._tolerance
1474
+
1475
+ def __repr__(self) -> str:
1476
+ return f"IsNow(tolerance={self._tolerance!r})"
1477
+
1478
+
1032
1479
  class StartsWith(Matcher):
1033
1480
  """Matches a string that starts with `prefix`.
1034
1481
 
@@ -1213,6 +1660,136 @@ class RegexFullmatch(Matcher):
1213
1660
  return f"RegexFullmatch(expected={self._expected!r}, flags={self._flags!r})"
1214
1661
 
1215
1662
 
1663
+ class IsUUID(Matcher):
1664
+ """Matches a :class:`uuid.UUID` or a string that parses as one.
1665
+
1666
+ `version` is checked for a UUID object and for a parsed string. Omit it
1667
+ to accept any version.
1668
+
1669
+ Args:
1670
+ version: Required UUID version.
1671
+
1672
+ Examples:
1673
+ >>> from uuid import uuid4
1674
+ >>> from dmock import DeclarativeMock, IsUUID
1675
+ >>> uuid4() == IsUUID(version=4)
1676
+ True
1677
+ >>> "not-a-uuid" == IsUUID()
1678
+ False
1679
+ >>> class Service:
1680
+ ... def save(self, item_id: str) -> str: ...
1681
+ >>> mock = DeclarativeMock(Service)
1682
+ >>> mock.expect("save", IsUUID(version=4)).returns("ok")
1683
+ Expectation(save(IsUUID(version=4)))
1684
+ >>> mock.save(str(uuid4()))
1685
+ 'ok'
1686
+ """
1687
+
1688
+ def __init__(self, *, version: int | None = None) -> None:
1689
+ self._version = version
1690
+
1691
+ def matches(self, value: object, /) -> bool:
1692
+ """Return whether `value` is a UUID of the requested version."""
1693
+ if isinstance(value, UUID):
1694
+ return self._version is None or value.version == self._version
1695
+
1696
+ if not isinstance(value, str):
1697
+ return False
1698
+
1699
+ try:
1700
+ uid = UUID(value)
1701
+ except ValueError:
1702
+ return False
1703
+
1704
+ return self._version is None or uid.version == self._version
1705
+
1706
+ def __repr__(self) -> str:
1707
+ return f"IsUUID(version={self._version!r})"
1708
+
1709
+
1710
+ IS_UUID = IsUUID()
1711
+ """Matches any :class:`uuid.UUID` or a string that parses as one.
1712
+
1713
+ ``version`` is omitted, so any UUID version matches.
1714
+
1715
+ Examples:
1716
+ >>> from uuid import uuid4
1717
+ >>> from dmock import DeclarativeMock, IS_UUID
1718
+ >>> uuid4() == IS_UUID
1719
+ True
1720
+ >>> "not-a-uuid" == IS_UUID
1721
+ False
1722
+ >>> class Service:
1723
+ ... def save(self, item_id: str) -> str: ...
1724
+ >>> mock = DeclarativeMock(Service)
1725
+ >>> mock.expect("save", IS_UUID).returns("ok")
1726
+ Expectation(save(IsUUID(version=None)))
1727
+ >>> mock.save(str(uuid4()))
1728
+ 'ok'
1729
+ """
1730
+
1731
+
1732
+ class IsDataclass(Matcher):
1733
+ """Matches a dataclass instance, or a dataclass type.
1734
+
1735
+ Args:
1736
+ instance: When True, match an instance and reject a class. When False,
1737
+ match a dataclass class or instance.
1738
+
1739
+ Examples:
1740
+ >>> from dataclasses import dataclass
1741
+ >>> from dmock import DeclarativeMock, IsDataclass
1742
+ >>> @dataclass
1743
+ ... class Item:
1744
+ ... name: str
1745
+ >>> Item("n") == IsDataclass()
1746
+ True
1747
+ >>> class Service:
1748
+ ... def save(self, item: Item) -> str: ...
1749
+ >>> mock = DeclarativeMock(Service)
1750
+ >>> mock.expect("save", IsDataclass()).returns("ok")
1751
+ Expectation(save(IsDataclass(instance=True)))
1752
+ >>> mock.save(Item("n"))
1753
+ 'ok'
1754
+ """
1755
+
1756
+ def __init__(self, *, instance: bool = True) -> None:
1757
+ self._instance = instance
1758
+
1759
+ def matches(self, value: object, /) -> bool:
1760
+ """Return whether `value` is a dataclass instance or class."""
1761
+ if self._instance and isinstance(value, type):
1762
+ return False
1763
+
1764
+ return dataclasses.is_dataclass(value)
1765
+
1766
+ def __repr__(self) -> str:
1767
+ return f"IsDataclass(instance={self._instance})"
1768
+
1769
+
1770
+ IS_DATACLASS = IsDataclass()
1771
+ """Matches a dataclass instance only.
1772
+
1773
+ Examples:
1774
+ >>> from dataclasses import dataclass
1775
+ >>> from dmock import DeclarativeMock, IS_DATACLASS
1776
+ >>> @dataclass
1777
+ ... class Item:
1778
+ ... name: str
1779
+ >>> Item("n") == IS_DATACLASS
1780
+ True
1781
+ >>> Item == IS_DATACLASS
1782
+ False
1783
+ >>> class Service:
1784
+ ... def save(self, item: Item) -> str: ...
1785
+ >>> mock = DeclarativeMock(Service)
1786
+ >>> mock.expect("save", IS_DATACLASS).returns("ok")
1787
+ Expectation(save(IsDataclass(instance=True)))
1788
+ >>> mock.save(Item("n"))
1789
+ 'ok'
1790
+ """
1791
+
1792
+
1216
1793
  class Args(Matcher):
1217
1794
  """Shared constructor for :class:`And` and :class:`Or`.
1218
1795
 
@@ -50,10 +50,6 @@ class _ExpectationLookup:
50
50
  rejected: tuple[Expectation[..., object], ...]
51
51
 
52
52
 
53
- def _is_dunder(name: str) -> bool:
54
- return name.startswith("__") and name.endswith("__")
55
-
56
-
57
53
  _RESERVED_DSL_NAMES: frozenset[str] = frozenset({"expect", "property", "verify"})
58
54
 
59
55
 
@@ -326,7 +322,7 @@ class DeclarativeMock(Generic[T], _Base):
326
322
 
327
323
  def __getattr__(self, name: str) -> Any:
328
324
  mock_attr = getattr(self.__mock, name) # AttributeError if not on spec
329
- if _is_dunder(name):
325
+ if name.startswith("__") and name.endswith("__"):
330
326
  return mock_attr
331
327
 
332
328
  if name in self.__properties: