Coverage for tests/asyncapi/base/v3_0_0/arguments.py: 98%
270 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
1import sys
2from dataclasses import dataclass
3from enum import Enum
4from typing import Annotated, Any, Literal
6import pydantic
7import pytest
8from dirty_equals import IsDict, IsPartialDict, IsStr
9from fast_depends import Depends
10from fastapi import Depends as APIDepends
12from faststream import Context
13from faststream._internal._compat import PYDANTIC_V2
14from tests.marks import pydantic_v2
16from .basic import AsyncAPI300Factory
19class FastAPICompatible(AsyncAPI300Factory):
20 is_fastapi: bool = False
22 broker_class: Any
23 dependency_builder: Any = staticmethod(APIDepends)
25 def test_default_naming(self) -> None:
26 broker = self.broker_class()
28 @broker.subscriber("test")
29 async def handle(msg: Any) -> None: ...
31 schema = self.get_spec(broker).to_jsonable()
33 channel_key = tuple(schema["channels"].keys())[0] # ruff: ignore[unnecessary-iterable-allocation-for-first-element]
34 operation_key = tuple(schema["operations"].keys())[0] # ruff: ignore[unnecessary-iterable-allocation-for-first-element]
36 assert channel_key == IsStr(regex=r"test[\w:]*:Handle"), channel_key
37 assert operation_key == IsStr(regex=r"test[\w:]*:HandleSubscribe"), operation_key
39 def test_custom_naming(self) -> None:
40 broker = self.broker_class()
42 @broker.subscriber("test", title="custom_name", description="test description")
43 async def handle(msg: Any) -> None: ...
45 schema = self.get_spec(broker).to_jsonable()
47 channel_key = tuple(schema["channels"].keys())[0] # ruff: ignore[unnecessary-iterable-allocation-for-first-element]
48 operation_key = tuple(schema["operations"].keys())[0] # ruff: ignore[unnecessary-iterable-allocation-for-first-element]
50 assert channel_key == "custom_name"
51 assert operation_key == "custom_name"
53 assert schema["channels"][channel_key]["description"] == "test description"
55 def test_slash_in_title(self) -> None:
56 broker = self.broker_class()
58 @broker.subscriber("test", title="/")
59 async def handle(msg: Any) -> None: ...
61 schema = self.get_spec(broker).to_jsonable()
63 channel_key = tuple(schema["channels"].keys())[0] # ruff: ignore[unnecessary-iterable-allocation-for-first-element]
64 operation_key = tuple(schema["operations"].keys())[0] # ruff: ignore[unnecessary-iterable-allocation-for-first-element]
66 assert channel_key == "."
67 # the title names the channel; `address` stays the address subscribed to
68 assert schema["channels"][channel_key]["address"] == "test"
70 assert operation_key == ".Subscribe"
72 assert next(iter(schema["components"]["messages"].keys())) == ".:SubscribeMessage"
73 assert (
74 schema["components"]["messages"][".:SubscribeMessage"]["title"]
75 == "/:SubscribeMessage"
76 )
78 assert next(iter(schema["components"]["schemas"].keys())) == ".:Message:Payload"
79 assert (
80 schema["components"]["schemas"][".:Message:Payload"]["title"]
81 == "/:Message:Payload"
82 )
84 def test_docstring_description(self) -> None:
85 broker = self.broker_class()
87 @broker.subscriber("test", title="custom_name")
88 async def handle(msg: Any) -> None:
89 """Test description."""
91 schema = self.get_spec(broker).to_jsonable()
92 key = tuple(schema["channels"].keys())[0] # ruff: ignore[unnecessary-iterable-allocation-for-first-element]
94 assert key == "custom_name"
95 assert schema["channels"][key]["description"] == "Test description.", schema[
96 "channels"
97 ][key]["description"]
99 def test_empty(self) -> None:
100 broker = self.broker_class()
102 @broker.subscriber("test")
103 async def handle() -> None: ...
105 schema = self.get_spec(broker).to_jsonable()
107 payload = schema["components"]["schemas"]
109 for key, v in payload.items():
110 assert key == "EmptyPayload"
111 assert v == {
112 "title": key,
113 "type": "null",
114 }
116 def test_no_type(self) -> None:
117 broker = self.broker_class()
119 @broker.subscriber("test")
120 async def handle(msg: Any) -> None: ...
122 schema = self.get_spec(broker).to_jsonable()
124 payload = schema["components"]["schemas"]
126 for key, v in payload.items():
127 assert key == "Handle:Message:Payload"
128 assert v == {"title": key}
130 def test_simple_type(self) -> None:
131 broker = self.broker_class()
133 @broker.subscriber("test")
134 async def handle(msg: int) -> None: ...
136 schema = self.get_spec(broker).to_jsonable()
138 payload = schema["components"]["schemas"]
139 assert next(iter(schema["channels"].values())).get("description") is None
141 for key, v in payload.items():
142 assert key == "Handle:Message:Payload"
143 assert v == {"title": key, "type": "integer"}
145 def test_simple_optional_type(self) -> None:
146 broker = self.broker_class()
148 @broker.subscriber("test")
149 async def handle(msg: int | None) -> None: ...
151 schema = self.get_spec(broker).to_jsonable()
153 payload = schema["components"]["schemas"]
155 for key, v in payload.items():
156 assert key == "Handle:Message:Payload"
157 assert v == IsDict(
158 {
159 "anyOf": [{"type": "integer"}, {"type": "null"}],
160 "title": key,
161 },
162 ) | IsDict(
163 { # TODO: remove when deprecating PydanticV1
164 "title": key,
165 "type": "integer",
166 },
167 ), v
169 def test_simple_type_with_default(self) -> None:
170 broker = self.broker_class()
172 @broker.subscriber("test")
173 async def handle(msg: int = 1) -> None: ...
175 schema = self.get_spec(broker).to_jsonable()
177 payload = schema["components"]["schemas"]
179 for key, v in payload.items():
180 assert key == "Handle:Message:Payload"
181 assert v == {
182 "default": 1,
183 "title": key,
184 "type": "integer",
185 }
187 def test_multi_args_no_type(self) -> None:
188 broker = self.broker_class()
190 @broker.subscriber("test")
191 async def handle(msg: Any, another: Any) -> None: ...
193 schema = self.get_spec(broker).to_jsonable()
195 payload = schema["components"]["schemas"]
197 for key, v in payload.items():
198 assert key == "Handle:Message:Payload"
199 assert v == {
200 "properties": {
201 "another": {"title": "Another"},
202 "msg": {"title": "Msg"},
203 },
204 "required": ["msg", "another"],
205 "title": key,
206 "type": "object",
207 }
209 def test_multi_args_with_type(self) -> None:
210 broker = self.broker_class()
212 @broker.subscriber("test")
213 async def handle(msg: str, another: int) -> None: ...
215 schema = self.get_spec(broker).to_jsonable()
217 payload = schema["components"]["schemas"]
219 for key, v in payload.items():
220 assert key == "Handle:Message:Payload"
221 assert v == {
222 "properties": {
223 "another": {"title": "Another", "type": "integer"},
224 "msg": {"title": "Msg", "type": "string"},
225 },
226 "required": ["msg", "another"],
227 "title": key,
228 "type": "object",
229 }
231 def test_multi_args_with_default(self) -> None:
232 broker = self.broker_class()
234 @broker.subscriber("test")
235 async def handle(msg: str, another: int | None = None) -> None: ...
237 schema = self.get_spec(broker).to_jsonable()
239 payload = schema["components"]["schemas"]
241 for key, v in payload.items():
242 assert key == "Handle:Message:Payload"
244 assert v == {
245 "properties": {
246 "another": IsDict(
247 {
248 "anyOf": [{"type": "integer"}, {"type": "null"}],
249 "default": None,
250 "title": "Another",
251 },
252 )
253 | IsDict(
254 { # TODO: remove when deprecating PydanticV1
255 "title": "Another",
256 "type": "integer",
257 },
258 ),
259 "msg": {"title": "Msg", "type": "string"},
260 },
261 "required": ["msg"],
262 "title": key,
263 "type": "object",
264 }
266 def test_dataclass(self) -> None:
267 @dataclass
268 class User:
269 id: int
270 name: str = ""
272 broker = self.broker_class()
274 @broker.subscriber("test")
275 async def handle(user: User) -> None: ...
277 schema = self.get_spec(broker).to_jsonable()
279 payload = schema["components"]["schemas"]
281 for key, v in payload.items():
282 assert key == "User"
283 assert v == {
284 "properties": {
285 "id": {"title": "Id", "type": "integer"},
286 "name": {"default": "", "title": "Name", "type": "string"},
287 },
288 "required": ["id"],
289 "title": key,
290 "type": "object",
291 }
293 def test_pydantic_model(self) -> None:
294 class User(pydantic.BaseModel):
295 name: str = ""
296 id: int
298 broker = self.broker_class()
300 @broker.subscriber("test")
301 async def handle(user: User) -> None: ...
303 schema = self.get_spec(broker).to_jsonable()
305 payload = schema["components"]["schemas"]
307 for key, v in payload.items():
308 assert key == "User"
309 assert v == {
310 "properties": {
311 "id": {"title": "Id", "type": "integer"},
312 "name": {"default": "", "title": "Name", "type": "string"},
313 },
314 "required": ["id"],
315 "title": key,
316 "type": "object",
317 }
319 def test_pydantic_model_with_enum(self) -> None:
320 class Status(str, Enum):
321 registered = "registered"
322 banned = "banned"
324 class User(pydantic.BaseModel):
325 name: str = ""
326 id: int
327 status: Status
329 broker = self.broker_class()
331 @broker.subscriber("test")
332 async def handle(user: User) -> None: ...
334 schema = self.get_spec(broker).to_jsonable()
336 payload = schema["components"]["schemas"]
338 assert payload == {
339 "Status": IsPartialDict(
340 {
341 "enum": ["registered", "banned"],
342 "title": "Status",
343 "type": "string",
344 },
345 ),
346 "User": {
347 "properties": {
348 "id": {"title": "Id", "type": "integer"},
349 "name": {"default": "", "title": "Name", "type": "string"},
350 "status": {"$ref": "#/components/schemas/Status"},
351 },
352 "required": ["id", "status"],
353 "title": "User",
354 "type": "object",
355 },
356 }, payload
358 def test_pydantic_model_mixed_regular(self) -> None:
359 class Email(pydantic.BaseModel):
360 addr: str
362 class User(pydantic.BaseModel):
363 name: str = ""
364 id: int
365 email: Email
367 broker = self.broker_class()
369 @broker.subscriber("test")
370 async def handle(user: User, description: str = "") -> None: ...
372 schema = self.get_spec(broker).to_jsonable()
374 payload = schema["components"]["schemas"]
376 assert payload == {
377 "Email": {
378 "title": "Email",
379 "type": "object",
380 "properties": {"addr": {"title": "Addr", "type": "string"}},
381 "required": ["addr"],
382 },
383 "User": {
384 "title": "User",
385 "type": "object",
386 "properties": {
387 "name": {"title": "Name", "default": "", "type": "string"},
388 "id": {"title": "Id", "type": "integer"},
389 "email": {"$ref": "#/components/schemas/Email"},
390 },
391 "required": ["id", "email"],
392 },
393 "Handle:Message:Payload": {
394 "title": "Handle:Message:Payload",
395 "type": "object",
396 "properties": {
397 "user": {"$ref": "#/components/schemas/User"},
398 "description": {
399 "title": "Description",
400 "default": "",
401 "type": "string",
402 },
403 },
404 "required": ["user"],
405 },
406 }
408 def test_nested_models_in_union_should_be_in_schemas(self) -> None:
409 """Test that nested Pydantic models in union types are promoted to components/schemas.
411 Fixes issue #2443: Nested Pydantic models are not included in AsyncAPI
412 components/schemas (inplaced instead).
413 """
415 class Email(pydantic.BaseModel):
416 addr: str
418 class User(pydantic.BaseModel):
419 name: str = ""
420 id: int
421 email: Email
423 class Other(pydantic.BaseModel):
424 id: int
426 broker = self.broker_class()
428 @broker.subscriber("test")
429 async def handle(body: User | Other) -> None: ...
431 schema = self.get_spec(broker).to_jsonable()
433 payload = schema["components"]["schemas"]
435 # Check that nested Email model is promoted to components/schemas
436 assert "Email" in payload
437 assert payload["Email"] == {
438 "title": "Email",
439 "type": "object",
440 "properties": {"addr": {"title": "Addr", "type": "string"}},
441 "required": ["addr"],
442 }
444 def test_nested_models_in_publisher_union_should_be_in_schemas(self) -> None:
445 """Test that nested Pydantic models in publisher union types are promoted to components/schemas.
447 Fixes issue #2443: Nested Pydantic models are not included in AsyncAPI
448 components/schemas (inplaced instead).
449 """
451 class Email(pydantic.BaseModel):
452 addr: str
454 class User(pydantic.BaseModel):
455 name: str = ""
456 id: int
457 email: Email
459 class Other(pydantic.BaseModel):
460 id: int
462 broker = self.broker_class()
464 publisher = broker.publisher("test")
466 @publisher
467 def handle0(msg: Any) -> User: ...
469 @publisher
470 def handle1(msg: Any) -> Other: ...
472 schema = self.get_spec(broker).to_jsonable()
474 payload = schema["components"]["schemas"]
476 # Check that nested Email model is promoted to components/schemas
477 assert "Email" in payload
478 assert payload["Email"] == {
479 "title": "Email",
480 "type": "object",
481 "properties": {"addr": {"title": "Addr", "type": "string"}},
482 "required": ["addr"],
483 }
485 def test_pydantic_model_with_example(self) -> None:
486 class User(pydantic.BaseModel):
487 name: str = ""
488 id: int
490 if PYDANTIC_V2: 490 ↛ 497line 490 didn't jump to line 497 because the condition on line 490 was always true
491 model_config = {
492 "json_schema_extra": {"examples": [{"name": "john", "id": 1}]},
493 }
495 else:
497 class Config:
498 schema_extra = {"examples": [{"name": "john", "id": 1}]} # ruff: ignore[mutable-class-default]
500 broker = self.broker_class()
502 @broker.subscriber("test")
503 async def handle(user: User) -> None: ...
505 schema = self.get_spec(broker).to_jsonable()
507 payload = schema["components"]["schemas"]
509 for key, v in payload.items():
510 assert key == "User"
511 assert v == {
512 "examples": [{"id": 1, "name": "john"}],
513 "properties": {
514 "id": {"title": "Id", "type": "integer"},
515 "name": {"default": "", "title": "Name", "type": "string"},
516 },
517 "required": ["id"],
518 "title": "User",
519 "type": "object",
520 }
522 def test_with_filter(self) -> None:
523 class User(pydantic.BaseModel):
524 name: str = ""
525 id: int
527 broker = self.broker_class()
529 sub = broker.subscriber("test")
531 @sub( # pragma: no branch
532 filter=lambda m: m.content_type == "application/json",
533 )
534 async def handle(id: int) -> None: ...
536 @sub
537 async def handle_default(msg: Any) -> None: ...
539 schema = self.get_spec(broker).to_jsonable()
541 assert (
542 len(
543 next(iter(schema["components"]["messages"].values()))["payload"]["oneOf"],
544 )
545 == 2
546 )
548 payload = schema["components"]["schemas"]
550 assert "Handle:Message:Payload" in list(payload.keys())
551 assert "HandleDefault:Message:Payload" in list(payload.keys())
553 def test_ignores_depends(self) -> None:
554 broker = self.broker_class()
556 def dep(name: str = "") -> Any:
557 return name
559 def dep2(name2: str) -> Any:
560 return name2
562 dependencies = (self.dependency_builder(dep2),)
563 message = self.dependency_builder(dep)
565 @broker.subscriber("test", dependencies=dependencies)
566 async def handle(id: int, message: Any = message) -> None: ...
568 schema = self.get_spec(broker).to_jsonable()
570 payload = schema["components"]["schemas"]
572 for key, v in payload.items():
573 assert key == "Handle:Message:Payload"
574 assert v == {
575 "properties": {
576 "id": {"title": "Id", "type": "integer"},
577 "name": {"default": "", "title": "Name", "type": "string"},
578 "name2": {"title": "Name2", "type": "string"},
579 },
580 "required": ["id", "name2"],
581 "title": key,
582 "type": "object",
583 }, v
585 @pydantic_v2
586 def test_discriminator(self) -> None:
587 class Sub2(pydantic.BaseModel):
588 type: Literal["sub2"]
590 class Sub(pydantic.BaseModel):
591 type: Literal["sub"]
593 broker = self.broker_class()
595 @broker.subscriber("test")
596 async def handle(
597 user: Annotated[Sub2 | Sub, pydantic.Field(discriminator="type")],
598 ) -> None: ...
600 schema = self.get_spec(broker).to_jsonable()
602 key = next(iter(schema["components"]["messages"].keys()))
604 assert key == IsStr(regex=r"test[\w:]*:Handle:SubscribeMessage"), key
606 p = schema["components"]["messages"][key]["payload"]
607 assert p == IsPartialDict({
608 "$ref": "#/components/schemas/Handle:Message:Payload",
609 }), p
611 assert schema["components"]["schemas"] == IsPartialDict({
612 "Sub": {
613 "properties": {
614 "type": IsPartialDict({"const": "sub", "title": "Type"}),
615 },
616 "required": ["type"],
617 "title": "Sub",
618 "type": "object",
619 },
620 "Sub2": {
621 "properties": {
622 "type": IsPartialDict({"const": "sub2", "title": "Type"}),
623 },
624 "required": ["type"],
625 "title": "Sub2",
626 "type": "object",
627 },
628 }), schema["components"]["schemas"]
630 payload = schema["components"]["schemas"].get("Handle:Message:Payload")
632 discriminator_payload = IsPartialDict({
633 "discriminator": "type",
634 "oneOf": [
635 {"$ref": "#/components/schemas/Sub2"},
636 {"$ref": "#/components/schemas/Sub"},
637 ],
638 "title": "Handle:Message:Payload",
639 })
641 if self.is_fastapi:
642 assert (
643 payload
644 == IsPartialDict({
645 "anyOf": [
646 {"$ref": "#/components/schemas/Sub2"},
647 {"$ref": "#/components/schemas/Sub"},
648 ],
649 })
650 | discriminator_payload
651 ), payload
653 else:
654 assert payload == discriminator_payload
656 @pydantic_v2
657 def test_nested_discriminator(self) -> None:
658 class Sub2(pydantic.BaseModel):
659 type: Literal["sub2"]
661 class Sub(pydantic.BaseModel):
662 type: Literal["sub"]
664 class Model(pydantic.BaseModel):
665 msg: Sub2 | Sub = pydantic.Field(..., discriminator="type")
667 broker = self.broker_class()
669 @broker.subscriber("test")
670 async def handle(user: Model) -> None: ...
672 schema = self.get_spec(broker).to_jsonable()
674 key = next(iter(schema["components"]["messages"].keys()))
675 assert key == IsStr(regex=r"test[\w:]*:Handle:SubscribeMessage")
676 assert schema["components"] == {
677 "messages": {
678 key: {
679 "title": key,
680 "correlationId": {"location": "$message.header#/correlation_id"},
681 "payload": {"$ref": "#/components/schemas/Model"},
682 },
683 },
684 "schemas": {
685 "Sub": {
686 "properties": {
687 "type": IsPartialDict({"const": "sub", "title": "Type"}),
688 },
689 "required": ["type"],
690 "title": "Sub",
691 "type": "object",
692 },
693 "Sub2": {
694 "properties": {
695 "type": IsPartialDict({"const": "sub2", "title": "Type"}),
696 },
697 "required": ["type"],
698 "title": "Sub2",
699 "type": "object",
700 },
701 "Model": {
702 "properties": {
703 "msg": {
704 "discriminator": "type",
705 "oneOf": [
706 {"$ref": "#/components/schemas/Sub2"},
707 {"$ref": "#/components/schemas/Sub"},
708 ],
709 "title": "Msg",
710 },
711 },
712 "required": ["msg"],
713 "title": "Model",
714 "type": "object",
715 },
716 },
717 }, schema["components"]
720class ArgumentsTestcase(FastAPICompatible):
721 dependency_builder: Any = staticmethod(Depends)
723 def test_pydantic_field(self) -> None:
724 broker = self.broker_class()
726 @broker.subscriber("msg")
727 async def msg(
728 msg: pydantic.PositiveInt = pydantic.Field(
729 1,
730 description="some field",
731 title="Perfect",
732 examples=[1],
733 ),
734 ) -> None: ...
736 schema = self.get_spec(broker).to_jsonable()
738 payload = schema["components"]["schemas"]
740 for key, v in payload.items():
741 assert key == "Perfect"
743 assert v == {
744 "default": 1,
745 "description": "some field",
746 "examples": [1],
747 "exclusiveMinimum": 0,
748 "title": "Perfect",
749 "type": "integer",
750 }
752 def test_ignores_custom_field(self) -> None:
753 broker = self.broker_class()
755 @broker.subscriber("test")
756 async def handle(
757 id: int,
758 user: str | None = None,
759 message: Any = Context(),
760 ) -> None: ...
762 schema = self.get_spec(broker).to_jsonable()
764 payload = schema["components"]["schemas"]
766 for key, v in payload.items():
767 assert v == IsDict(
768 {
769 "properties": {
770 "id": {"title": "Id", "type": "integer"},
771 "user": {
772 "anyOf": [{"type": "string"}, {"type": "null"}],
773 "default": None,
774 "title": "User",
775 },
776 },
777 "required": ["id"],
778 "title": key,
779 "type": "object",
780 },
781 ) | IsDict( # TODO: remove when deprecating PydanticV1
782 {
783 "properties": {
784 "id": {"title": "Id", "type": "integer"},
785 "user": {"title": "User", "type": "string"},
786 },
787 "required": ["id"],
788 "title": "Handle:Message:Payload",
789 "type": "object",
790 },
791 )
793 @pytest.mark.skipif(
794 sys.version_info >= (3, 14),
795 reason="Python 3.14 disallows redefining a class with the same name",
796 )
797 def test_overwrite_schema(self) -> None:
798 @dataclass
799 class User:
800 id: int
801 name: str = ""
803 broker = self.broker_class()
805 @broker.subscriber("test")
806 async def handle(user: User) -> None: ...
808 @dataclass
809 class User: # type: ignore[no-redef]
810 id: int
811 email: str = ""
813 @broker.subscriber("test2")
814 async def second_handle(user: User) -> None: ...
816 with pytest.warns(
817 RuntimeWarning,
818 match="Overwriting the message schema, data types have the same name",
819 ):
820 schema = self.get_spec(broker).to_jsonable()
822 payload = schema["components"]["schemas"]
824 assert len(payload) == 1
826 key, value = next(iter(payload.items()))
828 assert key == "User"
829 assert value == {
830 "properties": IsDict({
831 "id": {"title": "Id", "type": "integer"},
832 "email": {"default": "", "title": "Email", "type": "string"},
833 })
834 | IsDict({
835 "id": {"title": "Id", "type": "integer"},
836 "name": {"default": "", "title": "Name", "type": "string"},
837 }),
838 "required": ["id"],
839 "title": key,
840 "type": "object",
841 }