declarative-mocks 0.3.0__tar.gz → 0.4.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: declarative-mocks
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Declare mock behavior as ordered expectations. Simple, typed, gomock-inspired DSL over unittest.mock
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -174,16 +174,15 @@ Look up the dmock source code and tests yourself, it's full of examples!
174
174
  ## Limitations & non-goals
175
175
 
176
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).
177
+ - **No automatic** `verify()` **outside pytest.** The pytest plugin checks every mock when the test finishes. Other runners still need an explicit `verify()`.
178
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
179
  - **Not thread-safe.** Concurrent use of one mock from multiple threads is out of scope.
180
180
 
181
181
  ## Roadmap
182
182
 
183
- After 0.3.0, in no particular order:
183
+ Nothing is planned for 0.5.0, feel free to suggest!
184
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)`).
185
+ - **Other test runners (low priority)** - unittest and similar runners do not verify mocks on teardown the way the pytest plugin does.
187
186
 
188
187
  Other ideas belong in GitHub Issues.
189
188
 
@@ -195,7 +194,8 @@ ruff check .
195
194
  ruff format --check .
196
195
  mypy src tests
197
196
  pytest
198
- pytest --cov --cov-report=term-missing
197
+ coverage run -m pytest
198
+ coverage report
199
199
  ```
200
200
 
201
201
  See **[CONTRIBUTING.md](CONTRIBUTING.md)** for setup, commits, and tests. Agents follow **[AGENTS.md](AGENTS.md)**.
@@ -148,16 +148,15 @@ Look up the dmock source code and tests yourself, it's full of examples!
148
148
  ## Limitations & non-goals
149
149
 
150
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).
151
+ - **No automatic** `verify()` **outside pytest.** The pytest plugin checks every mock when the test finishes. Other runners still need an explicit `verify()`.
152
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
153
  - **Not thread-safe.** Concurrent use of one mock from multiple threads is out of scope.
154
154
 
155
155
  ## Roadmap
156
156
 
157
- After 0.3.0, in no particular order:
157
+ Nothing is planned for 0.5.0, feel free to suggest!
158
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)`).
159
+ - **Other test runners (low priority)** - unittest and similar runners do not verify mocks on teardown the way the pytest plugin does.
161
160
 
162
161
  Other ideas belong in GitHub Issues.
163
162
 
@@ -169,7 +168,8 @@ ruff check .
169
168
  ruff format --check .
170
169
  mypy src tests
171
170
  pytest
172
- pytest --cov --cov-report=term-missing
171
+ coverage run -m pytest
172
+ coverage report
173
173
  ```
174
174
 
175
175
  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.0"
3
+ version = "0.4.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"
@@ -28,6 +28,9 @@ Homepage = "https://github.com/MDx3R/declarative-mocks"
28
28
  Repository = "https://github.com/MDx3R/declarative-mocks"
29
29
  Issues = "https://github.com/MDx3R/declarative-mocks/issues"
30
30
 
31
+ [project.entry-points.pytest11]
32
+ dmock = "dmock._pytest_plugin"
33
+
31
34
  [tool.poetry]
32
35
  packages = [{ include = "dmock", from = "src" }]
33
36
 
@@ -131,4 +134,4 @@ branch = true
131
134
  [tool.coverage.report]
132
135
  show_missing = true
133
136
  fail_under = 90
134
- exclude_lines = ["pragma: no cover", "if TYPE_CHECKING:"]
137
+ exclude_lines = ["pragma: no cover", "if TYPE_CHECKING:", "@overload"]
@@ -78,15 +78,20 @@ class Expectation(Generic[P, R]):
78
78
 
79
79
  # -- Fluent outcome builders --
80
80
 
81
- def returns(self, value: R) -> Self:
81
+ def returns(self, value: R, *, repeat: int = 1) -> Self:
82
82
  """Declare the return value for the next matching call.
83
83
 
84
84
  Args:
85
85
  value: Object returned as-is (tuples are not unpacked).
86
+ repeat: How many successive calls receive this outcome. Must be
87
+ at least 1.
86
88
 
87
89
  Returns:
88
90
  This expectation, for chaining.
89
91
 
92
+ Raises:
93
+ ConfigurationError: If `repeat` is less than 1.
94
+
90
95
  Examples:
91
96
  >>> from dmock import DeclarativeMock
92
97
  >>> class Service:
@@ -97,18 +102,27 @@ class Expectation(Generic[P, R]):
97
102
  >>> mock.fetch("a")
98
103
  'A'
99
104
  """
100
- self._outcomes.append(ReturnOutcome(value))
105
+ self._append_outcome(ReturnOutcome(value), repeat)
101
106
  return self
102
107
 
103
- def raises(self, exc: BaseException | type[BaseException]) -> Self:
108
+ def raises(
109
+ self,
110
+ exc: BaseException | type[BaseException],
111
+ *,
112
+ repeat: int = 1,
113
+ ) -> Self:
104
114
  """Declare that the next matching call raises `exc`.
105
115
 
106
116
  Args:
107
117
  exc: Exception instance, or a type instantiated with no arguments.
118
+ repeat: How many successive calls raise `exc`. Must be at least 1.
108
119
 
109
120
  Returns:
110
121
  This expectation, for chaining.
111
122
 
123
+ Raises:
124
+ ConfigurationError: If `repeat` is less than 1.
125
+
112
126
  Examples:
113
127
  >>> from dmock import DeclarativeMock
114
128
  >>> class Service:
@@ -121,16 +135,16 @@ class Expectation(Generic[P, R]):
121
135
  ...
122
136
  KeyError
123
137
  """
124
- self._outcomes.append(RaiseOutcome(exc))
138
+ self._append_outcome(RaiseOutcome(exc), repeat)
125
139
  return self
126
140
 
127
141
  @overload
128
- def runs(self, func: Callable[P, R]) -> Self: ...
142
+ def runs(self, func: Callable[P, R], *, repeat: int = 1) -> Self: ...
129
143
 
130
144
  @overload
131
- def runs(self, func: Callable[P, Awaitable[R]]) -> Self: ...
145
+ def runs(self, func: Callable[P, Awaitable[R]], *, repeat: int = 1) -> Self: ...
132
146
 
133
- def runs(self, func: Callable[P, R | Awaitable[R]]) -> Self:
147
+ def runs(self, func: Callable[P, R | Awaitable[R]], *, repeat: int = 1) -> Self:
134
148
  """Call `func` with the actual arguments for the next matching call.
135
149
 
136
150
  The return value of `func` becomes the result of that call. Chaining
@@ -139,10 +153,14 @@ class Expectation(Generic[P, R]):
139
153
 
140
154
  Args:
141
155
  func: Called as ``func(*args, **kwargs)`` of the matching invocation.
156
+ repeat: How many successive calls invoke `func`. Must be at least 1.
142
157
 
143
158
  Returns:
144
159
  This expectation, for chaining.
145
160
 
161
+ Raises:
162
+ ConfigurationError: If `repeat` is less than 1.
163
+
146
164
  Examples:
147
165
  >>> from dmock import DeclarativeMock
148
166
  >>> class Service:
@@ -161,9 +179,21 @@ class Expectation(Generic[P, R]):
161
179
  >>> mock.fetch("a")
162
180
  'from-returns'
163
181
  """
164
- self._outcomes.append(RunOutcome(func))
182
+ self._append_outcome(RunOutcome(func), repeat)
165
183
  return self
166
184
 
185
+ def _append_outcome(self, outcome: Outcome, repeat: int) -> None:
186
+ """Append `outcome` once per `repeat`.
187
+
188
+ Raises:
189
+ ConfigurationError: If `repeat` is less than 1.
190
+ """
191
+ if repeat < 1:
192
+ raise ConfigurationError(f"repeat requires repeat >= 1, got {repeat}.")
193
+
194
+ for _ in range(repeat):
195
+ self._outcomes.append(outcome)
196
+
167
197
  # -- Fluent quantifiers --
168
198
 
169
199
  def once(self) -> Self:
@@ -317,7 +317,7 @@ class _NeverMatcher(Matcher):
317
317
  >>> class Service:
318
318
  ... def fetch(self, key: str) -> str: ...
319
319
  >>> mock = DeclarativeMock(Service)
320
- >>> mock.expect("fetch", Never).returns("ok")
320
+ >>> mock.expect("fetch", Never).returns("ok").maybe()
321
321
  Expectation(fetch(Never))
322
322
  >>> Never.matches("a")
323
323
  False
@@ -14,6 +14,7 @@ from dmock._exceptions import (
14
14
  )
15
15
  from dmock._expectation import Expectation
16
16
  from dmock._protocols import T
17
+ from dmock._registry import MockRegistry
17
18
  from dmock._types import (
18
19
  DefaultOutcome,
19
20
  RaiseOutcome,
@@ -109,6 +110,7 @@ class DeclarativeMock(Generic[T], _Base):
109
110
  self.__hooked: set[str] = set()
110
111
  self.__properties: dict[str, object] = {}
111
112
  self.__calls: list[RecordedCall] = []
113
+ MockRegistry.add(self)
112
114
 
113
115
  # -- Public DSL --
114
116
 
@@ -311,6 +313,8 @@ class DeclarativeMock(Generic[T], _Base):
311
313
  ... except UnsatisfiedExpectationError as exc:
312
314
  ... "expected exactly 1 call(s), got 0" in str(exc)
313
315
  True
316
+ >>> mock.fetch("a")
317
+ 'A'
314
318
  """
315
319
  unsatisfied = [e for e in self.__expectations if not e.is_satisfied()]
316
320
  if not unsatisfied:
@@ -0,0 +1,47 @@
1
+ """Verify declarative mocks from pytest's test report hook."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ import pytest
8
+ from _pytest._code import ExceptionInfo
9
+
10
+ from dmock._registry import MockRegistry
11
+
12
+
13
+ if TYPE_CHECKING:
14
+ from collections.abc import Generator
15
+
16
+ from _pytest.nodes import Item
17
+ from _pytest.reports import TestReport
18
+ from _pytest.runner import CallInfo
19
+
20
+
21
+ @pytest.hookimpl(hookwrapper=True)
22
+ def pytest_runtest_makereport(item: Item, call: CallInfo[None]) -> Generator[None]:
23
+ """Verify mocks when the call finishes, and again after teardown.
24
+
25
+ On the call phase a failed ``verify`` becomes the test failure. On the
26
+ teardown phase every mock still registered — including ones created while
27
+ fixtures were finalizing — is verified and dropped, and a failed
28
+ ``verify`` is recorded on that phase's report. An exception the phase
29
+ already raised stays in place (``call.excinfo`` is replaced only when it
30
+ is empty). ``MockRegistry.teardown`` empties the registry before
31
+ ``verify``, so a failure cannot leak into the next test.
32
+
33
+ Args:
34
+ item: Test item for which the hook is being called.
35
+ call: Information about the current call phase.
36
+
37
+ Yields:
38
+ Control back to the pytest runner.
39
+ """
40
+ del item
41
+ if call.when in {"call", "teardown"}:
42
+ try:
43
+ MockRegistry.teardown()
44
+ except BaseException:
45
+ call.excinfo = call.excinfo or ExceptionInfo.from_current()
46
+
47
+ _report: TestReport | None = yield
@@ -0,0 +1,66 @@
1
+ """Registry of declarative mocks verified at the end of a test."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, ClassVar
6
+
7
+
8
+ if TYPE_CHECKING:
9
+ from collections.abc import Sequence
10
+ from typing import Any
11
+
12
+ from dmock._mock import DeclarativeMock
13
+
14
+
15
+ class MockRegistry:
16
+ """Live mocks to verify when a test finishes.
17
+
18
+ :class:`~dmock.DeclarativeMock` registers itself on construction.
19
+ :meth:`teardown` copies that list, replaces it with an empty one, then
20
+ calls :meth:`~dmock.DeclarativeMock.verify` on the copy. Clearing first
21
+ means a failed verify cannot leak mocks into the next test. A later
22
+ :meth:`teardown` with nothing registered does nothing.
23
+
24
+ :meth:`clear` drops registered mocks without verifying them. Tests that
25
+ leave expectations unmet on purpose use it so a later ``teardown`` does
26
+ not fail them again.
27
+
28
+ Verification is fail-fast. If ``verify`` raises, mocks later in the copy
29
+ are not checked. They have already been dropped from the registry.
30
+ """
31
+
32
+ _mocks: ClassVar[list[DeclarativeMock[Any]]] = []
33
+
34
+ @property
35
+ def mocks(self) -> Sequence[DeclarativeMock[Any]]:
36
+ """Return a copy of the mocks registered right now.
37
+
38
+ Read it from any instance (``MockRegistry().mocks``). The copy is a
39
+ new list, so a later :meth:`add`, :meth:`clear`, or :meth:`teardown`
40
+ does not change it.
41
+ """
42
+ return list(self._mocks)
43
+
44
+ @classmethod
45
+ def add(cls, mock: DeclarativeMock[Any]) -> None:
46
+ """Remember `mock` until the next :meth:`teardown`."""
47
+ cls._mocks.append(mock)
48
+
49
+ @classmethod
50
+ def clear(cls) -> None:
51
+ """Drop every registered mock without calling ``verify``."""
52
+ cls._mocks = []
53
+
54
+ @classmethod
55
+ def teardown(cls) -> None:
56
+ """Verify every registered mock and forget them.
57
+
58
+ Raises:
59
+ UnsatisfiedExpectationError: A registered mock is unmet.
60
+ Remaining mocks in this batch are not verified.
61
+ """
62
+ mocks = list(cls._mocks)
63
+ cls._mocks = []
64
+
65
+ for mock in mocks:
66
+ mock.verify()