Coverage for tests/brokers/base/publish.py: 99%

252 statements  

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

1import asyncio 

2from contextlib import suppress 

3from dataclasses import asdict, dataclass 

4from datetime import datetime, timezone 

5from typing import Any 

6from unittest.mock import MagicMock 

7 

8import anyio 

9import pytest 

10from pydantic import BaseModel 

11 

12from faststream import BaseMiddleware, Context, FastStream, Response, TestApp 

13from faststream._internal._compat import dump_json, model_to_json 

14from faststream.context import ContextRepo 

15from faststream.exceptions import SubscriberNotFound 

16 

17from .basic import BaseTestcaseConfig 

18 

19 

20class SimpleModel(BaseModel): 

21 r: str 

22 

23 

24@dataclass 

25class SimpleDataclass: 

26 r: str 

27 

28 

29now = datetime.now(timezone.utc) 

30 

31parametrized = ( 

32 pytest.param( 

33 "hello", 

34 str, 

35 "hello", 

36 id="str->str", 

37 ), 

38 pytest.param( 

39 b"hello", 

40 bytes, 

41 b"hello", 

42 id="bytes->bytes", 

43 ), 

44 pytest.param( 

45 1, 

46 int, 

47 1, 

48 id="int->int", 

49 ), 

50 pytest.param( 

51 1.0, 

52 float, 

53 1.0, 

54 id="float->float", 

55 ), 

56 pytest.param( 

57 1, 

58 float, 

59 1.0, 

60 id="int->float", 

61 ), 

62 pytest.param( 

63 False, 

64 bool, 

65 False, 

66 id="bool->bool", 

67 ), 

68 pytest.param( 

69 {"m": 1}, 

70 dict[str, int], 

71 {"m": 1}, 

72 id="dict->dict", 

73 ), 

74 pytest.param( 

75 [1, 2, 3], 

76 list[int], 

77 [1, 2, 3], 

78 id="list->list", 

79 ), 

80 pytest.param( 

81 now, 

82 datetime, 

83 now, 

84 id="datetime->datetime", 

85 ), 

86 pytest.param( 

87 dump_json(asdict(SimpleDataclass(r="hello!"))), 

88 SimpleDataclass, 

89 SimpleDataclass(r="hello!"), 

90 id="bytes->dataclass", 

91 ), 

92 pytest.param( 

93 SimpleDataclass(r="hello!"), 

94 SimpleDataclass, 

95 SimpleDataclass(r="hello!"), 

96 id="dataclass->dataclass", 

97 ), 

98 pytest.param( 

99 SimpleDataclass(r="hello!"), 

100 dict, 

101 {"r": "hello!"}, 

102 id="dataclass->dict", 

103 ), 

104 pytest.param( 

105 {"r": "hello!"}, 

106 SimpleDataclass, 

107 SimpleDataclass(r="hello!"), 

108 id="dict->dataclass", 

109 ), 

110) 

111 

112 

113class BrokerPublishTestcase(BaseTestcaseConfig[Any]): 

114 @pytest.mark.asyncio() 

115 @pytest.mark.parametrize( 

116 ("message", "message_type", "expected_message"), 

117 ( 

118 *parametrized, 

119 pytest.param( 

120 model_to_json(SimpleModel(r="hello!")).encode(), 

121 SimpleModel, 

122 SimpleModel(r="hello!"), 

123 id="bytes->model", 

124 ), 

125 pytest.param( 

126 SimpleModel(r="hello!"), 

127 SimpleModel, 

128 SimpleModel(r="hello!"), 

129 id="model->model", 

130 ), 

131 pytest.param( 

132 SimpleModel(r="hello!"), 

133 dict, 

134 {"r": "hello!"}, 

135 id="model->dict", 

136 ), 

137 pytest.param( 

138 {"r": "hello!"}, 

139 SimpleModel, 

140 SimpleModel(r="hello!"), 

141 id="dict->model", 

142 ), 

143 ), 

144 ) 

145 async def test_serialize( 

146 self, 

147 queue: str, 

148 message: Any, 

149 message_type: Any, 

150 expected_message: Any, 

151 mock: MagicMock, 

152 event: asyncio.Event, 

153 ) -> None: 

154 pub_broker = self.get_broker(apply_types=True) 

155 

156 args, kwargs = self.get_subscriber_params(queue) 

157 

158 @pub_broker.subscriber(*args, **kwargs) 

159 async def handler(m: message_type) -> None: 

160 event.set() 

161 mock(m) 

162 

163 async with self.patch_broker(pub_broker) as br: 

164 await br.start() 

165 

166 await asyncio.wait( 

167 ( 

168 asyncio.create_task(br.publish(message, queue)), 

169 asyncio.create_task(event.wait()), 

170 ), 

171 timeout=self.timeout, 

172 ) 

173 

174 mock.assert_called_with(expected_message) 

175 

176 @pytest.mark.asyncio() 

177 async def test_response( 

178 self, queue: str, mock: MagicMock, event: asyncio.Event 

179 ) -> None: 

180 pub_broker = self.get_broker(apply_types=True) 

181 

182 args, kwargs = self.get_subscriber_params(queue) 

183 

184 @pub_broker.subscriber(*args, **kwargs) 

185 @pub_broker.publisher(queue + "1") 

186 async def m() -> Any: 

187 return Response(1, headers={"custom": "1"}, correlation_id="1") 

188 

189 args2, kwargs2 = self.get_subscriber_params(queue + "1") 

190 

191 @pub_broker.subscriber(*args2, **kwargs2) 

192 async def m_next(msg: Any = Context("message")) -> None: 

193 event.set() 

194 mock( 

195 body=msg.body, 

196 headers=msg.headers["custom"], 

197 correlation_id=msg.correlation_id, 

198 ) 

199 

200 async with self.patch_broker(pub_broker) as br: 

201 await br.start() 

202 await asyncio.wait( 

203 ( 

204 asyncio.create_task(br.publish(None, queue)), 

205 asyncio.create_task(event.wait()), 

206 ), 

207 timeout=self.timeout, 

208 ) 

209 

210 mock.assert_called_with( 

211 body=b"1", 

212 correlation_id="1", 

213 headers="1", 

214 ) 

215 

216 @pytest.mark.asyncio() 

217 async def test_custom_id_generator( 

218 self, 

219 queue: str, 

220 mock: MagicMock, 

221 ) -> None: 

222 event = asyncio.Event() 

223 

224 pub_broker = self.get_broker(apply_types=True, id_generator=lambda: "custom-id") 

225 

226 args, kwargs = self.get_subscriber_params(queue) 

227 

228 @pub_broker.subscriber(*args, **kwargs) 

229 async def handler(msg: Any = Context("message")) -> None: 

230 event.set() 

231 mock(correlation_id=msg.correlation_id) 

232 

233 async with self.patch_broker(pub_broker) as br: 

234 await br.start() 

235 await asyncio.wait( 

236 ( 

237 asyncio.create_task(br.publish("hello", queue)), 

238 asyncio.create_task(event.wait()), 

239 ), 

240 timeout=self.timeout, 

241 ) 

242 

243 mock.assert_called_with(correlation_id="custom-id") 

244 

245 @pytest.mark.asyncio() 

246 async def test_unwrap_dict( 

247 self, queue: str, mock: MagicMock, event: asyncio.Event 

248 ) -> None: 

249 pub_broker = self.get_broker(apply_types=True) 

250 

251 args, kwargs = self.get_subscriber_params(queue) 

252 

253 @pub_broker.subscriber(*args, **kwargs) 

254 async def m(a: int, b: int) -> None: 

255 event.set() 

256 mock({"a": a, "b": b}) 

257 

258 async with self.patch_broker(pub_broker) as br: 

259 await br.start() 

260 await asyncio.wait( 

261 ( 

262 asyncio.create_task(br.publish({"a": 1, "b": 1.0}, queue)), 

263 asyncio.create_task(event.wait()), 

264 ), 

265 timeout=self.timeout, 

266 ) 

267 

268 mock.assert_called_with( 

269 { 

270 "a": 1, 

271 "b": 1, 

272 }, 

273 ) 

274 

275 @pytest.mark.asyncio() 

276 async def test_unwrap_list( 

277 self, mock: MagicMock, queue: str, event: asyncio.Event 

278 ) -> None: 

279 pub_broker = self.get_broker(apply_types=True) 

280 

281 args, kwargs = self.get_subscriber_params(queue) 

282 

283 @pub_broker.subscriber(*args, **kwargs) 

284 async def m(a: int, b: int, *args: tuple[int, ...]) -> None: 

285 event.set() 

286 mock({"a": a, "b": b, "args": args}) 

287 

288 async with self.patch_broker(pub_broker) as br: 

289 await br.start() 

290 await asyncio.wait( 

291 ( 

292 asyncio.create_task(br.publish([1, 2.0, 3.0, 4.0], queue)), 

293 asyncio.create_task(event.wait()), 

294 ), 

295 timeout=self.timeout, 

296 ) 

297 

298 mock.assert_called_with({"a": 1, "b": 2, "args": (3, 4)}) 

299 

300 @pytest.mark.asyncio() 

301 async def test_base_publisher( 

302 self, queue: str, mock: MagicMock, event: asyncio.Event 

303 ) -> None: 

304 pub_broker = self.get_broker(apply_types=True) 

305 

306 args, kwargs = self.get_subscriber_params(queue) 

307 

308 @pub_broker.subscriber(*args, **kwargs) 

309 @pub_broker.publisher(queue + "resp") 

310 async def m() -> str: 

311 return "" 

312 

313 args2, kwargs2 = self.get_subscriber_params(queue + "resp") 

314 

315 @pub_broker.subscriber(*args2, **kwargs2) 

316 async def resp(msg: Any) -> None: 

317 event.set() 

318 mock(msg) 

319 

320 async with self.patch_broker(pub_broker) as br: 

321 await br.start() 

322 await asyncio.wait( 

323 ( 

324 asyncio.create_task(br.publish("", queue)), 

325 asyncio.create_task(event.wait()), 

326 ), 

327 timeout=self.timeout, 

328 ) 

329 

330 assert event.is_set() 

331 mock.assert_called_once_with("") 

332 

333 @pytest.mark.asyncio() 

334 async def test_publisher_object( 

335 self, queue: str, mock: MagicMock, event: asyncio.Event 

336 ) -> None: 

337 pub_broker = self.get_broker(apply_types=True) 

338 

339 publisher = pub_broker.publisher(queue + "resp") 

340 

341 args, kwargs = self.get_subscriber_params(queue) 

342 

343 @publisher 

344 @pub_broker.subscriber(*args, **kwargs) 

345 async def m() -> str: 

346 return "" 

347 

348 args, kwargs = self.get_subscriber_params(queue + "resp") 

349 

350 @pub_broker.subscriber(*args, **kwargs) 

351 async def resp(msg: Any) -> None: 

352 event.set() 

353 mock(msg) 

354 

355 async with self.patch_broker(pub_broker) as br: 

356 await br.start() 

357 await asyncio.wait( 

358 ( 

359 asyncio.create_task(br.publish("", queue)), 

360 asyncio.create_task(event.wait()), 

361 ), 

362 timeout=self.timeout, 

363 ) 

364 

365 mock.assert_called_once_with("") 

366 

367 @pytest.mark.asyncio() 

368 async def test_publish_manual( 

369 self, queue: str, mock: MagicMock, event: asyncio.Event 

370 ) -> None: 

371 pub_broker = self.get_broker(apply_types=True) 

372 

373 publisher = pub_broker.publisher(queue + "resp") 

374 

375 args, kwargs = self.get_subscriber_params(queue) 

376 

377 @pub_broker.subscriber(*args, **kwargs) 

378 async def m() -> None: 

379 await publisher.publish("") 

380 

381 args2, kwargs2 = self.get_subscriber_params(queue + "resp") 

382 

383 @pub_broker.subscriber(*args2, **kwargs2) 

384 async def resp(msg: Any) -> None: 

385 event.set() 

386 mock(msg) 

387 

388 async with self.patch_broker(pub_broker) as br: 

389 await br.start() 

390 await asyncio.wait( 

391 ( 

392 asyncio.create_task(br.publish("", queue)), 

393 asyncio.create_task(event.wait()), 

394 ), 

395 timeout=self.timeout, 

396 ) 

397 

398 mock.assert_called_once_with("") 

399 

400 @pytest.mark.asyncio() 

401 async def test_multiple_publishers( 

402 self, 

403 queue: str, 

404 mock: MagicMock, 

405 ) -> None: 

406 pub_broker = self.get_broker(apply_types=True) 

407 

408 event = anyio.Event() 

409 event2 = anyio.Event() 

410 

411 args, kwargs = self.get_subscriber_params(queue) 

412 

413 @pub_broker.publisher(queue + "resp2") 

414 @pub_broker.subscriber(*args, **kwargs) 

415 @pub_broker.publisher(queue + "resp") 

416 async def m() -> str: 

417 return "" 

418 

419 args2, kwargs2 = self.get_subscriber_params(queue + "resp") 

420 

421 @pub_broker.subscriber(*args2, **kwargs2) 

422 async def resp(msg: Any) -> None: 

423 event.set() 

424 mock.resp1(msg) 

425 

426 args3, kwargs3 = self.get_subscriber_params(queue + "resp2") 

427 

428 @pub_broker.subscriber(*args3, **kwargs3) 

429 async def resp2(msg: Any) -> None: 

430 event2.set() 

431 mock.resp2(msg) 

432 

433 async with self.patch_broker(pub_broker) as br: 

434 await br.start() 

435 await asyncio.wait( 

436 ( 

437 asyncio.create_task(br.publish("", queue)), 

438 asyncio.create_task(event.wait()), 

439 asyncio.create_task(event2.wait()), 

440 ), 

441 timeout=self.timeout, 

442 ) 

443 

444 mock.resp1.assert_called_once_with("") 

445 mock.resp2.assert_called_once_with("") 

446 

447 @pytest.mark.asyncio() 

448 async def test_reusable_publishers( 

449 self, 

450 queue: str, 

451 mock: MagicMock, 

452 ) -> None: 

453 pub_broker = self.get_broker(apply_types=True) 

454 

455 consume = anyio.Event() 

456 consume2 = anyio.Event() 

457 

458 pub = pub_broker.publisher(queue + "resp") 

459 

460 args, kwargs = self.get_subscriber_params(queue) 

461 

462 @pub 

463 @pub_broker.subscriber(*args, **kwargs) 

464 async def m() -> str: 

465 return "" 

466 

467 args2, kwargs2 = self.get_subscriber_params(queue + "2") 

468 

469 @pub 

470 @pub_broker.subscriber(*args2, **kwargs2) 

471 async def m2() -> str: 

472 return "" 

473 

474 args3, kwargs3 = self.get_subscriber_params(queue + "resp") 

475 

476 @pub_broker.subscriber(*args3, **kwargs3) 

477 async def resp() -> None: 

478 if not consume.is_set(): 

479 consume.set() 

480 else: 

481 consume2.set() 

482 mock() 

483 

484 async with self.patch_broker(pub_broker) as br: 

485 await br.start() 

486 await asyncio.wait( 

487 ( 

488 asyncio.create_task(br.publish("", queue)), 

489 asyncio.create_task(br.publish("", queue + "2")), 

490 asyncio.create_task(consume.wait()), 

491 asyncio.create_task(consume2.wait()), 

492 ), 

493 timeout=self.timeout, 

494 ) 

495 

496 assert mock.call_count == 2 

497 

498 @pytest.mark.asyncio() 

499 async def test_reply_to( 

500 self, queue: str, mock: MagicMock, event: asyncio.Event 

501 ) -> None: 

502 pub_broker = self.get_broker(apply_types=True) 

503 

504 args, kwargs = self.get_subscriber_params(queue + "reply") 

505 

506 @pub_broker.subscriber(*args, **kwargs) 

507 async def reply_handler(m: Any) -> None: 

508 event.set() 

509 mock(m) 

510 

511 args2, kwargs2 = self.get_subscriber_params(queue) 

512 

513 @pub_broker.subscriber(*args2, **kwargs2) 

514 async def handler(m: Any) -> Any: 

515 return m 

516 

517 async with self.patch_broker(pub_broker) as br: 

518 await br.start() 

519 

520 await asyncio.wait( 

521 ( 

522 asyncio.create_task( 

523 br.publish("Hello!", queue, reply_to=queue + "reply"), 

524 ), 

525 asyncio.create_task(event.wait()), 

526 ), 

527 timeout=self.timeout, 

528 ) 

529 

530 mock.assert_called_with("Hello!") 

531 

532 @pytest.mark.asyncio() 

533 async def test_no_reply( 

534 self, queue: str, mock: MagicMock, event: asyncio.Event 

535 ) -> None: 

536 class Mid(BaseMiddleware): 

537 async def after_processed(self, *args: Any, **kwargs: Any) -> Any: 

538 event.set() 

539 

540 return await super().after_processed(*args, **kwargs) 

541 

542 pub_broker = self.get_broker(apply_types=True) 

543 pub_broker.add_middleware(Mid) 

544 

545 args, kwargs = self.get_subscriber_params(queue + "reply") 

546 

547 @pub_broker.subscriber(*args, **kwargs) 

548 async def reply_handler(m: Any) -> None: 

549 mock(m) 

550 

551 args2, kwargs2 = self.get_subscriber_params(queue, no_reply=True) 

552 

553 @pub_broker.subscriber(*args2, **kwargs2) 

554 async def handler(m: Any) -> Any: 

555 return m 

556 

557 async with self.patch_broker(pub_broker) as br: 

558 await br.start() 

559 

560 await asyncio.wait( 

561 ( 

562 asyncio.create_task( 

563 br.publish("Hello!", queue, reply_to=queue + "reply"), 

564 ), 

565 asyncio.create_task(event.wait()), 

566 ), 

567 timeout=self.timeout, 

568 ) 

569 

570 assert not mock.called 

571 

572 @pytest.mark.asyncio() 

573 async def test_publisher_after_connect(self, queue: str) -> None: 

574 async with self.patch_broker(self.get_broker()) as br: 

575 # Should pass without error 

576 # suppress TestClient error due where is no suitable subscriber 

577 with suppress(SubscriberNotFound): 

578 await br.publisher(queue).publish(None) 

579 

580 @pytest.mark.asyncio() 

581 async def test_publisher_after_start( 

582 self, queue: str, mock: MagicMock, event: asyncio.Event 

583 ) -> None: 

584 pub_broker = self.get_broker(apply_types=True) 

585 

586 args, kwargs = self.get_subscriber_params(queue) 

587 

588 @pub_broker.subscriber(*args, **kwargs) 

589 async def handler(m: Any) -> None: 

590 event.set() 

591 mock(m) 

592 

593 async with self.patch_broker(pub_broker) as br: 

594 await br.start() 

595 

596 pub = br.publisher(queue) 

597 

598 await asyncio.wait( 

599 ( 

600 asyncio.create_task(pub.publish("Hello!")), 

601 asyncio.create_task(event.wait()), 

602 ), 

603 timeout=self.timeout, 

604 ) 

605 

606 mock.assert_called_with("Hello!") 

607 

608 @pytest.mark.asyncio() 

609 async def test_composition_context( 

610 self, 

611 queue: str, 

612 mock: MagicMock, 

613 mock2: MagicMock, 

614 event: asyncio.Event, 

615 event2: asyncio.Event, 

616 ) -> None: 

617 broker = self.get_broker( 

618 apply_types=True, 

619 context=ContextRepo({"broker_var": "BROKER 1"}), 

620 ) 

621 broker2 = self.get_broker( 

622 apply_types=True, 

623 context=ContextRepo({"broker_var": "BROKER 2"}), 

624 ) 

625 

626 app = FastStream(broker, broker2, context=ContextRepo({"app_var": "APP"})) 

627 

628 args, kwargs = self.get_subscriber_params(queue) 

629 

630 @broker.subscriber(*args, **kwargs) 

631 async def handle(app_var: Any = Context(), broker_var: Any = Context()) -> None: 

632 mock(app_var, broker_var) 

633 event.set() 

634 

635 args2, kwargs2 = self.get_subscriber_params(queue + "2") 

636 

637 @broker2.subscriber(*args2, **kwargs2) 

638 async def handle2(app_var: Any = Context(), broker_var: Any = Context()) -> None: 

639 mock2(app_var, broker_var) 

640 event2.set() 

641 

642 async with ( 

643 self.patch_broker(broker, broker2) as (br, br2), 

644 TestApp(app), 

645 ): 

646 await asyncio.wait( 

647 ( 

648 asyncio.create_task(br.publish("", queue)), 

649 asyncio.create_task(br2.publish("", queue + "2")), 

650 asyncio.create_task(event.wait()), 

651 asyncio.create_task(event2.wait()), 

652 ), 

653 timeout=self.timeout, 

654 ) 

655 

656 assert event.is_set() 

657 assert event2.is_set() 

658 mock.assert_called_once_with("APP", "BROKER 1") 

659 mock2.assert_called_once_with("APP", "BROKER 2")