declarative-mocks 0.1.1__tar.gz → 0.3.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.
@@ -0,0 +1,206 @@
1
+ Metadata-Version: 2.4
2
+ Name: declarative-mocks
3
+ Version: 0.3.0
4
+ Summary: Declare mock behavior as ordered expectations. Simple, typed, gomock-inspired DSL over unittest.mock
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Keywords: mock,mocking,testing,unittest,pytest
8
+ Author: Dimitry Churilov
9
+ Author-email: d.mdx3r@gmail.com
10
+ Requires-Python: >=3.11
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Software Development :: Testing
20
+ Classifier: Topic :: Software Development :: Testing :: Mocking
21
+ Classifier: Typing :: Typed
22
+ Project-URL: Homepage, https://github.com/MDx3R/declarative-mocks
23
+ Project-URL: Issues, https://github.com/MDx3R/declarative-mocks/issues
24
+ Project-URL: Repository, https://github.com/MDx3R/declarative-mocks
25
+ Description-Content-Type: text/markdown
26
+
27
+ ![Checks](https://github.com/MDx3R/declarative-mocks/actions/workflows/ci.yml/badge.svg)
28
+ ![PyPI](https://img.shields.io/pypi/v/declarative-mocks.svg)
29
+ ![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)
30
+ ![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)
31
+
32
+ # declarative-mocks
33
+
34
+ **Declare mock behavior as ordered expectations**. Write readable and maintainable tests with explicit call patterns, return sequences, and side effects using **dmock**.
35
+
36
+ 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).
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ pip install declarative-mocks
42
+ ```
43
+
44
+ _dmock_ requires Python 3.11+.
45
+
46
+ ## Usage
47
+
48
+ Normally you would set a return value, then check the object field by field and assert the call separately:
49
+
50
+ ```python
51
+ from dataclasses import dataclass
52
+ from unittest.mock import Mock
53
+
54
+ @dataclass
55
+ class User:
56
+ id: int
57
+ name: str
58
+ email: str
59
+
60
+ class Directory:
61
+ def lookup(self, name: str) -> User: ...
62
+
63
+ service = Mock(spec=Directory)
64
+ service.lookup.return_value = User(id=1, name="Ada", email="ada@example.com")
65
+
66
+ 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")
71
+ ```
72
+
73
+ Here's an example of how _dmock_ improves your tests:
74
+
75
+ ```python
76
+ from dmock import AnythingOfType, Contains, DeclarativeMock, StartsWith
77
+
78
+ 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"))
83
+
84
+ assert service.lookup("ada") == User(
85
+ id=AnythingOfType(int),
86
+ name=StartsWith("A"),
87
+ email=Contains("@"),
88
+ )
89
+ service.verify()
90
+ ```
91
+
92
+ That's not all! _dmock_ can do so much more than that, for example:
93
+
94
+ Successive outcomes apply to the next matching call, in order:
95
+
96
+ ```python
97
+ from dmock import DeclarativeMock
98
+
99
+ api = DeclarativeMock(ApiClient)
100
+ api.expect("next_page").returns({"items": [1], "cursor": "a"})
101
+ api.expect("next_page").returns({"items": [2], "cursor": None})
102
+ # first call → first dict; second call → second dict
103
+
104
+ calc = DeclarativeMock(Calculator)
105
+ calc.expect("price", 100).runs(lambda x: x - 1).returns(99)
106
+ assert calc.price(100) == 99 # from the lambda
107
+ assert calc.price(100) == 99 # from .returns(99)
108
+ ```
109
+
110
+ `expect(...)` with no further arguments matches a call with no arguments. A keyword matches only that keyword:
111
+
112
+ ```python
113
+ from dmock import Anything, DeclarativeMock
114
+
115
+ m = DeclarativeMock(Worker)
116
+ m.expect("run") # called with no arguments
117
+ m.expect("run", Anything()).returns(0) # any single positional arg
118
+ m.expect("run", job_id=123).returns("queued") # this keyword only
119
+ ```
120
+
121
+ `ANY_ARGS` and `ANY_KWARGS` match any positional and keyword arguments, including none:
122
+
123
+ ```python
124
+ from dmock import ANY_ARGS, ANY_KWARGS, DeclarativeMock
125
+
126
+ m = DeclarativeMock(Worker)
127
+ m.expect("run", ANY_ARGS, ANY_KWARGS).returns(0) # any positional and keyword args, including none
128
+ ```
129
+
130
+ Only one quantifier per expectation is allowed. The last outcome repeats when the count allows more calls, and `verify()` checks the counts:
131
+
132
+ ```python
133
+ from dmock import DeclarativeMock
134
+
135
+ calc = DeclarativeMock(Calculator)
136
+ calc.expect("price", 100).returns(99).once()
137
+ assert calc.price(100) == 99
138
+
139
+ calc.expect("price", 200).returns(99).times(3) # last outcome repeats for the extra calls
140
+ assert [calc.price(200) for _ in range(3)] == [99, 99, 99]
141
+
142
+ calc.expect("price", 300).returns(99).between(1, 3)
143
+ assert calc.price(300) == 99
144
+
145
+ calc.expect("price", 400).never()
146
+ calc.verify()
147
+ ```
148
+
149
+ Async methods use the same DSL. `runs()` accepts a sync or an async function:
150
+
151
+ ```python
152
+ from dmock import Anything, DeclarativeMock
153
+
154
+ mock = DeclarativeMock(MyService)
155
+ mock.expect(MyService.aprocess_order, Anything()).returns("ok")
156
+ assert await mock.aprocess_order(1) == "ok"
157
+
158
+ mock.expect(MyService.aprocess_order, Anything()).runs(lambda order_id: f"sync-{order_id}")
159
+ assert await mock.aprocess_order(7) == "sync-7"
160
+
161
+
162
+ async def async_fn(order_id: int) -> str:
163
+ return f"async-{order_id}"
164
+
165
+
166
+ mock.expect(MyService.aprocess_order, Anything()).runs(async_fn)
167
+ assert await mock.aprocess_order(9) == "async-9"
168
+ ```
169
+
170
+ **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
+
172
+ Look up the dmock source code and tests yourself, it's full of examples!
173
+
174
+ ## Limitations & non-goals
175
+
176
+ - **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()`. You call `verify()` yourself (a pytest hook is on the roadmap).
178
+ - **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
+ - **Not thread-safe.** Concurrent use of one mock from multiple threads is out of scope.
180
+
181
+ ## Roadmap
182
+
183
+ After 0.3.0, in no particular order:
184
+
185
+ - **pytest auto-**`verify()` - a plugin or fixture that runs `verify()` at the end of each test (gomock-style `Finish` on teardown), so you do not have to remember the call.
186
+ - **Per-outcome counts (maybe)** - repeat a `.returns()` / `.raises()` / `.runs()` without chaining it n times (today `.returns(1).returns(1).returns(1).returns(2)`).
187
+
188
+ Other ideas belong in GitHub Issues.
189
+
190
+ ## Development
191
+
192
+ ```bash
193
+ poetry install
194
+ ruff check .
195
+ ruff format --check .
196
+ mypy src tests
197
+ pytest
198
+ pytest --cov --cov-report=term-missing
199
+ ```
200
+
201
+ See **[CONTRIBUTING.md](CONTRIBUTING.md)** for setup, commits, and tests. Agents follow **[AGENTS.md](AGENTS.md)**.
202
+
203
+ ## License
204
+
205
+ MIT
206
+
@@ -0,0 +1,179 @@
1
+ ![Checks](https://github.com/MDx3R/declarative-mocks/actions/workflows/ci.yml/badge.svg)
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)
4
+ ![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)
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
26
+ from unittest.mock import Mock
27
+
28
+ @dataclass
29
+ class User:
30
+ id: int
31
+ name: str
32
+ email: str
33
+
34
+ class Directory:
35
+ def lookup(self, name: str) -> User: ...
36
+
37
+ service = Mock(spec=Directory)
38
+ service.lookup.return_value = User(id=1, name="Ada", email="ada@example.com")
39
+
40
+ 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")
45
+ ```
46
+
47
+ Here's an example of how _dmock_ improves your tests:
48
+
49
+ ```python
50
+ from dmock import AnythingOfType, Contains, DeclarativeMock, StartsWith
51
+
52
+ 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"))
57
+
58
+ assert service.lookup("ada") == User(
59
+ id=AnythingOfType(int),
60
+ name=StartsWith("A"),
61
+ email=Contains("@"),
62
+ )
63
+ service.verify()
64
+ ```
65
+
66
+ That's not all! _dmock_ can do so much more than that, for example:
67
+
68
+ Successive outcomes apply to the next matching call, in order:
69
+
70
+ ```python
71
+ from dmock import DeclarativeMock
72
+
73
+ api = DeclarativeMock(ApiClient)
74
+ api.expect("next_page").returns({"items": [1], "cursor": "a"})
75
+ api.expect("next_page").returns({"items": [2], "cursor": None})
76
+ # first call → first dict; second call → second dict
77
+
78
+ calc = DeclarativeMock(Calculator)
79
+ calc.expect("price", 100).runs(lambda x: x - 1).returns(99)
80
+ assert calc.price(100) == 99 # from the lambda
81
+ assert calc.price(100) == 99 # from .returns(99)
82
+ ```
83
+
84
+ `expect(...)` with no further arguments matches a call with no arguments. A keyword matches only that keyword:
85
+
86
+ ```python
87
+ from dmock import Anything, DeclarativeMock
88
+
89
+ m = DeclarativeMock(Worker)
90
+ m.expect("run") # called with no arguments
91
+ m.expect("run", Anything()).returns(0) # any single positional arg
92
+ m.expect("run", job_id=123).returns("queued") # this keyword only
93
+ ```
94
+
95
+ `ANY_ARGS` and `ANY_KWARGS` match any positional and keyword arguments, including none:
96
+
97
+ ```python
98
+ from dmock import ANY_ARGS, ANY_KWARGS, DeclarativeMock
99
+
100
+ m = DeclarativeMock(Worker)
101
+ m.expect("run", ANY_ARGS, ANY_KWARGS).returns(0) # any positional and keyword args, including none
102
+ ```
103
+
104
+ Only one quantifier per expectation is allowed. The last outcome repeats when the count allows more calls, and `verify()` checks the counts:
105
+
106
+ ```python
107
+ from dmock import DeclarativeMock
108
+
109
+ calc = DeclarativeMock(Calculator)
110
+ calc.expect("price", 100).returns(99).once()
111
+ assert calc.price(100) == 99
112
+
113
+ calc.expect("price", 200).returns(99).times(3) # last outcome repeats for the extra calls
114
+ assert [calc.price(200) for _ in range(3)] == [99, 99, 99]
115
+
116
+ calc.expect("price", 300).returns(99).between(1, 3)
117
+ assert calc.price(300) == 99
118
+
119
+ calc.expect("price", 400).never()
120
+ calc.verify()
121
+ ```
122
+
123
+ Async methods use the same DSL. `runs()` accepts a sync or an async function:
124
+
125
+ ```python
126
+ from dmock import Anything, DeclarativeMock
127
+
128
+ mock = DeclarativeMock(MyService)
129
+ mock.expect(MyService.aprocess_order, Anything()).returns("ok")
130
+ assert await mock.aprocess_order(1) == "ok"
131
+
132
+ mock.expect(MyService.aprocess_order, Anything()).runs(lambda order_id: f"sync-{order_id}")
133
+ assert await mock.aprocess_order(7) == "sync-7"
134
+
135
+
136
+ async def async_fn(order_id: int) -> str:
137
+ return f"async-{order_id}"
138
+
139
+
140
+ mock.expect(MyService.aprocess_order, Anything()).runs(async_fn)
141
+ assert await mock.aprocess_order(9) == "async-9"
142
+ ```
143
+
144
+ **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
+
146
+ Look up the dmock source code and tests yourself, it's full of examples!
147
+
148
+ ## Limitations & non-goals
149
+
150
+ - **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()`. You call `verify()` yourself (a pytest hook is on the roadmap).
152
+ - **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
+ - **Not thread-safe.** Concurrent use of one mock from multiple threads is out of scope.
154
+
155
+ ## Roadmap
156
+
157
+ After 0.3.0, in no particular order:
158
+
159
+ - **pytest auto-**`verify()` - a plugin or fixture that runs `verify()` at the end of each test (gomock-style `Finish` on teardown), so you do not have to remember the call.
160
+ - **Per-outcome counts (maybe)** - repeat a `.returns()` / `.raises()` / `.runs()` without chaining it n times (today `.returns(1).returns(1).returns(1).returns(2)`).
161
+
162
+ Other ideas belong in GitHub Issues.
163
+
164
+ ## Development
165
+
166
+ ```bash
167
+ poetry install
168
+ ruff check .
169
+ ruff format --check .
170
+ mypy src tests
171
+ pytest
172
+ pytest --cov --cov-report=term-missing
173
+ ```
174
+
175
+ See **[CONTRIBUTING.md](CONTRIBUTING.md)** for setup, commits, and tests. Agents follow **[AGENTS.md](AGENTS.md)**.
176
+
177
+ ## License
178
+
179
+ MIT
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "declarative-mocks"
3
- version = "0.1.1"
3
+ version = "0.3.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"
@@ -0,0 +1,108 @@
1
+ """Declarative wrapper around unittest.mock with a DSL for tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, version
6
+
7
+ from dmock._exceptions import (
8
+ ConfigurationError,
9
+ DeclarativeMockError,
10
+ UnexpectedCallError,
11
+ UnsatisfiedExpectationError,
12
+ )
13
+ from dmock._expectation import Expectation, in_order
14
+ from dmock._matchers import (
15
+ ANY_ARGS,
16
+ ANY_KWARGS,
17
+ AWARE_DATETIME,
18
+ EMPTY,
19
+ FALSY,
20
+ NAIVE_DATETIME,
21
+ TRUTHY,
22
+ And,
23
+ Anything,
24
+ AnythingOfType,
25
+ Approx,
26
+ Args,
27
+ Attr,
28
+ Contains,
29
+ Empty,
30
+ EndsWith,
31
+ Equals,
32
+ GreaterEquals,
33
+ GreaterThan,
34
+ In,
35
+ Includes,
36
+ Is,
37
+ LessEquals,
38
+ LessThan,
39
+ MatchedBy,
40
+ Matcher,
41
+ Maybe,
42
+ Never,
43
+ Not,
44
+ Nothing,
45
+ Or,
46
+ Range,
47
+ Regex,
48
+ RegexFullmatch,
49
+ RegexMatch,
50
+ RegexSearch,
51
+ StartsWith,
52
+ )
53
+ from dmock._mock import DeclarativeMock, dmock
54
+
55
+
56
+ try:
57
+ __version__ = version("declarative-mocks")
58
+ except PackageNotFoundError: # pragma: no cover
59
+ __version__ = "0.0.0+unknown"
60
+
61
+
62
+ __all__ = [
63
+ "ANY_ARGS",
64
+ "ANY_KWARGS",
65
+ "AWARE_DATETIME",
66
+ "EMPTY",
67
+ "FALSY",
68
+ "NAIVE_DATETIME",
69
+ "TRUTHY",
70
+ "And",
71
+ "Anything",
72
+ "AnythingOfType",
73
+ "Approx",
74
+ "Args",
75
+ "Attr",
76
+ "ConfigurationError",
77
+ "Contains",
78
+ "DeclarativeMock",
79
+ "DeclarativeMockError",
80
+ "Empty",
81
+ "EndsWith",
82
+ "Equals",
83
+ "Expectation",
84
+ "GreaterEquals",
85
+ "GreaterThan",
86
+ "In",
87
+ "Includes",
88
+ "Is",
89
+ "LessEquals",
90
+ "LessThan",
91
+ "MatchedBy",
92
+ "Matcher",
93
+ "Maybe",
94
+ "Never",
95
+ "Not",
96
+ "Nothing",
97
+ "Or",
98
+ "Range",
99
+ "Regex",
100
+ "RegexFullmatch",
101
+ "RegexMatch",
102
+ "RegexSearch",
103
+ "StartsWith",
104
+ "UnexpectedCallError",
105
+ "UnsatisfiedExpectationError",
106
+ "dmock",
107
+ "in_order",
108
+ ]
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING
5
5
 
6
6
  if TYPE_CHECKING:
7
7
  from collections.abc import Sequence
8
+ from typing import Any
8
9
 
9
10
  from dmock._expectation import Expectation
10
11
  from dmock._types import RecordedCall
@@ -44,7 +45,7 @@ class NoMatchingCallError(UnexpectedCallError):
44
45
  def __init__(
45
46
  self,
46
47
  call: RecordedCall,
47
- rejected: Sequence[Expectation],
48
+ rejected: Sequence[Expectation[Any, Any]],
48
49
  history: Sequence[RecordedCall],
49
50
  ) -> None:
50
51
  self.call = call
@@ -66,7 +67,7 @@ class NoMatchingCallError(UnexpectedCallError):
66
67
  self.history,
67
68
  )
68
69
 
69
- def _reason(self, exp: Expectation) -> str:
70
+ def _reason(self, exp: Expectation[Any, Any]) -> str:
70
71
  if exp.is_exhausted():
71
72
  maximum = exp.quantifier.max_calls
72
73
  bound = "*" if maximum is None else str(maximum)
@@ -81,8 +82,8 @@ class BlockedCallError(UnexpectedCallError):
81
82
  def __init__(
82
83
  self,
83
84
  call: RecordedCall,
84
- expectation: Expectation,
85
- blocked: Sequence[Expectation],
85
+ expectation: Expectation[Any, Any],
86
+ blocked: Sequence[Expectation[Any, Any]],
86
87
  history: Sequence[RecordedCall],
87
88
  ) -> None:
88
89
  self.call = call
@@ -101,7 +102,7 @@ class BlockedCallError(UnexpectedCallError):
101
102
  )
102
103
 
103
104
  @staticmethod
104
- def _blocked_reason(req: Expectation) -> str:
105
+ def _blocked_reason(req: Expectation[Any, Any]) -> str:
105
106
  return (
106
107
  f"blocked by {req.method_name} "
107
108
  f"(expected {req.quantifier.description}, got {req.call_count})"
@@ -111,7 +112,7 @@ class BlockedCallError(UnexpectedCallError):
111
112
  class ExceededCallError(UnexpectedCallError):
112
113
  """A matching call exceeded the expectation's quantifier upper bound."""
113
114
 
114
- def __init__(self, method_name: str, calls: int, max_calls: int) -> None:
115
+ def __init__(self, method_name: str, calls: int, max_calls: int | None) -> None:
115
116
  self.method_name = method_name
116
117
  self.calls = calls
117
118
  self.max_calls = max_calls
@@ -121,7 +122,7 @@ class ExceededCallError(UnexpectedCallError):
121
122
  return (
122
123
  f"Unexpected call to {self.method_name!r}: "
123
124
  f"called {self.calls} time(s), "
124
- f"max allowed is {self.max_calls}."
125
+ f"max allowed is {self.max_calls or 0}."
125
126
  )
126
127
 
127
128
 
@@ -130,7 +131,7 @@ class UnsatisfiedExpectationError(DeclarativeMockError):
130
131
 
131
132
  def __init__(
132
133
  self,
133
- expectations: Sequence[Expectation],
134
+ expectations: Sequence[Expectation[Any, Any]],
134
135
  history: Sequence[RecordedCall],
135
136
  ) -> None:
136
137
  self.expectations = tuple(expectations)
@@ -1,7 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from collections import deque
4
- from typing import TYPE_CHECKING, Self
4
+ 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 (
@@ -9,6 +9,7 @@ from dmock._matchers import (
9
9
  _AnyArgsSentinel, # pyright: ignore[reportPrivateUsage]
10
10
  _AnyKwargsSentinel, # pyright: ignore[reportPrivateUsage]
11
11
  )
12
+ from dmock._protocols import P, R
12
13
  from dmock._types import (
13
14
  AtLeast,
14
15
  Between,
@@ -22,7 +23,8 @@ from dmock._types import (
22
23
 
23
24
 
24
25
  if TYPE_CHECKING:
25
- from collections.abc import Callable, Sequence
26
+ from collections.abc import Awaitable, Callable, Sequence
27
+ from typing import Any
26
28
 
27
29
  from dmock._types import Outcome, Quantifier
28
30
 
@@ -34,7 +36,8 @@ def _value_matches(expected: object, actual: object) -> bool:
34
36
  return expected == actual
35
37
 
36
38
 
37
- class Expectation:
39
+ @final
40
+ class Expectation(Generic[P, R]):
38
41
  """A single expected call: fluent builder for outcomes and quantifiers.
39
42
 
40
43
  Constructed by :meth:`~dmock.DeclarativeMock.expect`. Chained ``returns`` /
@@ -71,11 +74,11 @@ class Expectation:
71
74
  self._quantifier: Quantifier | None = None
72
75
  self._optional: bool = False
73
76
  self._calls = 0
74
- self._requires: list[Expectation] = []
77
+ self._requires: list[Expectation[Any, Any]] = []
75
78
 
76
79
  # -- Fluent outcome builders --
77
80
 
78
- def returns(self, value: object) -> Self:
81
+ def returns(self, value: R) -> Self:
79
82
  """Declare the return value for the next matching call.
80
83
 
81
84
  Args:
@@ -121,7 +124,13 @@ class Expectation:
121
124
  self._outcomes.append(RaiseOutcome(exc))
122
125
  return self
123
126
 
124
- def runs(self, func: Callable[..., object]) -> Self:
127
+ @overload
128
+ def runs(self, func: Callable[P, R]) -> Self: ...
129
+
130
+ @overload
131
+ def runs(self, func: Callable[P, Awaitable[R]]) -> Self: ...
132
+
133
+ def runs(self, func: Callable[P, R | Awaitable[R]]) -> Self:
125
134
  """Call `func` with the actual arguments for the next matching call.
126
135
 
127
136
  The return value of `func` becomes the result of that call. Chaining
@@ -327,7 +336,7 @@ class Expectation:
327
336
  """
328
337
  return self._set_quantifier(Never())
329
338
 
330
- def not_before(self, *expectations: Expectation) -> Self:
339
+ def not_before(self, *expectations: Expectation[Any, Any]) -> Self:
331
340
  """Require that every `expectations` item is satisfied before this one.
332
341
 
333
342
  Args:
@@ -364,10 +373,10 @@ class Expectation:
364
373
 
365
374
  return self
366
375
 
367
- def _is_reachable_from(self, source: Expectation) -> bool:
376
+ def _is_reachable_from(self, source: Expectation[Any, Any]) -> bool:
368
377
  """Return True if `self` is reachable by following `_requires` from `source`."""
369
378
  visited: set[int] = set()
370
- queue: deque[Expectation] = deque([source])
379
+ queue: deque[Expectation[Any, Any]] = deque([source])
371
380
  while queue:
372
381
  node = queue.popleft()
373
382
  node_id = id(node)
@@ -383,7 +392,7 @@ class Expectation:
383
392
  return False
384
393
 
385
394
  @property
386
- def requires(self) -> Sequence[Expectation]:
395
+ def requires(self) -> Sequence[Expectation[Any, Any]]:
387
396
  """Prerequisites that must be satisfied before this expectation can match."""
388
397
  return self._requires
389
398
 
@@ -454,7 +463,7 @@ class Expectation:
454
463
  """
455
464
  q = self.quantifier
456
465
  self._calls += 1
457
- if q.max_calls is not None and self._calls > q.max_calls:
466
+ if q.is_exceeded(self._calls):
458
467
  raise ExceededCallError(self._method_name, self._calls, q.max_calls)
459
468
 
460
469
  if not self._outcomes:
@@ -496,7 +505,7 @@ class Expectation:
496
505
  return f"Expectation({self._method_name}({all_parts}))"
497
506
 
498
507
 
499
- def in_order(*expectations: Expectation) -> None:
508
+ def in_order(*expectations: Expectation[Any, Any]) -> None:
500
509
  """Link `expectations` so each one requires the previous to be satisfied first.
501
510
 
502
511
  Equivalent to calling ``expectations[i].not_before(expectations[i - 1])``