Coverage for faststream/_internal/testing/calls.py: 98%

150 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-17 21:20 +0000

1from collections.abc import Callable, Mapping 

2from copy import copy 

3from dataclasses import dataclass, field, fields 

4from typing import TYPE_CHECKING, Any, TypeAlias 

5from unittest.mock import MagicMock 

6 

7from faststream._internal.constants import EMPTY 

8from faststream._internal.context import ContextRepo 

9from faststream._internal.parser import DefaultCodec 

10from faststream.exceptions import ContextError, SetupError 

11 

12if TYPE_CHECKING: 

13 from faststream._internal.configs import BrokerConfig 

14 from faststream.message import StreamMessage 

15 

16# Takes a Broker field off the raw message, under the name the broker's `publish()` uses 

17FieldReader: TypeAlias = Callable[[str, "StreamMessage[Any]"], Any] 

18 

19 

20class CallAssertions: 

21 """The mock and the Call assertions an endpoint answers with under a test broker.""" 

22 

23 __slots__ = () 

24 

25 is_test: bool 

26 _recorder: "CallRecorder" 

27 

28 @property 

29 def mock(self) -> MagicMock: 

30 """The mock recording the endpoint's calls, available under a test broker.""" 

31 return self._recorder_under_test().mock 

32 

33 async def assert_called_once_with( 

34 self, 

35 body: Any = EMPTY, 

36 /, 

37 *, 

38 headers: Any = EMPTY, 

39 correlation_id: Any = EMPTY, 

40 reply_to: Any = EMPTY, 

41 content_type: Any = EMPTY, 

42 path: Any = EMPTY, 

43 context: Mapping[str, Any] = EMPTY, 

44 ) -> None: 

45 """Assert the endpoint was called once, with the message described here. 

46 

47 Args: 

48 body: The body as a dict, a model or a matcher; it goes through the codec. 

49 headers: Headers the message must carry; the rest may carry more. 

50 correlation_id: The exact correlation id. 

51 reply_to: The exact reply-to destination. 

52 content_type: The exact content type. 

53 path: The exact path parameters the subject template matched. 

54 context: Context paths, as given to `Context()`, mapped to their values. 

55 """ 

56 await self._assert_called_once_with( 

57 ExpectedCall( 

58 body=body, 

59 headers=headers, 

60 correlation_id=correlation_id, 

61 reply_to=reply_to, 

62 content_type=content_type, 

63 path=path, 

64 context=context, 

65 ) 

66 ) 

67 

68 async def assert_called_with( 

69 self, 

70 body: Any = EMPTY, 

71 /, 

72 *, 

73 headers: Any = EMPTY, 

74 correlation_id: Any = EMPTY, 

75 reply_to: Any = EMPTY, 

76 content_type: Any = EMPTY, 

77 path: Any = EMPTY, 

78 context: Mapping[str, Any] = EMPTY, 

79 ) -> None: 

80 """Assert the last message the endpoint saw is the one described here. 

81 

82 Args: 

83 body: The body as a dict, a model or a matcher; it goes through the codec. 

84 headers: Headers the message must carry; the rest may carry more. 

85 correlation_id: The exact correlation id. 

86 reply_to: The exact reply-to destination. 

87 content_type: The exact content type. 

88 path: The exact path parameters the subject template matched. 

89 context: Context paths, as given to `Context()`, mapped to their values. 

90 """ 

91 await self._assert_called_with( 

92 ExpectedCall( 

93 body=body, 

94 headers=headers, 

95 correlation_id=correlation_id, 

96 reply_to=reply_to, 

97 content_type=content_type, 

98 path=path, 

99 context=context, 

100 ) 

101 ) 

102 

103 async def assert_any_call( 

104 self, 

105 body: Any = EMPTY, 

106 /, 

107 *, 

108 headers: Any = EMPTY, 

109 correlation_id: Any = EMPTY, 

110 reply_to: Any = EMPTY, 

111 content_type: Any = EMPTY, 

112 path: Any = EMPTY, 

113 context: Mapping[str, Any] = EMPTY, 

114 ) -> None: 

115 """Assert one of the messages the endpoint saw is the one described here. 

116 

117 Args: 

118 body: The body as a dict, a model or a matcher; it goes through the codec. 

119 headers: Headers the message must carry; the rest may carry more. 

120 correlation_id: The exact correlation id. 

121 reply_to: The exact reply-to destination. 

122 content_type: The exact content type. 

123 path: The exact path parameters the subject template matched. 

124 context: Context paths, as given to `Context()`, mapped to their values. 

125 """ 

126 await self._assert_any_call( 

127 ExpectedCall( 

128 body=body, 

129 headers=headers, 

130 correlation_id=correlation_id, 

131 reply_to=reply_to, 

132 content_type=content_type, 

133 path=path, 

134 context=context, 

135 ) 

136 ) 

137 

138 async def _assert_called_once_with(self, expected: "ExpectedCall") -> None: 

139 """The check behind `assert_called_once_with`; a broker's mixin enters here.""" 

140 recorder = self._recorder_with_calls() 

141 recorder.mock.assert_called_once() 

142 await recorder.assert_last_call(expected) 

143 

144 async def _assert_called_with(self, expected: "ExpectedCall") -> None: 

145 await self._recorder_with_calls().assert_last_call(expected) 

146 

147 async def _assert_any_call(self, expected: "ExpectedCall") -> None: 

148 await self._recorder_with_calls().assert_any_call(expected) 

149 

150 def _recorder_with_calls(self) -> "CallRecorder": 

151 recorder = self._recorder_under_test() 

152 # Every Call assertion answers alike for an endpoint nobody called 

153 if not recorder.calls: 

154 msg = f"`{recorder.name}` was not called" 

155 raise AssertionError(msg) 

156 return recorder 

157 

158 def _recorder_under_test(self) -> "CallRecorder": 

159 if not self.is_test: 

160 msg = ( 

161 f"`{self._recorder.name}` is not under a test broker: " 

162 "wrap the broker with its `Test*Broker` to use the mock " 

163 "and the Call assertions." 

164 ) 

165 raise SetupError(msg) 

166 return self._recorder 

167 

168 

169class CallRecorder: 

170 """Records the messages an endpoint saw under a test broker and compares them.""" 

171 

172 def __init__(self, name: str, outer_config: "BrokerConfig") -> None: 

173 self.name = name 

174 self.mock = MagicMock() 

175 self.calls: list[RecordedCall] = [] 

176 

177 self._outer_config = outer_config 

178 # A publisher shares its fake subscriber's recorder, or mirrors a real one 

179 self._mirrors: list[CallRecorder] = [] 

180 

181 async def record(self, message: "StreamMessage[Any]") -> None: 

182 # The context is scoped to this call, so it has to be captured now 

183 # rather than resolved when the assertion runs. 

184 context = self._outer_config.context.context 

185 call = RecordedCall(message, context) 

186 decoded = await message.decode() 

187 

188 for recorder in (self, *self._mirrors): 

189 recorder.calls.append(call) 

190 recorder.mock(decoded) 

191 

192 def mirror_to(self, other: "CallRecorder") -> None: 

193 # The test broker may start more than once inside one context 

194 if other not in self._mirrors: 

195 self._mirrors.append(other) 

196 

197 def stop_mirroring(self) -> None: 

198 self._mirrors.clear() 

199 

200 def reset(self) -> None: 

201 self.mock.reset_mock() 

202 self.calls.clear() 

203 

204 async def assert_last_call(self, expected: "ExpectedCall") -> None: 

205 """Assert the last Recorded call is the one described.""" 

206 mismatches = await self._mismatches(self.calls[-1], expected) 

207 if mismatches: 

208 raise AssertionError(_called_with_different(self.name, mismatches)) 

209 

210 async def assert_any_call(self, expected: "ExpectedCall") -> None: 

211 """Assert one of the Recorded calls, in order, is the one described.""" 

212 reports: list[list[str]] = [] 

213 for call in self.calls: 

214 mismatches = await self._mismatches(call, expected) 

215 if not mismatches: 

216 return 

217 reports.append(mismatches) 

218 raise AssertionError(_not_called_with(self.name, reports)) 

219 

220 async def _mismatches( 

221 self, 

222 call: "RecordedCall", 

223 expected: "ExpectedCall", 

224 ) -> list[str]: 

225 """Compare one Recorded call with the message described, one line per mismatch.""" 

226 checks = _Mismatches() 

227 

228 if expected.body is not EMPTY: 

229 checks.compare( 

230 "body", 

231 await self._expected_body(expected.body, call.message), 

232 await call.message.decode(), 

233 ) 

234 

235 asked = expected.message_fields() 

236 if asked and call.message.batch_headers: 

237 msg = ( 

238 f"`{self.name}` received a batch: only its body can be asserted, " 

239 f"not {', '.join(asked)}." 

240 ) 

241 raise SetupError(msg) 

242 

243 if expected.headers is not EMPTY: 

244 checks.compare( 

245 "headers", 

246 expected.headers, 

247 _headers_seen_through(expected.headers, call.message.headers), 

248 shown=call.message.headers, 

249 ) 

250 

251 for name in ("correlation_id", "reply_to", "content_type", "path"): 

252 if (value := getattr(expected, name)) is not EMPTY: 

253 checks.compare(name, value, getattr(call.message, name)) 

254 

255 if expected.context is not EMPTY: 

256 repo = ContextRepo(call.context) 

257 for key, value in expected.context.items(): 

258 try: 

259 actual = repo.resolve(key) 

260 except (ContextError, AttributeError, KeyError): 

261 actual = EMPTY 

262 checks.compare(f"context[{key!r}]", value, actual) 

263 

264 if (fields := expected.broker_fields) is not None: 

265 for name, value in fields.values.items(): 

266 checks.compare(name, value, fields.read(name, call.message)) 

267 

268 return checks.lines 

269 

270 async def _expected_body(self, body: Any, message: "StreamMessage[Any]") -> Any: 

271 """Run the expected body through the path the received one took.""" 

272 codec = self._outer_config.broker_codec or DefaultCodec() 

273 serializer = self._outer_config.fd_config._serializer 

274 

275 try: 

276 if message.batch_headers: 

277 encoded = [await codec.encode(item, serializer) for item in body] 

278 else: 

279 encoded = [await codec.encode(body, serializer)] 

280 

281 # A matcher (dirty-equals and the like) cannot be encoded: compare it as is 

282 except (TypeError, ValueError): 

283 return body 

284 

285 probes = [ 

286 _with_body(message, data, content_type) for data, content_type in encoded 

287 ] 

288 if not message.batch_headers: 

289 return await probes[0].decode() 

290 

291 # A batch decoder answers for the whole batch, so items go through the codec 

292 for probe in probes: 

293 probe.set_decoder(codec.decode) 

294 return [await probe.decode() for probe in probes] 

295 

296 

297@dataclass(slots=True, kw_only=True) 

298class ExpectedCall: 

299 """The message a Call assertion describes; a field given as EMPTY is not compared.""" 

300 

301 body: Any 

302 headers: Any 

303 correlation_id: Any 

304 reply_to: Any 

305 content_type: Any 

306 path: Any 

307 context: Mapping[str, Any] 

308 broker_fields: "BrokerFields | None" = None 

309 

310 def message_fields(self) -> list[str]: 

311 """The names asked of the message beside its body.""" 

312 named = (f.name for f in fields(self) if f.name not in {"body", "broker_fields"}) 

313 return [ 

314 *(name for name in named if getattr(self, name) is not EMPTY), 

315 *(self.broker_fields.values if self.broker_fields else ()), 

316 ] 

317 

318 

319@dataclass(slots=True) 

320class BrokerFields: 

321 """A broker's own fields a Call assertion asks for, and the reader that answers them.""" 

322 

323 # Under the names the broker's `publish()` takes; a field not asked for is absent 

324 values: Mapping[str, Any] 

325 read: FieldReader 

326 

327 

328@dataclass(slots=True) 

329class RecordedCall: 

330 message: "StreamMessage[Any]" 

331 context: dict[str, Any] 

332 

333 

334def _with_body( 

335 message: "StreamMessage[Any]", 

336 body: bytes, 

337 content_type: str | None, 

338) -> "StreamMessage[Any]": 

339 """A copy of the message carrying another body, decoded the same way.""" 

340 probe = copy(message) 

341 probe.body = body 

342 probe.content_type = content_type 

343 return probe 

344 

345 

346def _headers_seen_through(expected: Any, actual: dict[str, Any]) -> Any: 

347 """Project the received headers onto the expected keys.""" 

348 if not isinstance(expected, Mapping): 348 ↛ 349line 348 didn't jump to line 349 because the condition on line 348 was never true

349 return actual 

350 # Headers match as a subset: the framework and the broker add their own 

351 return {key: actual.get(key, EMPTY) for key in expected} 

352 

353 

354def _called_with_different(name: str, mismatches: list[str]) -> str: 

355 return "\n".join(( 

356 f"`{name}` was called with different arguments:", 

357 *(f" {line}" for line in mismatches), 

358 )) 

359 

360 

361def _not_called_with(name: str, reports: list[list[str]]) -> str: 

362 lines = [f"`{name}` was not called with these arguments:"] 

363 for number, mismatches in enumerate(reports, start=1): 

364 lines.append(f" call {number}:") 

365 lines.extend(f" {line}" for line in mismatches) 

366 return "\n".join(lines) 

367 

368 

369@dataclass(slots=True) 

370class _Mismatches: 

371 lines: list[str] = field(default_factory=list) 

372 

373 def compare( 

374 self, 

375 name: str, 

376 expected: Any, 

377 actual: Any, 

378 *, 

379 shown: Any = EMPTY, 

380 ) -> None: 

381 if expected == actual: 

382 return 

383 got = actual if shown is EMPTY else shown 

384 self.lines.append(f"{name}: expected {expected!r}, got {got!r}")