declarative-mocks 0.2.0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: declarative-mocks
3
- Version: 0.2.0
3
+ Version: 0.3.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
@@ -76,7 +76,10 @@ Here's an example of how _dmock_ improves your tests:
76
76
  from dmock import AnythingOfType, Contains, DeclarativeMock, StartsWith
77
77
 
78
78
  service = DeclarativeMock(Directory)
79
- service.expect("lookup", "ada").returns(User(id=1, name="Ada", email="ada@example.com"))
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"))
80
83
 
81
84
  assert service.lookup("ada") == User(
82
85
  id=AnythingOfType(int),
@@ -143,16 +146,16 @@ calc.expect("price", 400).never()
143
146
  calc.verify()
144
147
  ```
145
148
 
146
- Async methods use the same DSL. `runs()` accepts a sync or an async functions:
149
+ Async methods use the same DSL. `runs()` accepts a sync or an async function:
147
150
 
148
151
  ```python
149
152
  from dmock import Anything, DeclarativeMock
150
153
 
151
154
  mock = DeclarativeMock(MyService)
152
- mock.expect("aprocess_order", Anything()).returns("ok")
155
+ mock.expect(MyService.aprocess_order, Anything()).returns("ok")
153
156
  assert await mock.aprocess_order(1) == "ok"
154
157
 
155
- mock.expect("aprocess_order", Anything()).runs(lambda order_id: f"sync-{order_id}")
158
+ mock.expect(MyService.aprocess_order, Anything()).runs(lambda order_id: f"sync-{order_id}")
156
159
  assert await mock.aprocess_order(7) == "sync-7"
157
160
 
158
161
 
@@ -160,7 +163,7 @@ async def async_fn(order_id: int) -> str:
160
163
  return f"async-{order_id}"
161
164
 
162
165
 
163
- mock.expect("aprocess_order", Anything()).runs(async_fn)
166
+ mock.expect(MyService.aprocess_order, Anything()).runs(async_fn)
164
167
  assert await mock.aprocess_order(9) == "async-9"
165
168
  ```
166
169
 
@@ -170,14 +173,14 @@ Look up the dmock source code and tests yourself, it's full of examples!
170
173
 
171
174
  ## Limitations & non-goals
172
175
 
173
- - **No signature binding.** `expect("method", …)` checks that `method` exists on the spec, not that the argument list matches the real signature.
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.
174
177
  - **No automatic** `verify()`. You call `verify()` yourself (a pytest hook is on the roadmap).
175
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.
176
179
  - **Not thread-safe.** Concurrent use of one mock from multiple threads is out of scope.
177
180
 
178
181
  ## Roadmap
179
182
 
180
- After 0.2.0, in no particular order:
183
+ After 0.3.0, in no particular order:
181
184
 
182
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.
183
186
  - **Per-outcome counts (maybe)** - repeat a `.returns()` / `.raises()` / `.runs()` without chaining it n times (today `.returns(1).returns(1).returns(1).returns(2)`).
@@ -50,7 +50,10 @@ Here's an example of how _dmock_ improves your tests:
50
50
  from dmock import AnythingOfType, Contains, DeclarativeMock, StartsWith
51
51
 
52
52
  service = DeclarativeMock(Directory)
53
- service.expect("lookup", "ada").returns(User(id=1, name="Ada", email="ada@example.com"))
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"))
54
57
 
55
58
  assert service.lookup("ada") == User(
56
59
  id=AnythingOfType(int),
@@ -117,16 +120,16 @@ calc.expect("price", 400).never()
117
120
  calc.verify()
118
121
  ```
119
122
 
120
- Async methods use the same DSL. `runs()` accepts a sync or an async functions:
123
+ Async methods use the same DSL. `runs()` accepts a sync or an async function:
121
124
 
122
125
  ```python
123
126
  from dmock import Anything, DeclarativeMock
124
127
 
125
128
  mock = DeclarativeMock(MyService)
126
- mock.expect("aprocess_order", Anything()).returns("ok")
129
+ mock.expect(MyService.aprocess_order, Anything()).returns("ok")
127
130
  assert await mock.aprocess_order(1) == "ok"
128
131
 
129
- mock.expect("aprocess_order", Anything()).runs(lambda order_id: f"sync-{order_id}")
132
+ mock.expect(MyService.aprocess_order, Anything()).runs(lambda order_id: f"sync-{order_id}")
130
133
  assert await mock.aprocess_order(7) == "sync-7"
131
134
 
132
135
 
@@ -134,7 +137,7 @@ async def async_fn(order_id: int) -> str:
134
137
  return f"async-{order_id}"
135
138
 
136
139
 
137
- mock.expect("aprocess_order", Anything()).runs(async_fn)
140
+ mock.expect(MyService.aprocess_order, Anything()).runs(async_fn)
138
141
  assert await mock.aprocess_order(9) == "async-9"
139
142
  ```
140
143
 
@@ -144,14 +147,14 @@ Look up the dmock source code and tests yourself, it's full of examples!
144
147
 
145
148
  ## Limitations & non-goals
146
149
 
147
- - **No signature binding.** `expect("method", …)` checks that `method` exists on the spec, not that the argument list matches the real signature.
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.
148
151
  - **No automatic** `verify()`. You call `verify()` yourself (a pytest hook is on the roadmap).
149
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.
150
153
  - **Not thread-safe.** Concurrent use of one mock from multiple threads is out of scope.
151
154
 
152
155
  ## Roadmap
153
156
 
154
- After 0.2.0, in no particular order:
157
+ After 0.3.0, in no particular order:
155
158
 
156
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.
157
160
  - **Per-outcome counts (maybe)** - repeat a `.returns()` / `.raises()` / `.runs()` without chaining it n times (today `.returns(1).returns(1).returns(1).returns(2)`).
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "declarative-mocks"
3
- version = "0.2.0"
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"
@@ -50,7 +50,7 @@ from dmock._matchers import (
50
50
  RegexSearch,
51
51
  StartsWith,
52
52
  )
53
- from dmock._mock import DeclarativeMock
53
+ from dmock._mock import DeclarativeMock, dmock
54
54
 
55
55
 
56
56
  try:
@@ -103,5 +103,6 @@ __all__ = [
103
103
  "StartsWith",
104
104
  "UnexpectedCallError",
105
105
  "UnsatisfiedExpectationError",
106
+ "dmock",
106
107
  "in_order",
107
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])``