From 8a62d0b3fd2248e54cba8a2a5ba5d0709cd0cdba Mon Sep 17 00:00:00 2001 From: Tseluiko Aleksandr Date: Sat, 14 Nov 2026 16:38:20 +0300 Subject: [PATCH 1/8] refactor: share body binding rules between runtime and AsyncAPI --- .../subscription/annotation.md | 10 + faststream/_internal/di/body.py | 27 +++ faststream/_internal/di/config.py | 13 +- faststream/specification/asyncapi/message.py | 48 +++- tests/brokers/rabbit/test_body_binding.py | 98 ++++++++ tests/utils/test_body_binding.py | 213 ++++++++++++++++++ 6 files changed, 386 insertions(+), 23 deletions(-) create mode 100644 faststream/_internal/di/body.py create mode 100644 tests/brokers/rabbit/test_body_binding.py create mode 100644 tests/utils/test_body_binding.py diff --git a/docs/docs/en/getting-started/subscription/annotation.md b/docs/docs/en/getting-started/subscription/annotation.md index 190a45b15f7..a0c43bbef82 100644 --- a/docs/docs/en/getting-started/subscription/annotation.md +++ b/docs/docs/en/getting-started/subscription/annotation.md @@ -101,6 +101,16 @@ For this reason, **FastStream** supports per-argument message serialization: you ### Serialization details +The body parameters are the handler's ordinary inputs plus the external inputs +of its dependencies, including extra subscriber dependencies. Dependency results +and injected `Header`, `Path`, and `Context` values do not count as body parameters. +For example, one body input together with a header still receives the whole body; +it does not require an object wrapping that input under its parameter name. + +The same body parameter selection is used for handler invocation and AsyncAPI +payload generation. A header's Python parameter name does not hide a body input +with the same name in a dependency. + #### Simple message If you expect to consume a simple message like `#!python b"1"` or `#!python b"any_string"`, use a single argument as the function annotation. diff --git a/faststream/_internal/di/body.py b/faststream/_internal/di/body.py new file mode 100644 index 00000000000..f7bf017ae89 --- /dev/null +++ b/faststream/_internal/di/body.py @@ -0,0 +1,27 @@ +from inspect import Parameter +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from fast_depends.core import CallModel + from fast_depends.library.serializer import OptionItem + + +class BodyBinding: + """External body parameters, without dependency results or custom fields.""" + + __slots__ = ("params",) + + def __init__(self, call: "CallModel") -> None: + self.params = tuple(call.flat_params) + + @property + def single_parameter(self) -> "OptionItem | None": + return self.params[0] if len(self.params) == 1 else None + + @property + def unpack(self) -> bool: + single = self.single_parameter + # A lone *args parameter consumes the body's sequence elements. + return len(self.params) > 1 or ( + single is not None and single.kind is Parameter.VAR_POSITIONAL + ) diff --git a/faststream/_internal/di/config.py b/faststream/_internal/di/config.py index 9aaf00ae5db..af026b23373 100644 --- a/faststream/_internal/di/config.py +++ b/faststream/_internal/di/config.py @@ -1,4 +1,3 @@ -import inspect from collections.abc import Awaitable, Callable, Mapping, Reversible, Sequence from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Optional @@ -10,6 +9,7 @@ from faststream._internal.constants import EMPTY from faststream._internal.context import ContextRepo from faststream._internal.context.composition import ContextRepoComposition +from faststream._internal.di.body import BodyBinding from faststream._internal.utils import apply_types, to_async if TYPE_CHECKING: @@ -105,16 +105,7 @@ def _unwrap_message_to_fast_depends_decorator( func: Callable[..., Any], dependent: "CallModel", ) -> Callable[["StreamMessage[Any]"], Awaitable[Any]]: - dependant_params = dependent.flat_params - if len(dependant_params) <= 1: - if option := next(iter(dependant_params), None): - is_multi_params = option.kind is inspect.Parameter.VAR_POSITIONAL - else: - is_multi_params = False - else: - is_multi_params = True - - if is_multi_params: + if BodyBinding(dependent).unpack: async def decode_wrapper(message: "StreamMessage[Any]") -> Any: msg = await message.decode() diff --git a/faststream/specification/asyncapi/message.py b/faststream/specification/asyncapi/message.py index f51bb510dc6..988f5869804 100644 --- a/faststream/specification/asyncapi/message.py +++ b/faststream/specification/asyncapi/message.py @@ -10,6 +10,7 @@ get_model_fields, model_schema, ) +from faststream._internal.di.body import BodyBinding if TYPE_CHECKING: from fast_depends.core import CallModel @@ -21,13 +22,17 @@ def parse_handler_params(call: "CallModel", prefix: str = "") -> dict[str, Any]: model = cast("type[BaseModel] | None", getattr(model_container, "model", None)) assert model - body = get_model_schema( - create_model( - model.__name__, - **{p.field_name: (p.field_type, p.default_value) for p in call.flat_params}, # type: ignore[call-overload] - ), + binding = BodyBinding(call) + body_model = create_model( + model.__name__, + **{p.field_name: (p.field_type, p.default_value) for p in binding.params}, # type: ignore[call-overload] + ) + single = binding.single_parameter + body = _get_model_schema( + body_model, + get_model_fields(body_model), + single.field_name if single is not None else None, prefix=prefix, - exclude=tuple(call.custom_fields.keys()), ) if body is None: @@ -85,16 +90,32 @@ def get_model_schema( return None params = {k: v for k, v in get_model_fields(call).items() if k not in exclude} - params_number = len(params) + return _get_model_schema( + call, + params, + next(iter(params)) if len(params) == 1 else None, + prefix=prefix, + exclude=exclude, + ) + - if params_number == 0: +def _get_model_schema( + call: type[BaseModel], + params: dict[str, Any], + single_parameter: str | None, + *, + prefix: str, + exclude: Sequence[str] = (), +) -> dict[str, Any] | None: + if not params: return None model = None use_original_model = False - name, param = next(iter(params.items())) + name = single_parameter + param = params[name] if name is not None else None if ( - params_number == 1 + param is not None and param.annotation and isclass(param.annotation) and issubclass(param.annotation, BaseModel) # NOTE: 3.7-3.10 compatibility @@ -112,9 +133,12 @@ def get_model_schema( if required := body.get("required"): body["required"] = list(filter(lambda x: x not in exclude, required)) - if params_number == 1 and not use_original_model: + if name is not None and param is not None and not use_original_model: param_body: dict[str, Any] = body.get("properties", {}) - param_body = param_body[name] + # Validation aliases can change the single emitted property's name. + param_body = ( + next(iter(param_body.values())) if len(param_body) == 1 else param_body[name] + ) if defs := body.get(DEF_KEY): # single argument with useless reference diff --git a/tests/brokers/rabbit/test_body_binding.py b/tests/brokers/rabbit/test_body_binding.py new file mode 100644 index 00000000000..7d7288ffabd --- /dev/null +++ b/tests/brokers/rabbit/test_body_binding.py @@ -0,0 +1,98 @@ +from typing import Any + +import pydantic +import pytest +from fast_depends import Depends +from fast_depends.msgspec import MsgSpecSerializer +from fast_depends.pydantic import PydanticSerializer + +from faststream import Context, Header +from faststream.message import StreamMessage +from faststream.rabbit import RabbitBroker, TestRabbitBroker +from tests.asyncapi.base.v2_6_0.basic import get_2_6_0_schema +from tests.asyncapi.base.v3_0_0.basic import get_3_0_0_schema +from tests.marks import pydantic_v2 + + +@pytest.mark.rabbit() +@pytest.mark.asyncio() +@pytest.mark.parametrize("serializer", (PydanticSerializer(), MsgSpecSerializer())) +@pytest.mark.parametrize("schema_version", ("2.6.0", "3.0.0")) +@pytest.mark.parametrize("extra", (False, True)) +async def test_injected_name_does_not_hide_dependency_body( + serializer: Any, schema_version: str, extra: bool +) -> None: + broker = RabbitBroker(serializer=serializer) + seen: list[tuple[str, int | None]] = [] + dependencies: list[int] = [] + + def dependency(value: int) -> int: + dependencies.append(value) + return value + 1 + + async def handler( + value: str = Header("token"), + raw: StreamMessage[Any] = Context("message"), + result: int = Depends(dependency), + ) -> None: + assert raw.headers["token"] == value + seen.append((value, result)) + + async def with_extra( + value: str = Header("token"), + raw: StreamMessage[Any] = Context("message"), + ) -> None: + assert raw.headers["token"] == value + seen.append((value, None)) + + broker.subscriber("input", dependencies=[Depends(dependency)] if extra else [])( + with_extra if extra else handler + ) + get_schema = get_2_6_0_schema if schema_version == "2.6.0" else get_3_0_0_schema + schema = get_schema(broker) + payloads = schema["components"]["schemas"] + + assert len(payloads) == 1 + assert next(iter(payloads.values()))["type"] == "integer" + assert get_schema(broker) == schema + assert dependencies == [] + assert seen == [] + + async with TestRabbitBroker(broker) as test_broker: + await test_broker.publish(41, "input", headers={"token": "secret"}) + + assert seen == [("secret", None if extra else 42)] + assert dependencies == [41] + + +@pytest.mark.rabbit() +@pytest.mark.asyncio() +@pytest.mark.parametrize("schema_version", ("2.6.0", "3.0.0")) +@pydantic_v2 +async def test_dependency_validation_alias_keeps_single_body(schema_version: str) -> None: + broker = RabbitBroker() + seen: list[tuple[str, int]] = [] + + def dependency( + value: int = pydantic.Field( + ..., validation_alias=pydantic.AliasChoices("external", "value") + ), + ) -> int: + return value + 1 + + @broker.subscriber("input") + async def handler( + value: str = Header("token"), result: int = Depends(dependency) + ) -> None: + seen.append((value, result)) + + get_schema = get_2_6_0_schema if schema_version == "2.6.0" else get_3_0_0_schema + payloads = get_schema(broker)["components"]["schemas"] + assert len(payloads) == 1 + assert next(iter(payloads.values()))["type"] == "integer" + assert seen == [] + + async with TestRabbitBroker(broker) as test_broker: + await test_broker.publish(41, "input", headers={"token": "secret"}) + + assert seen == [("secret", 42)] diff --git a/tests/utils/test_body_binding.py b/tests/utils/test_body_binding.py new file mode 100644 index 00000000000..f89c68a7eea --- /dev/null +++ b/tests/utils/test_body_binding.py @@ -0,0 +1,213 @@ +import json +from collections.abc import Callable +from typing import Any + +import pytest +from fast_depends import Depends, Provider +from pydantic import BaseModel, Field + +from faststream._internal.di import FastDependsConfig +from faststream._internal.di.config import _unwrap_message_to_fast_depends_decorator +from faststream.message import StreamMessage, decode_message +from faststream.specification.asyncapi.message import parse_handler_params + + +class User(BaseModel): + name: str + + +async def scalar(value: int) -> int: + return value + + +async def mapping(value: dict[str, int]) -> dict[str, int]: + return value + + +async def sequence(value: list[int]) -> list[int]: + return value + + +async def model(user: User) -> dict[str, str]: + return {"name": user.name} + + +async def pair(a: int, b: int) -> tuple[int, int]: + return a, b + + +async def varargs(*items: tuple[int, ...]) -> tuple[Any, ...]: + return items + + +async def mixed(a: int, *rest: tuple[int, ...]) -> tuple[int, tuple[Any, ...]]: + return a, rest + + +async def keyword_only(*, value: int) -> int: + return value + + +async def empty() -> str: + return "empty" + + +async def decode(message: StreamMessage[Any]) -> Any: + return decode_message(message) + + +def message(value: Any) -> StreamMessage[Any]: + result = StreamMessage( + None, json.dumps(value).encode(), content_type="application/json" + ) + result.set_decoder(decode) + return result + + +@pytest.mark.asyncio() +@pytest.mark.parametrize( + ("handler", "payload", "expected", "schema_type"), + ( + (scalar, "12", 12, "integer"), + (mapping, {"n": "2"}, {"n": 2}, "object"), + (sequence, [1, "2"], [1, 2], "array"), + (model, {"name": "Ada"}, {"name": "Ada"}, "object"), + (pair, {"a": "1", "b": 2}, (1, 2), "object"), + (pair, [1, "2"], (1, 2), "object"), + (varargs, [1, "2"], (1, 2), "array"), + (mixed, [1, "2", 3], (1, (2, 3)), "object"), + (keyword_only, "12", 12, "integer"), + (empty, None, "empty", "null"), + (empty, {}, "empty", "null"), + ), +) +async def test_existing_body_shapes( + handler: Callable[..., Any], payload: Any, expected: Any, schema_type: str +) -> None: + built = FastDependsConfig().build_call(handler) + + assert parse_handler_params(built.dependent)["type"] == schema_type + assert await built.wrapped_call(message(payload)) == expected + + +@pytest.mark.asyncio() +@pytest.mark.parametrize("payload", (None, {}, [])) +async def test_whole_body_and_null_remain_distinct(payload: Any) -> None: + async def handler(value: Any) -> Any: + return value + + built = FastDependsConfig().build_call(handler) + + assert await built.wrapped_call(message(payload)) == payload + assert parse_handler_params(built.dependent)["title"] != "EmptyPayload" + + +@pytest.mark.asyncio() +@pytest.mark.parametrize("extra", (False, True)) +async def test_dependency_inputs_define_body_without_running_dependencies( + extra: bool, +) -> None: + seen: list[int] = [] + + def dependency(value: int) -> int: + seen.append(value) + return value + 1 + + async def handler(result: int = Depends(dependency)) -> int: + return result + + built = FastDependsConfig().build_call( + empty if extra else handler, + dependencies=(Depends(dependency),) if extra else (), + ) + schema = parse_handler_params(built.dependent) + + assert schema["type"] == "integer" + assert seen == [] + assert await built.wrapped_call(message(41)) == ("empty" if extra else 42) + assert seen == [41] + + +@pytest.mark.asyncio() +async def test_provider_override_inputs_define_body() -> None: + def dependency(value: int) -> int: + return value + + def replacement(a: int, b: int) -> int: + return a * 2 + b + + async def handler(result: int = Depends(dependency)) -> int: + return result + + provider = Provider() + provider.override(dependency, replacement) + built = FastDependsConfig(provider=provider).build_call(handler) + + assert set(parse_handler_params(built.dependent)["properties"]) == {"a", "b"} + assert await built.wrapped_call(message({"a": 10, "b": 22})) == 42 + + +@pytest.mark.asyncio() +async def test_multiple_parameters_preserve_aliases_and_defaults() -> None: + async def handler( + a: int = Field(..., alias="external"), b: int = 7 + ) -> tuple[int, int]: + return a, b + + built = FastDependsConfig().build_call(handler) + schema = parse_handler_params(built.dependent) + + assert set(schema["properties"]) == {"external", "b"} + assert schema["required"] == ["external"] + assert schema["properties"]["b"]["default"] == 7 + assert await built.wrapped_call(message({"external": 1})) == (1, 7) + + +@pytest.mark.asyncio() +@pytest.mark.parametrize( + ("signature", "payload", "expected_args", "expected_kwargs"), + ( + ("positional", 42, (42,), {}), + ("star", [1, 2], (1, 2), {}), + ("double_star", {"a": 1}, ({"a": 1},), {}), + ("mixed", {"a": 1, "b": 2}, (), {"a": 1, "b": 2}), + ), +) +async def test_argument_kinds_preserve_unwrapping( + signature: str, + payload: Any, + expected_args: tuple[Any, ...], + expected_kwargs: dict[str, Any], +) -> None: + async def positional(value: int, /) -> None: ... + + async def star(*items: tuple[int, ...]) -> None: ... + + async def double_star(**values: Any) -> None: ... + + async def mixed(a: int, **values: Any) -> None: ... + + calls: list[tuple[tuple[Any, ...], dict[str, Any]]] = [] + + async def receive(*args: Any, **kwargs: Any) -> None: + calls.append((args, kwargs)) + + handlers: dict[str, Callable[..., Any]] = { + "positional": positional, + "star": star, + "double_star": double_star, + "mixed": mixed, + } + built = FastDependsConfig().build_call(handlers[signature]) + wrapper = _unwrap_message_to_fast_depends_decorator(receive, built.dependent) + await wrapper(message(payload)) + + assert calls == [(expected_args, expected_kwargs)] + + +@pytest.mark.asyncio() +async def test_non_container_body_keeps_unpacking_error() -> None: + built = FastDependsConfig().build_call(pair) + + with pytest.raises(ValueError, match="Couldn't unpack `42` to multiple values"): + await built.wrapped_call(message(42)) From acf5b78c2fe48ea92f9f8515ef093a498008bf1d Mon Sep 17 00:00:00 2001 From: Tseluiko Aleksandr Date: Sat, 14 Nov 2026 19:23:01 +0300 Subject: [PATCH 2/8] feat: use FastDepends serializers for AsyncAPI payload schemas --- .../getting-started/subscription/msgspec.md | 22 + .../endpoint/publisher/specification.py | 60 +-- faststream/_internal/fastapi/get_dependant.py | 11 +- faststream/specification/asyncapi/message.py | 286 +++++----- faststream/specification/asyncapi/utils.py | 126 +++-- .../specification/asyncapi/v2_6_0/generate.py | 21 +- .../specification/asyncapi/v3_0_0/generate.py | 21 +- pyproject.toml | 3 +- tests/asyncapi/test_serializers.py | 508 ++++++++++++++++++ tests/fastapi/test_get_dependant.py | 8 +- 10 files changed, 828 insertions(+), 238 deletions(-) create mode 100644 tests/asyncapi/test_serializers.py diff --git a/docs/docs/en/getting-started/subscription/msgspec.md b/docs/docs/en/getting-started/subscription/msgspec.md index bdb82c557d1..12d3e1b3fca 100644 --- a/docs/docs/en/getting-started/subscription/msgspec.md +++ b/docs/docs/en/getting-started/subscription/msgspec.md @@ -149,3 +149,25 @@ To make your message schema reusable between different subscribers and publisher ```python linenums="1" hl_lines="1 15-17 22" {!> docs_src/getting_started/subscription/mqtt/msgspec_struct.py !} ``` + +## AsyncAPI schemas + +AsyncAPI payload schemas use the serializer configured on the broker, including +`msgspec.Struct`, `msgspec.field` aliases and `msgspec.Meta` constraints. This +requires FastDepends 4.0.0a0 or newer. Both AsyncAPI 2.6 and 3.0 are supported. + +The same backend describes subscriber bodies, publisher return annotations and +explicit publisher `schema=` types. A subscriber with one body parameter describes +the whole body; multiple body parameters form an object. Dependency inputs are +included, while injected context and header values are excluded from the body. +Schema generation does not execute handlers or dependencies. + +Publisher schemas continue to describe the declared payload type for the generic +broker encoder. Annotation serializers on a return type do not change the generic +publication path. Typed response encoding, raw bytes, custom codecs and batch +publication remain separate transport contracts. + +FastStream still uses Pydantic for its internal AsyncAPI document models and the +FastAPI integration. Selecting Msgspec for payloads does not yet remove the +Pydantic installation dependency. A disabled serializer cannot generate typed +payload schemas; no implicit Pydantic payload fallback is used. diff --git a/faststream/_internal/endpoint/publisher/specification.py b/faststream/_internal/endpoint/publisher/specification.py index 30394fb2c39..b022b31e1b6 100644 --- a/faststream/_internal/endpoint/publisher/specification.py +++ b/faststream/_internal/endpoint/publisher/specification.py @@ -2,12 +2,12 @@ from typing import TYPE_CHECKING, Any from fast_depends.core import build_call_model -from fast_depends.pydantic._compat import create_model, get_config_base # ruff: ignore[import-private-name] from typing_extensions import TypeVar as TypeVar313 from faststream._internal.configs import BrokerConfig, PublisherSpecificationConfig from faststream._internal.endpoint.specification import EndpointSpecification -from faststream.specification.asyncapi.message import get_model_schema +from faststream.exceptions import SetupError +from faststream.specification.asyncapi.message import payload_schema from faststream.specification.asyncapi.utils import to_camelcase if TYPE_CHECKING: @@ -43,48 +43,34 @@ def add_call(self, call: "AnyCallable") -> None: def get_payloads(self) -> list[tuple[dict[str, Any], str]]: payloads: list[tuple[dict[str, Any], str]] = [] - if self.config.schema_: - body = get_model_schema( - call=create_model( - "", - __config__=get_config_base(), - response__=(self.config.schema_, ...), - ), - prefix=f"{self.name}:Message", - ) - - if body: # pragma: no branch - payloads.append((body, "")) + di_state = self._outer_config.fd_config + factory = di_state._serializer + prefix = f"{self.name}:Message" + if self.config.schema_ is not None: + if factory is None: + msg = "AsyncAPI requires a serializer with JSON Schema support." + raise SetupError(msg) + body = payload_schema(factory, self.config.schema_, prefix=prefix) + payloads.append((body, "")) else: - di_state = self._outer_config.fd_config - for call in self.calls: call_model = build_call_model( call, dependency_provider=di_state.provider, - serializer_cls=di_state._serializer, + serializer_cls=factory, ) - - if call_model.serializer: - response_type = next( - iter(call_model.serializer.response_option.values()), - ).field_type - else: - response_type = None - - if response_type is not None and response_type is not Parameter.empty: - body = get_model_schema( - create_model( - "", - __config__=get_config_base(), - response__=(response_type, ...), - ), - prefix=f"{self.name}:Message", - ) - - if body: - payloads.append((body, to_camelcase(unwrap(call).__name__))) + serializer = call_model.serializer + if serializer is None: + continue + response_type = serializer.response_option["return"].field_type + if ( + factory is not None + and response_type is not None + and response_type is not Parameter.empty + ): + body = payload_schema(factory, response_type, prefix=prefix) + payloads.append((body, to_camelcase(unwrap(call).__name__))) return payloads diff --git a/faststream/_internal/fastapi/get_dependant.py b/faststream/_internal/fastapi/get_dependant.py index 25e8aea1b8d..fbe2facc558 100644 --- a/faststream/_internal/fastapi/get_dependant.py +++ b/faststream/_internal/fastapi/get_dependant.py @@ -4,6 +4,7 @@ from typing import TYPE_CHECKING, Annotated, Any, cast, get_args, get_origin from fast_depends.library.serializer import OptionItem +from fast_depends.pydantic import PydanticSerializer from fast_depends.utils import get_typed_annotation from fastapi import params from fastapi.dependencies.models import Dependant @@ -12,7 +13,7 @@ get_parameterless_sub_dependant, get_typed_signature, ) -from pydantic import Field, create_model +from pydantic import Field from pydantic.fields import FieldInfo from faststream._internal._compat import PYDANTIC_V2, PydanticUndefined @@ -25,9 +26,9 @@ class _FastStreamDependant(Dependant): """FastAPI dependant extended with fields required by FastStream.""" - __slots__ = ("custom_fields", "flat_params", "model") + __slots__ = ("custom_fields", "flat_params", "serializer_cls") - model: type[Any] + serializer_cls: PydanticSerializer custom_fields: dict[str, Any] flat_params: list[OptionItem] @@ -145,9 +146,7 @@ def _patch_fastapi_dependent(dependant: "models.Dependant") -> "models.Dependant f, ) - dependant.model = create_model( - getattr(call, "__name__", type(call).__name__), - ) + dependant.serializer_cls = PydanticSerializer(use_fastdepends_errors=False) dependant.custom_fields = {} dependant.flat_params = [ diff --git a/faststream/specification/asyncapi/message.py b/faststream/specification/asyncapi/message.py index 988f5869804..36a76ea2bfc 100644 --- a/faststream/specification/asyncapi/message.py +++ b/faststream/specification/asyncapi/message.py @@ -1,166 +1,162 @@ -from collections.abc import Sequence -from inspect import isclass -from typing import TYPE_CHECKING, Any, Optional, cast, overload - -from pydantic import BaseModel, create_model - -from faststream._internal._compat import ( - DEF_KEY, - PYDANTIC_V2, - get_model_fields, - model_schema, -) +from copy import deepcopy +from inspect import Parameter +from typing import TYPE_CHECKING, Annotated, Any, get_args, get_origin +from urllib.parse import unquote + +from fast_depends.library.schema_processing import process_schema +from fast_depends.library.serializer import OptionItem + from faststream._internal.di.body import BodyBinding +from faststream.exceptions import SetupError if TYPE_CHECKING: + from collections.abc import Sequence + from fast_depends.core import CallModel + from fast_depends.library.serializer import SerializerProto -def parse_handler_params(call: "CallModel", prefix: str = "") -> dict[str, Any]: - """Parses the handler parameters.""" - model_container = getattr(call, "serializer", call) - model = cast("type[BaseModel] | None", getattr(model_container, "model", None)) - assert model +_DEFINITIONS = ("$defs", "definitions") - binding = BodyBinding(call) - body_model = create_model( - model.__name__, - **{p.field_name: (p.field_type, p.default_value) for p in binding.params}, # type: ignore[call-overload] - ) - single = binding.single_parameter - body = _get_model_schema( - body_model, - get_model_fields(body_model), - single.field_name if single is not None else None, - prefix=prefix, - ) - if body is None: +def parse_handler_params(call: "CallModel", prefix: str = "") -> dict[str, Any]: + """Describe the same external body parameters used by message binding.""" + binding = BodyBinding(call) + if not binding.params: return {"title": "EmptyPayload", "type": "null"} - return body - - -@overload -def get_response_schema(call: None, prefix: str = "") -> None: ... - - -@overload -def get_response_schema(call: "CallModel", prefix: str = "") -> dict[str, Any]: ... - - -def get_response_schema( - call: Optional["CallModel"], - prefix: str = "", -) -> dict[str, Any] | None: - """Get the response schema for a given call.""" - return get_model_schema( - getattr( - call, - "response_model", - None, - ), # NOTE: FastAPI Dependant object compatibility - prefix=prefix, + factory = call.serializer_cls + if factory is None: + msg = "AsyncAPI requires a serializer with JSON Schema support." + raise SetupError(msg) + serializer = factory( + name=f"{prefix}:Payload", + options=list(binding.params), + response_type=Parameter.empty, ) + single = binding.single_parameter + document = serializer.get_schema() + root = _schema_root(document) + properties = root.get("properties", {}) + emitted_name = next(iter(properties)) if len(properties) == 1 else None + schema = process_schema(document, embed=single is not None) + body = prepare_payload(schema, prefix=prefix) + if single is not None: + title = _field_title(single) + if ( + "$ref" not in schema + and emitted_name is not None + and body.get("title") == emitted_name.replace("_", " ").title() + and title != body.get("title") + ): + body["title"] = f"{prefix}:Payload" + return body -@overload -def get_model_schema( - call: None, - prefix: str = "", - exclude: Sequence[str] = (), -) -> None: ... - - -@overload -def get_model_schema( - call: type[BaseModel], - prefix: str = "", - exclude: Sequence[str] = (), -) -> dict[str, Any]: ... - - -def get_model_schema( - call: type[BaseModel] | None, +def payload_schema( + factory: "SerializerProto", + annotation: Any, prefix: str = "", - exclude: Sequence[str] = (), -) -> dict[str, Any] | None: - """Get the schema of a model.""" - if call is None: - return None - - params = {k: v for k, v in get_model_fields(call).items() if k not in exclude} - return _get_model_schema( - call, - params, - next(iter(params)) if len(params) == 1 else None, - prefix=prefix, - exclude=exclude, +) -> dict[str, Any]: + """Describe the declared payload type for the generic publisher encoder.""" + serializer = factory( + name=f"{prefix}:Payload", + options=[OptionItem("payload", annotation)], + response_type=Parameter.empty, ) - - -def _get_model_schema( - call: type[BaseModel], - params: dict[str, Any], - single_parameter: str | None, - *, - prefix: str, - exclude: Sequence[str] = (), -) -> dict[str, Any] | None: - if not params: - return None - - model = None - use_original_model = False - name = single_parameter - param = params[name] if name is not None else None + document = serializer.get_schema() + root = _schema_root(document) + properties = root.get("properties", {}) + emitted_name = next(iter(properties)) if len(properties) == 1 else "payload" + schema = process_schema(document, embed=True) + body = prepare_payload(schema, prefix=prefix) if ( - param is not None - and param.annotation - and isclass(param.annotation) - and issubclass(param.annotation, BaseModel) # NOTE: 3.7-3.10 compatibility + "$ref" not in schema + and body.get("title") == emitted_name.replace("_", " ").title() ): - model = param.annotation - use_original_model = True - - if model is None: - model = call - - body: dict[str, Any] = model_schema(model) - body["properties"] = body.get("properties", {}) - for i in exclude: - body["properties"].pop(i, None) - if required := body.get("required"): - body["required"] = list(filter(lambda x: x not in exclude, required)) - - if name is not None and param is not None and not use_original_model: - param_body: dict[str, Any] = body.get("properties", {}) - # Validation aliases can change the single emitted property's name. - param_body = ( - next(iter(param_body.values())) if len(param_body) == 1 else param_body[name] - ) - - if defs := body.get(DEF_KEY): - # single argument with useless reference - if param_body.get("$ref"): - ref_obj: dict[str, Any] = next(iter(defs.values())) - ref_obj[DEF_KEY] = { - k: v for k, v in defs.items() if k != ref_obj.get("title") - } - return ref_obj - param_body[DEF_KEY] = defs + body["title"] = f"{prefix}:Payload" + return body - original_title = param.title if PYDANTIC_V2 else param.field_info.title - if original_title: - use_original_model = True - param_body["title"] = original_title - else: - param_body["title"] = name +def prepare_payload(schema: dict[str, Any], *, prefix: str) -> dict[str, Any]: + """Keep native schema metadata while giving the payload a component name.""" + body = deepcopy(schema) + if "$id" in body: + body.setdefault("title", f"{prefix}:Payload") + return body + definitions = {key: body.pop(key) for key in _DEFINITIONS if key in body} + reference = body.get("$ref") + if isinstance(reference, str) and reference.startswith("#/"): + target = _lookup_reference(schema, reference) + if isinstance(target, dict) and target is not schema and "$id" not in target: + siblings = {k: v for k, v in body.items() if k != "$ref"} + annotations = { + "title", + "description", + "default", + "examples", + "deprecated", + "readOnly", + "writeOnly", + } + if siblings.keys() - annotations: + body = { + **siblings, + "allOf": [deepcopy(target), *siblings.get("allOf", [])], + } + else: + body = {**deepcopy(target), **siblings} + body.setdefault("title", f"{prefix}:Payload") + for key, values in definitions.items(): + # References to this component remain valid after its definition moves. + if isinstance(reference, str) and reference.startswith(f"#/{key}/"): + name = ( + unquote(reference[len(key) + 3 :]).replace("~1", "/").replace("~0", "~") + ) + if name == body["title"]: + values.pop(name, None) + if values: + body[key] = values + return body - body = param_body - if not use_original_model: - body["title"] = f"{prefix}:Payload" - - return body +def _lookup_reference(document: dict[str, Any], reference: str) -> dict[str, Any] | None: + if not reference.startswith("#/"): + return None + target: Any = document + for raw_token in unquote(reference[2:]).split("/"): + if target is not document and isinstance(target, dict) and "$id" in target: + return None + token = raw_token.replace("~1", "/").replace("~0", "~") + if isinstance(target, dict): + target = target.get(token) + elif isinstance(target, list) and token.isdigit() and int(token) < len(target): + target = target[int(token)] + else: + return None + return target if isinstance(target, dict) else None + + +def _schema_root(document: dict[str, Any]) -> dict[str, Any]: + root = document + seen: set[str] = set() + while isinstance(reference := root.get("$ref"), str) and reference not in seen: + seen.add(reference) + if "$id" in root or not reference.startswith("#/"): + break + target = _lookup_reference(document, reference) + if not isinstance(target, dict): + break + root = target + return root + + +def _field_title(parameter: "OptionItem") -> str | None: + annotation = parameter.field_type + metadata: Sequence[Any] = ( + get_args(annotation)[1:] if get_origin(annotation) is Annotated else () + ) + for value in reversed((*metadata, parameter.default_value)): + if isinstance(title := getattr(value, "title", None), str): + return title + return None diff --git a/faststream/specification/asyncapi/utils.py b/faststream/specification/asyncapi/utils.py index df56e286586..222106cf01f 100644 --- a/faststream/specification/asyncapi/utils.py +++ b/faststream/specification/asyncapi/utils.py @@ -1,5 +1,6 @@ +from copy import deepcopy from typing import Any -from urllib.parse import quote +from urllib.parse import quote, unquote def to_camelcase(*names: str) -> str: @@ -58,34 +59,99 @@ def _encode_json_pointer_part(part: str) -> str: return quote(pointer_part, safe="~:._-") -def move_pydantic_refs( - original: Any, - key: str, -) -> Any: - """Remove pydantic references and replacem them by real schemas.""" - if not isinstance(original, dict): - return original - - data = original.copy() - - for k in data: - item = data[k] - - if isinstance(item, str): - if key in item: - data[k] = data[k].replace(key, "components/schemas") - - elif isinstance(item, dict): - data[k] = move_pydantic_refs(data[k], key) - - elif isinstance(item, list): - for i in range(len(data[k])): - data[k][i] = move_pydantic_refs(item[i], key) +_SCHEMA_MAPS = { + "properties", + "patternProperties", + "dependentSchemas", + "dependencies", + "$defs", + "definitions", +} +_SCHEMA_LISTS = {"allOf", "anyOf", "oneOf", "prefixItems"} +_SCHEMA_VALUES = { + "additionalProperties", + "additionalItems", + "unevaluatedProperties", + "unevaluatedItems", + "propertyNames", + "items", + "contains", + "not", + "if", + "then", + "else", + "contentSchema", +} + + +def move_schema_refs(original: Any, *, root_name: str) -> Any: + """Move local definitions to AsyncAPI components without changing data literals.""" + data = deepcopy(original) + + def rewrite(value: str, root_ref: str) -> str: + for key in ("$defs", "definitions"): + prefix = f"#/{key}/" + if value.startswith(prefix): + name, *tail = unquote(value[len(prefix) :]).split("/") + name = name.replace("~1", "/").replace("~0", "~") + target = ref("components", "schemas", clear_key(name))["$ref"] + return target + ( + "/" + quote("/".join(tail), safe="/~:._-") if tail else "" + ) + if value == "#" or value.startswith("#/"): + return root_ref + value[1:] + return value + + def visit(schema: Any, root_ref: str) -> None: + if not isinstance(schema, dict) or "$id" in schema: + return + for key in ("$ref", "$dynamicRef", "$recursiveRef"): + if isinstance(value := schema.get(key), str): + schema[key] = rewrite(value, root_ref) + discriminator = schema.get("discriminator") + if isinstance(discriminator, dict): + if isinstance(mapping := discriminator.get("mapping"), dict): + discriminator["mapping"] = { + k: rewrite(v, root_ref) if isinstance(v, str) else v + for k, v in mapping.items() + } + if "propertyName" in discriminator: + schema["discriminator"] = discriminator["propertyName"] + for key, value in schema.items(): + if key in _SCHEMA_MAPS and isinstance(value, dict): + for child in value.values(): + visit(child, root_ref) + elif key == "oneOf" and isinstance(value, dict): + # FastStream's overloaded-handler payloads use a named map. + for name, child in value.items(): + child_name = ( + child.get("title", name) if isinstance(child, dict) else name + ) + if not isinstance(child_name, str): + child_name = name + visit( + child, ref("components", "schemas", clear_key(child_name))["$ref"] + ) + elif (key in _SCHEMA_LISTS or key == "items") and isinstance(value, list): + for child in value: + visit(child, root_ref) + elif key in _SCHEMA_VALUES: + visit(value, root_ref) + + title = data.get("title", root_name) if isinstance(data, dict) else root_name + visit(data, ref("components", "schemas", clear_key(title))["$ref"]) + return data - if ( - isinstance(desciminator := data.get("discriminator"), dict) - and "propertyName" in desciminator - ): - data["discriminator"] = desciminator["propertyName"] - return data +def pop_schema_definitions(payload: dict[str, Any]) -> dict[str, Any]: + if "$id" in payload: + return {} + definitions: dict[str, Any] = {} + for key in ("$defs", "definitions"): + for name, schema in (payload.pop(key, None) or {}).items(): + normalized_name = clear_key(name) + if normalized_name in definitions and definitions[normalized_name] != schema: + msg = f"Conflicting schema definitions for {normalized_name!r}." + raise ValueError(msg) + definitions[normalized_name] = schema + return definitions diff --git a/faststream/specification/asyncapi/v2_6_0/generate.py b/faststream/specification/asyncapi/v2_6_0/generate.py index 58f3bdc8c55..11101655cd5 100644 --- a/faststream/specification/asyncapi/v2_6_0/generate.py +++ b/faststream/specification/asyncapi/v2_6_0/generate.py @@ -2,9 +2,13 @@ from collections.abc import Iterable, Sequence from typing import TYPE_CHECKING, Any, Optional, Union -from faststream._internal._compat import DEF_KEY from faststream._internal.constants import ContentTypes -from faststream.specification.asyncapi.utils import clear_key, move_pydantic_refs, ref +from faststream.specification.asyncapi.utils import ( + clear_key, + move_schema_refs, + pop_schema_definitions, + ref, +) from faststream.specification.asyncapi.v2_6_0.schema import ( ApplicationInfo, ApplicationSchema, @@ -269,10 +273,9 @@ def _resolve_msg_payloads( Payloads and messages are editable dicts to store schemas for reference in AsyncAPI. """ one_of_list: list[Reference] = [] - m.payload = move_pydantic_refs(m.payload, DEF_KEY) + m.payload = move_schema_refs(m.payload, root_name=f"{channel_name}Payload") - if DEF_KEY in m.payload: - payloads.update(m.payload.pop(DEF_KEY)) + payloads.update(pop_schema_definitions(m.payload)) one_of = m.payload.get("oneOf") if isinstance(one_of, dict): @@ -280,11 +283,11 @@ def _resolve_msg_payloads( formatted_payload_title = clear_key(p_title) # Promote nested Pydantic $defs from each payload into components/schemas # so that referenced nested models are available globally. - if isinstance(p, dict) and DEF_KEY in p: - defs = p.pop(DEF_KEY) or {} + if isinstance(p, dict): + defs = pop_schema_definitions(p) for def_name, def_schema in defs.items(): payloads[clear_key(def_name)] = def_schema - payloads.update(p.pop(DEF_KEY, {})) + payloads.update(pop_schema_definitions(p)) if formatted_payload_title not in payloads: payloads[formatted_payload_title] = p one_of_list.append( @@ -302,7 +305,7 @@ def _resolve_msg_payloads( one_of_list.append(Reference(**ref("components", "schemas", p_title))) if not one_of_list: - payloads.update(m.payload.pop(DEF_KEY, {})) + payloads.update(pop_schema_definitions(m.payload)) p_title = m.payload.get("title", f"{channel_name}Payload") p_title = clear_key(p_title) if p_title in payloads and payloads[p_title] != m.payload: diff --git a/faststream/specification/asyncapi/v3_0_0/generate.py b/faststream/specification/asyncapi/v3_0_0/generate.py index f37c8751efe..895437b496d 100644 --- a/faststream/specification/asyncapi/v3_0_0/generate.py +++ b/faststream/specification/asyncapi/v3_0_0/generate.py @@ -4,9 +4,13 @@ from typing import TYPE_CHECKING, Any, Optional, Union from urllib.parse import urlparse -from faststream._internal._compat import DEF_KEY from faststream._internal.constants import ContentTypes -from faststream.specification.asyncapi.utils import clear_key, move_pydantic_refs, ref +from faststream.specification.asyncapi.utils import ( + clear_key, + move_schema_refs, + pop_schema_definitions, + ref, +) from faststream.specification.asyncapi.v3_0_0.schema import ( ApplicationInfo, ApplicationSchema, @@ -331,13 +335,14 @@ def _resolve_msg_payloads( ) -> Reference: assert isinstance(m.payload, dict) - m.payload = move_pydantic_refs(m.payload, DEF_KEY) + m.payload = move_schema_refs( + m.payload, root_name=f"{channel_name}:{message_name}:Payload" + ) message_name = clear_key(message_name) channel_name = clear_key(channel_name) - if DEF_KEY in m.payload: - payloads.update(m.payload.pop(DEF_KEY)) + payloads.update(pop_schema_definitions(m.payload)) one_of = m.payload.get("oneOf", None) if isinstance(one_of, dict): @@ -346,8 +351,8 @@ def _resolve_msg_payloads( for name, payload in one_of.items(): # Promote nested Pydantic $defs from each payload into components/schemas # so that referenced nested models are available globally. - if isinstance(payload, dict) and DEF_KEY in payload: - defs = payload.pop(DEF_KEY) or {} + if isinstance(payload, dict): + defs = pop_schema_definitions(payload) for def_name, def_schema in defs.items(): payloads[clear_key(def_name)] = def_schema processed_payloads[clear_key(name)] = payload @@ -361,7 +366,7 @@ def _resolve_msg_payloads( **ref("components", "messages", f"{channel_name}:{message_name}"), ) - payloads.update(m.payload.pop(DEF_KEY, {})) + payloads.update(pop_schema_definitions(m.payload)) payload_name = m.payload.get("title", f"{channel_name}:{message_name}:Payload") payload_name = clear_key(payload_name) diff --git a/pyproject.toml b/pyproject.toml index df29c477b34..fc93d274eaa 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -53,12 +53,11 @@ classifiers = [ "Environment :: Web Environment", "Framework :: AsyncIO", "Framework :: Pydantic", - "Framework :: Pydantic :: 1", "Framework :: Pydantic :: 2", ] dependencies = [ - "fast-depends[pydantic]>=3.0.9", + "fast-depends[pydantic]>=4.0.0a0,<5.0.0", "typing-extensions>=4.12.0", "anyio>=4.14.2,<5", ] diff --git a/tests/asyncapi/test_serializers.py b/tests/asyncapi/test_serializers.py new file mode 100644 index 00000000000..61cabb10f48 --- /dev/null +++ b/tests/asyncapi/test_serializers.py @@ -0,0 +1,508 @@ +from copy import deepcopy +from importlib import import_module +from typing import Annotated, Any, Literal +from urllib.parse import unquote + +import msgspec +import pytest +from fast_depends import Depends, Provider +from fast_depends.library import CustomField, SchemaField +from fast_depends.library.schema_processing import process_schema +from fast_depends.library.serializer import Serializer, SerializerProto +from fast_depends.msgspec import MsgSpecSerializer +from fast_depends.pydantic import PydanticSerializer +from pydantic import Field, PlainSerializer + +from faststream._internal.di import FastDependsConfig +from faststream.exceptions import SetupError +from faststream.message import encode_message +from faststream.rabbit import RabbitBroker +from faststream.specification import AsyncAPI +from faststream.specification.asyncapi.message import ( + parse_handler_params, + prepare_payload, +) + + +class Item(msgspec.Struct, rename="camel", tag="item", omit_defaults=True): + item_id: Annotated[int, msgspec.Meta(gt=0)] + label: str = "" + + +class Tree(msgspec.Struct): + children: list["Tree"] = msgspec.field(default_factory=list) + + +@pytest.fixture(params=("2.6.0", "3.0.0")) +def specification(request: pytest.FixtureRequest): + def generate(broker): + factory = AsyncAPI(schema_version=request.param) + factory.add_broker(broker) + return factory.to_specification().to_jsonable() + + return generate + + +def assert_local_refs_resolve(document): + def visit(value): + if isinstance(value, dict): + if "$id" in value: + return + if isinstance(reference := value.get("$ref"), str) and reference.startswith( + "#/" + ): + target = document + for token in unquote(reference[2:]).split("/"): + target = target[token.replace("~1", "/").replace("~0", "~")] + for key, child in value.items(): + if key not in {"default", "examples", "enum", "const"}: + visit(child) + elif isinstance(value, list): + for child in value: + visit(child) + + visit(document) + + +@pytest.mark.parametrize("publisher", (False, True)) +@pytest.mark.parametrize("annotation", (Item, list[Item], Tree)) +def test_msgspec_struct_payloads(specification, publisher, annotation): + broker = RabbitBroker(serializer=MsgSpecSerializer()) + if publisher: + + @broker.publisher("out") + async def handle() -> annotation: ... + + else: + + @broker.subscriber("in") + async def handle(value: annotation): ... + + document = specification(broker) + schemas = document["components"]["schemas"] + assert_local_refs_resolve(document) + if annotation is Tree: + assert schemas["Tree"]["properties"]["children"]["items"] == { + "$ref": "#/components/schemas/Tree" + } + else: + assert schemas["Item"]["properties"] == { + "type": {"enum": ["item"]}, + "itemId": {"type": "integer", "exclusiveMinimum": 0}, + "label": {"type": "string", "default": ""}, + } + assert schemas["Item"]["required"] == ["type", "itemId"] + if annotation == list[Item]: + assert any( + value.get("items") == {"$ref": "#/components/schemas/Item"} + for value in schemas.values() + ) + + +def test_explicit_msgspec_publisher_schema(specification): + broker = RabbitBroker(serializer=MsgSpecSerializer()) + broker.publisher("out", schema=Item) + document = specification(broker) + assert document["components"]["schemas"]["Item"]["required"] == ["type", "itemId"] + assert_local_refs_resolve(document) + + +def test_msgspec_field_alias_and_constraint(specification): + broker = RabbitBroker(serializer=MsgSpecSerializer()) + + @broker.subscriber("in") + async def handle( + count: Annotated[int, msgspec.Meta(ge=1)] = msgspec.field(name="size"), + label: Literal["a", "b"] = "a", + ): ... + + schema = specification(broker)["components"]["schemas"]["Handle:Message:Payload"] + assert schema["properties"]["size"] == {"type": "integer", "minimum": 1} + assert schema["properties"]["label"] == {"enum": ["a", "b"], "default": "a"} + assert schema["required"] == ["size"] + + +@pytest.mark.parametrize("factory", (PydanticSerializer, MsgSpecSerializer)) +def test_custom_field_schemas_stay_outside_body(factory): + class Header(CustomField): + def get_schema(self, parameter): + return SchemaField( + parameter.field_name, parameter.field_type, source="headers" + ) + + async def handler(payload: int, token: Annotated[str, Header()]): ... + + call = FastDependsConfig(serializer=factory()).build_call(handler) + assert parse_handler_params(call.dependent, "Handler:Message") == { + "title": "Handler:Message:Payload", + "type": "integer", + } + + +def test_selected_factory_configuration(specification): + broker = RabbitBroker( + serializer=PydanticSerializer(pydantic_config={"alias_generator": str.upper}) + ) + + @broker.subscriber("in") + async def handle(first: int, second: str): ... + + schema = specification(broker)["components"]["schemas"]["Handle:Message:Payload"] + assert set(schema["properties"]) == {"FIRST", "SECOND"} + assert schema["required"] == ["FIRST", "SECOND"] + + +def test_explicit_field_title(specification): + broker = RabbitBroker() + + @broker.subscriber("in") + async def handle(value: Annotated[int, Field(title="Counter", gt=0)]): ... + + assert specification(broker)["components"]["schemas"]["Counter"] == { + "title": "Counter", + "type": "integer", + "exclusiveMinimum": 0, + } + + +def test_publisher_keeps_generic_annotation_encoding_contract(specification): + annotation = Annotated[int, PlainSerializer(str, return_type=str)] + factory = PydanticSerializer() + broker = RabbitBroker(serializer=factory) + + @broker.publisher("out") + async def handle() -> annotation: + return 42 + + schemas = specification(broker)["components"]["schemas"] + assert next(iter(schemas.values()))["type"] == "integer" + assert encode_message(42, factory)[0] == b"42" + + +def test_dependency_override_changes_body_schema(): + provider = Provider() + + async def dependency(count: int): ... + async def replacement(item: Item): ... + async def handler(value: Annotated[Any, Depends(dependency)]): ... + + call = FastDependsConfig( + serializer=MsgSpecSerializer(), provider=provider + ).build_call(handler) + assert parse_handler_params(call.dependent)["type"] == "integer" + with provider.scope(dependency, replacement): + assert parse_handler_params(call.dependent)["title"] == "Item" + assert parse_handler_params(call.dependent)["type"] == "integer" + + +class Opaque: + pass + + +class NativeFactory(SerializerProto): + def __init__(self): + self.document = { + "$ref": "#/definitions/Actual", + "definitions": { + "Unused": {"type": "integer"}, + "Actual": { + "title": "Actual", + "type": "string", + "pattern": "^x", + "description": "literal #/definitions/Unused", + "examples": [{"$ref": "#/definitions/Unused"}], + }, + }, + } + + def __call__(self, *, name, options, response_type): + document = self.document + + class NativeSerializer(Serializer): + def __call__(self, kwargs): + return kwargs + + def get_schema(self, *, embed=False, exclude=(), resolve_refs=False): + schema = { + "type": "object", + "properties": { + p.field_name: {"$ref": document["$ref"]} for p in options + }, + "definitions": document["definitions"], + } + return process_schema(schema, embed=embed, resolve_refs=resolve_refs) + + return NativeSerializer(name=name, options=options, response_type=response_type) + + +def test_custom_backend_uses_exact_ref_and_preserves_data(specification): + factory = NativeFactory() + original = deepcopy(factory.document) + broker = RabbitBroker(serializer=factory) + + @broker.subscriber("in") + async def handler(value: Opaque): ... + + document = specification(broker) + schema = document["components"]["schemas"]["Actual"] + assert schema == { + "title": "Actual", + "type": "string", + "pattern": "^x", + "description": "literal #/definitions/Unused", + "examples": [{"$ref": "#/definitions/Unused"}], + } + assert factory.document == original + assert_local_refs_resolve(document) + + +def test_disabled_serializer_fails_clearly(): + async def handler(value: int): ... + + call = FastDependsConfig(serializer=None).build_call(handler) + with pytest.raises(SetupError, match="serializer with JSON Schema support"): + parse_handler_params(call.dependent) + + +@pytest.mark.parametrize( + ("annotation", "default", "title"), + ( + (Annotated[int, Field(title="First"), Field(title="Second")], ..., "Second"), + (Annotated[int, Field(title="Inner")], Field(title="Outer"), "Outer"), + ), +) +def test_field_title_uses_backend_precedence(specification, annotation, default, title): + broker = RabbitBroker() + + @broker.subscriber("in") + async def handle(value: annotation = default): ... + + schema = specification(broker)["components"]["schemas"][title] + assert schema["title"] == title + assert schema["type"] == "integer" + + +def test_single_field_alias_does_not_merge_unrelated_components(specification): + broker = RabbitBroker() + + @broker.subscriber("first") + async def first(value: int = Field(alias="wire")): ... + @broker.subscriber("second") + async def second(value: str = Field(alias="wire")): ... + + schemas = specification(broker)["components"]["schemas"] + assert schemas["First:Message:Payload"]["type"] == "integer" + assert schemas["Second:Message:Payload"]["type"] == "string" + assert "Wire" not in schemas + + +@pytest.fixture(params=("v2_6_0", "v3_0_0")) +def component_payload(request): + + module = import_module(f"faststream.specification.asyncapi.{request.param}.generate") + + def generate(native): + schemas, messages = {}, {} + message = module.Message( + title="Message", payload=prepare_payload(native, prefix="Case") + ) + kwargs = { + "m": message, + "channel_name": "Channel", + "payloads": schemas, + "messages": messages, + } + if request.param == "v3_0_0": + kwargs["message_name"] = "Message" + module._resolve_msg_payloads(**kwargs) + return {"components": {"schemas": schemas}} + + return generate + + +def test_root_pointer_ref_is_rebased(component_payload): + native = { + "title": "Payload", + "type": "object", + "properties": { + "actual": {"type": "string"}, + "copy": {"$ref": "#/properties/actual"}, + }, + } + document = component_payload(native) + assert document["components"]["schemas"]["Payload"]["properties"]["copy"] == { + "$ref": "#/components/schemas/Payload/properties/actual" + } + assert_local_refs_resolve(document) + + +def test_schema_dependencies_refs_are_rebased(component_payload): + native = { + "title": "Payload", + "type": "object", + "dependencies": { + "name": {"properties": {"alias": {"$ref": "#/definitions/Value"}}} + }, + "definitions": {"Value": {"type": "string"}}, + } + document = component_payload(native) + assert document["components"]["schemas"]["Payload"]["dependencies"]["name"][ + "properties" + ]["alias"] == {"$ref": "#/components/schemas/Value"} + assert_local_refs_resolve(document) + + +def test_scoped_resource_keeps_recursive_definitions(component_payload): + native = { + "$id": "https://example.test/payload", + "$ref": "#/$defs/Node", + "$defs": { + "Node": { + "title": "Node", + "type": "object", + "properties": {"child": {"$ref": "#/$defs/Node"}}, + } + }, + } + schema = component_payload(native)["components"]["schemas"]["Case:Payload"] + assert schema == {**native, "title": "Case:Payload"} + + +def test_root_ref_keeps_all_sibling_constraints(component_payload): + native = { + "$ref": "#/$defs/Actual", + "allOf": [{"minLength": 3}], + "$defs": {"Actual": {"type": "string"}}, + } + schema = component_payload(native)["components"]["schemas"]["Case:Payload"] + assert schema["allOf"] == [{"type": "string"}, {"minLength": 3}] + + +def test_conflicting_definition_names_fail_clearly(component_payload): + native = { + "title": "Payload", + "properties": { + "text": {"$ref": "#/$defs/Shared"}, + "count": {"$ref": "#/definitions/Shared"}, + }, + "$defs": {"Shared": {"type": "string"}}, + "definitions": {"Shared": {"type": "integer"}}, + } + with pytest.raises(ValueError, match="Conflicting schema definitions for 'Shared'"): + component_payload(native) + + +def test_unrelated_definition_matching_title_is_preserved(): + + native = { + "title": "Payload", + "properties": {"value": {"$ref": "#/$defs/Payload"}}, + "$defs": {"Payload": {"type": "string"}}, + } + assert prepare_payload(native, prefix="Case")["$defs"] == native["$defs"] + + +def test_nested_scoped_resource_from_options_aware_backend(specification): + resource = { + "$id": "https://example.test/record", + "$ref": "#/$defs/Node", + "$defs": { + "Node": { + "title": "Node", + "type": "object", + "properties": {"child": {"$ref": "#/$defs/Node"}}, + } + }, + } + + class ResourceFactory(SerializerProto): + def __call__(self, *, name, options, response_type): + class ResourceSerializer(Serializer): + def __call__(self, kwargs): + return kwargs + + def get_schema(self, *, embed=False, exclude=(), resolve_refs=False): + schema = { + "type": "object", + "properties": {p.field_name: deepcopy(resource) for p in options}, + } + return process_schema(schema, embed=embed, resolve_refs=resolve_refs) + + return ResourceSerializer( + name=name, options=options, response_type=response_type + ) + + broker = RabbitBroker(serializer=ResourceFactory()) + + @broker.subscriber("in") + async def handle(value: Opaque): ... + + document = specification(broker) + schemas = document["components"]["schemas"] + assert schemas["__fast_depends_input"]["properties"]["value"] == resource + assert ( + schemas["Handle:Message:Payload"]["$ref"] + == "#/components/schemas/__fast_depends_input/properties/value" + ) + assert_local_refs_resolve(document) + + +def test_reference_tail_preserves_literal_percent_encoding(component_payload): + native = { + "title": "Payload", + "type": "object", + "properties": {"value": {"$ref": "#/$defs/Container/properties/%252F"}}, + "$defs": { + "Container": {"type": "object", "properties": {"%2F": {"type": "string"}}} + }, + } + document = component_payload(native) + assert document["components"]["schemas"]["Payload"]["properties"]["value"] == { + "$ref": "#/components/schemas/Container/properties/%252F" + } + assert_local_refs_resolve(document) + + +def test_input_resource_scope_is_preserved_during_embedding(specification): + native = { + "$id": "https://example.test/inputs", + "type": "object", + "properties": {"value": {"$ref": "#/$defs/Node"}}, + "$defs": { + "Node": { + "type": "object", + "properties": { + "children": {"type": "array", "items": {"$ref": "#/$defs/Node"}} + }, + } + }, + } + + class ResourceFactory(SerializerProto): + def __call__(self, *, name, options, response_type): + class ResourceSerializer(Serializer): + def __call__(self, kwargs): + return kwargs + + def get_schema(self, *, embed=False, exclude=(), resolve_refs=False): + return process_schema( + deepcopy(native), embed=embed, resolve_refs=resolve_refs + ) + + return ResourceSerializer( + name=name, options=options, response_type=response_type + ) + + broker = RabbitBroker(serializer=ResourceFactory()) + + @broker.subscriber("in") + async def handle(value: Opaque): ... + + document = specification(broker) + schemas = document["components"]["schemas"] + assert schemas["__fast_depends_input"] == native + assert ( + schemas["Handle:Message:Payload"]["$ref"] + == "#/components/schemas/__fast_depends_input/properties/value" + ) + assert_local_refs_resolve(document) diff --git a/tests/fastapi/test_get_dependant.py b/tests/fastapi/test_get_dependant.py index fbdcabe90a8..a19f60b1b98 100644 --- a/tests/fastapi/test_get_dependant.py +++ b/tests/fastapi/test_get_dependant.py @@ -1,8 +1,10 @@ from typing import Annotated +from fast_depends.pydantic import PydanticSerializer from fastapi import Depends from faststream._internal.fastapi.get_dependant import get_fastapi_dependant +from faststream.specification.asyncapi.message import parse_handler_params def test_get_fastapi_dependant_has_faststream_fields() -> None: @@ -20,6 +22,10 @@ async def handler( assert dependant.call is handler assert len(dependant.dependencies) == 1 assert dependant.dependencies[0].call is dependency - assert dependant.model.__name__ == "handler" + assert isinstance(dependant.serializer_cls, PydanticSerializer) + assert parse_handler_params(dependant, "Handler:Message") == { + "title": "Handler:Message:Payload", + "type": "string", + } assert dependant.custom_fields == {} assert [field.field_name for field in dependant.flat_params] == ["message"] From 435b1bbc2d50359a76093a28ac307526fd968b35 Mon Sep 17 00:00:00 2001 From: Tseluiko Aleksandr Date: Sat, 14 Nov 2026 19:56:20 +0300 Subject: [PATCH 3/8] fix: preserve AsyncAPI titles and shared schema references --- faststream/specification/asyncapi/message.py | 44 +++++-------- faststream/specification/asyncapi/utils.py | 25 ++++--- .../specification/asyncapi/v2_6_0/generate.py | 5 -- .../specification/asyncapi/v3_0_0/generate.py | 5 +- tests/asyncapi/test_serializers.py | 65 +++++++++++++++++++ 5 files changed, 98 insertions(+), 46 deletions(-) diff --git a/faststream/specification/asyncapi/message.py b/faststream/specification/asyncapi/message.py index 36a76ea2bfc..23e79a83e17 100644 --- a/faststream/specification/asyncapi/message.py +++ b/faststream/specification/asyncapi/message.py @@ -29,12 +29,27 @@ def parse_handler_params(call: "CallModel", prefix: str = "") -> dict[str, Any]: if factory is None: msg = "AsyncAPI requires a serializer with JSON Schema support." raise SetupError(msg) + return _payload_schema(factory, list(binding.params), prefix) + + +def payload_schema( + factory: "SerializerProto", + annotation: Any, + prefix: str = "", +) -> dict[str, Any]: + """Describe the declared payload type for the generic publisher encoder.""" + return _payload_schema(factory, [OptionItem("payload", annotation)], prefix) + + +def _payload_schema( + factory: "SerializerProto", options: list[OptionItem], prefix: str +) -> dict[str, Any]: serializer = factory( name=f"{prefix}:Payload", - options=list(binding.params), + options=options, response_type=Parameter.empty, ) - single = binding.single_parameter + single = options[0] if len(options) == 1 else None document = serializer.get_schema() root = _schema_root(document) properties = root.get("properties", {}) @@ -53,31 +68,6 @@ def parse_handler_params(call: "CallModel", prefix: str = "") -> dict[str, Any]: return body -def payload_schema( - factory: "SerializerProto", - annotation: Any, - prefix: str = "", -) -> dict[str, Any]: - """Describe the declared payload type for the generic publisher encoder.""" - serializer = factory( - name=f"{prefix}:Payload", - options=[OptionItem("payload", annotation)], - response_type=Parameter.empty, - ) - document = serializer.get_schema() - root = _schema_root(document) - properties = root.get("properties", {}) - emitted_name = next(iter(properties)) if len(properties) == 1 else "payload" - schema = process_schema(document, embed=True) - body = prepare_payload(schema, prefix=prefix) - if ( - "$ref" not in schema - and body.get("title") == emitted_name.replace("_", " ").title() - ): - body["title"] = f"{prefix}:Payload" - return body - - def prepare_payload(schema: dict[str, Any], *, prefix: str) -> dict[str, Any]: """Keep native schema metadata while giving the payload a component name.""" body = deepcopy(schema) diff --git a/faststream/specification/asyncapi/utils.py b/faststream/specification/asyncapi/utils.py index 222106cf01f..b36c468a3cd 100644 --- a/faststream/specification/asyncapi/utils.py +++ b/faststream/specification/asyncapi/utils.py @@ -102,14 +102,17 @@ def rewrite(value: str, root_ref: str) -> str: return root_ref + value[1:] return value - def visit(schema: Any, root_ref: str) -> None: + def visit(schema: Any, root_ref: str) -> Any: if not isinstance(schema, dict) or "$id" in schema: - return + return schema + schema = schema.copy() for key in ("$ref", "$dynamicRef", "$recursiveRef"): if isinstance(value := schema.get(key), str): schema[key] = rewrite(value, root_ref) discriminator = schema.get("discriminator") if isinstance(discriminator, dict): + discriminator = discriminator.copy() + schema["discriminator"] = discriminator if isinstance(mapping := discriminator.get("mapping"), dict): discriminator["mapping"] = { k: rewrite(v, root_ref) if isinstance(v, str) else v @@ -119,28 +122,30 @@ def visit(schema: Any, root_ref: str) -> None: schema["discriminator"] = discriminator["propertyName"] for key, value in schema.items(): if key in _SCHEMA_MAPS and isinstance(value, dict): - for child in value.values(): - visit(child, root_ref) + schema[key] = { + name: visit(child, root_ref) for name, child in value.items() + } elif key == "oneOf" and isinstance(value, dict): # FastStream's overloaded-handler payloads use a named map. + children = {} for name, child in value.items(): child_name = ( child.get("title", name) if isinstance(child, dict) else name ) if not isinstance(child_name, str): child_name = name - visit( + children[name] = visit( child, ref("components", "schemas", clear_key(child_name))["$ref"] ) + schema[key] = children elif (key in _SCHEMA_LISTS or key == "items") and isinstance(value, list): - for child in value: - visit(child, root_ref) + schema[key] = [visit(child, root_ref) for child in value] elif key in _SCHEMA_VALUES: - visit(value, root_ref) + schema[key] = visit(value, root_ref) + return schema title = data.get("title", root_name) if isinstance(data, dict) else root_name - visit(data, ref("components", "schemas", clear_key(title))["$ref"]) - return data + return visit(data, ref("components", "schemas", clear_key(title))["$ref"]) def pop_schema_definitions(payload: dict[str, Any]) -> dict[str, Any]: diff --git a/faststream/specification/asyncapi/v2_6_0/generate.py b/faststream/specification/asyncapi/v2_6_0/generate.py index 11101655cd5..4e9a703f223 100644 --- a/faststream/specification/asyncapi/v2_6_0/generate.py +++ b/faststream/specification/asyncapi/v2_6_0/generate.py @@ -283,10 +283,6 @@ def _resolve_msg_payloads( formatted_payload_title = clear_key(p_title) # Promote nested Pydantic $defs from each payload into components/schemas # so that referenced nested models are available globally. - if isinstance(p, dict): - defs = pop_schema_definitions(p) - for def_name, def_schema in defs.items(): - payloads[clear_key(def_name)] = def_schema payloads.update(pop_schema_definitions(p)) if formatted_payload_title not in payloads: payloads[formatted_payload_title] = p @@ -305,7 +301,6 @@ def _resolve_msg_payloads( one_of_list.append(Reference(**ref("components", "schemas", p_title))) if not one_of_list: - payloads.update(pop_schema_definitions(m.payload)) p_title = m.payload.get("title", f"{channel_name}Payload") p_title = clear_key(p_title) if p_title in payloads and payloads[p_title] != m.payload: diff --git a/faststream/specification/asyncapi/v3_0_0/generate.py b/faststream/specification/asyncapi/v3_0_0/generate.py index 895437b496d..dd24a6893c3 100644 --- a/faststream/specification/asyncapi/v3_0_0/generate.py +++ b/faststream/specification/asyncapi/v3_0_0/generate.py @@ -352,9 +352,7 @@ def _resolve_msg_payloads( # Promote nested Pydantic $defs from each payload into components/schemas # so that referenced nested models are available globally. if isinstance(payload, dict): - defs = pop_schema_definitions(payload) - for def_name, def_schema in defs.items(): - payloads[clear_key(def_name)] = def_schema + payloads.update(pop_schema_definitions(payload)) processed_payloads[clear_key(name)] = payload one_of_list.append(Reference(**ref("components", "schemas", name))) @@ -366,7 +364,6 @@ def _resolve_msg_payloads( **ref("components", "messages", f"{channel_name}:{message_name}"), ) - payloads.update(pop_schema_definitions(m.payload)) payload_name = m.payload.get("title", f"{channel_name}:{message_name}:Payload") payload_name = clear_key(payload_name) diff --git a/tests/asyncapi/test_serializers.py b/tests/asyncapi/test_serializers.py index 61cabb10f48..fe538c519f3 100644 --- a/tests/asyncapi/test_serializers.py +++ b/tests/asyncapi/test_serializers.py @@ -506,3 +506,68 @@ async def handle(value: Opaque): ... == "#/components/schemas/__fast_depends_input/properties/value" ) assert_local_refs_resolve(document) + + +@pytest.mark.parametrize( + ("factory", "metadata"), + ((PydanticSerializer, Field), (MsgSpecSerializer, msgspec.Meta)), +) +@pytest.mark.parametrize("title", ("Payload", "Counter")) +def test_publisher_preserves_explicit_scalar_title( + specification, factory, metadata, title +): + broker = RabbitBroker(serializer=factory()) + annotation = Annotated[int, metadata(title=title)] + + @broker.publisher("out") + async def handle() -> annotation: ... + + assert specification(broker)["components"]["schemas"] == { + title: {"title": title, "type": "integer"} + } + + +def test_shared_schema_nodes_are_rewritten_once(component_payload): + shared = {"$ref": "#/$defs/Leaf"} + native = { + "title": "Payload", + "type": "object", + "properties": {"first": shared, "second": shared}, + "$defs": {"Leaf": {"type": "string"}}, + } + original = deepcopy(native) + document = component_payload(native) + schema = document["components"]["schemas"]["Payload"] + assert schema["properties"] == { + "first": {"$ref": "#/components/schemas/Leaf"}, + "second": {"$ref": "#/components/schemas/Leaf"}, + } + assert native == original + assert_local_refs_resolve(document) + + +def test_shared_nodes_preserve_resource_scope_and_data_literals(component_payload): + shared = {"$ref": "#/$defs/Leaf"} + resource = { + "$id": "https://example.test/local", + "type": "object", + "properties": {"local": shared}, + "$defs": {"Leaf": {"type": "integer"}}, + } + native = { + "title": "Payload", + "type": "object", + "properties": {"global": shared, "scoped": resource}, + "default": shared, + "examples": [shared], + "$defs": {"Leaf": {"type": "string"}}, + } + original = deepcopy(native) + document = component_payload(native) + schema = document["components"]["schemas"]["Payload"] + assert schema["properties"]["global"] == {"$ref": "#/components/schemas/Leaf"} + assert schema["properties"]["scoped"] == resource + assert schema["default"] == {"$ref": "#/$defs/Leaf"} + assert schema["examples"] == [{"$ref": "#/$defs/Leaf"}] + assert native == original + assert_local_refs_resolve(document) From b27265300d353c308bea01d784e22fa13823cbe6 Mon Sep 17 00:00:00 2001 From: Lancetnik Date: Sun, 15 Nov 2026 21:09:54 +0300 Subject: [PATCH 4/8] chore: refresh AsyncAPI serializer tests and dependency lock --- tests/asyncapi/test_serializers.py | 1024 ++++++++++++++++------------ uv.lock | 8 +- 2 files changed, 573 insertions(+), 459 deletions(-) diff --git a/tests/asyncapi/test_serializers.py b/tests/asyncapi/test_serializers.py index fe538c519f3..b28fc1d8525 100644 --- a/tests/asyncapi/test_serializers.py +++ b/tests/asyncapi/test_serializers.py @@ -1,14 +1,15 @@ +from collections.abc import Callable, Iterable from copy import deepcopy from importlib import import_module -from typing import Annotated, Any, Literal +from typing import Annotated, Any, Literal, TypeAlias from urllib.parse import unquote import msgspec import pytest from fast_depends import Depends, Provider from fast_depends.library import CustomField, SchemaField -from fast_depends.library.schema_processing import process_schema -from fast_depends.library.serializer import Serializer, SerializerProto +from fast_depends.library.schema_processing import SchemaExclude, process_schema +from fast_depends.library.serializer import OptionItem, Serializer, SerializerProto from fast_depends.msgspec import MsgSpecSerializer from fast_depends.pydantic import PydanticSerializer from pydantic import Field, PlainSerializer @@ -23,6 +24,9 @@ prepare_payload, ) +SpecificationGenerator: TypeAlias = Callable[[RabbitBroker], dict[str, Any]] +ComponentGenerator: TypeAlias = Callable[[dict[str, Any]], dict[str, Any]] + class Item(msgspec.Struct, rename="camel", tag="item", omit_defaults=True): item_id: Annotated[int, msgspec.Meta(gt=0)] @@ -33,18 +37,25 @@ class Tree(msgspec.Struct): children: list["Tree"] = msgspec.field(default_factory=list) -@pytest.fixture(params=("2.6.0", "3.0.0")) -def specification(request: pytest.FixtureRequest): - def generate(broker): +@pytest.fixture( + params=( + pytest.param("2.6.0", id="asyncapi-2.6"), + pytest.param("3.0.0", id="asyncapi-3.0"), + ) +) +def specification(request: pytest.FixtureRequest) -> SpecificationGenerator: + def generate(broker: RabbitBroker) -> dict[str, Any]: factory = AsyncAPI(schema_version=request.param) factory.add_broker(broker) - return factory.to_specification().to_jsonable() + document = factory.to_specification().to_jsonable() + assert isinstance(document, dict) + return document return generate -def assert_local_refs_resolve(document): - def visit(value): +def assert_local_refs_resolve(document: dict[str, Any]) -> None: + def visit(value: Any) -> None: if isinstance(value, dict): if "$id" in value: return @@ -64,144 +75,13 @@ def visit(value): visit(document) -@pytest.mark.parametrize("publisher", (False, True)) -@pytest.mark.parametrize("annotation", (Item, list[Item], Tree)) -def test_msgspec_struct_payloads(specification, publisher, annotation): - broker = RabbitBroker(serializer=MsgSpecSerializer()) - if publisher: - - @broker.publisher("out") - async def handle() -> annotation: ... - - else: - - @broker.subscriber("in") - async def handle(value: annotation): ... - - document = specification(broker) - schemas = document["components"]["schemas"] - assert_local_refs_resolve(document) - if annotation is Tree: - assert schemas["Tree"]["properties"]["children"]["items"] == { - "$ref": "#/components/schemas/Tree" - } - else: - assert schemas["Item"]["properties"] == { - "type": {"enum": ["item"]}, - "itemId": {"type": "integer", "exclusiveMinimum": 0}, - "label": {"type": "string", "default": ""}, - } - assert schemas["Item"]["required"] == ["type", "itemId"] - if annotation == list[Item]: - assert any( - value.get("items") == {"$ref": "#/components/schemas/Item"} - for value in schemas.values() - ) - - -def test_explicit_msgspec_publisher_schema(specification): - broker = RabbitBroker(serializer=MsgSpecSerializer()) - broker.publisher("out", schema=Item) - document = specification(broker) - assert document["components"]["schemas"]["Item"]["required"] == ["type", "itemId"] - assert_local_refs_resolve(document) - - -def test_msgspec_field_alias_and_constraint(specification): - broker = RabbitBroker(serializer=MsgSpecSerializer()) - - @broker.subscriber("in") - async def handle( - count: Annotated[int, msgspec.Meta(ge=1)] = msgspec.field(name="size"), - label: Literal["a", "b"] = "a", - ): ... - - schema = specification(broker)["components"]["schemas"]["Handle:Message:Payload"] - assert schema["properties"]["size"] == {"type": "integer", "minimum": 1} - assert schema["properties"]["label"] == {"enum": ["a", "b"], "default": "a"} - assert schema["required"] == ["size"] - - -@pytest.mark.parametrize("factory", (PydanticSerializer, MsgSpecSerializer)) -def test_custom_field_schemas_stay_outside_body(factory): - class Header(CustomField): - def get_schema(self, parameter): - return SchemaField( - parameter.field_name, parameter.field_type, source="headers" - ) - - async def handler(payload: int, token: Annotated[str, Header()]): ... - - call = FastDependsConfig(serializer=factory()).build_call(handler) - assert parse_handler_params(call.dependent, "Handler:Message") == { - "title": "Handler:Message:Payload", - "type": "integer", - } - - -def test_selected_factory_configuration(specification): - broker = RabbitBroker( - serializer=PydanticSerializer(pydantic_config={"alias_generator": str.upper}) - ) - - @broker.subscriber("in") - async def handle(first: int, second: str): ... - - schema = specification(broker)["components"]["schemas"]["Handle:Message:Payload"] - assert set(schema["properties"]) == {"FIRST", "SECOND"} - assert schema["required"] == ["FIRST", "SECOND"] - - -def test_explicit_field_title(specification): - broker = RabbitBroker() - - @broker.subscriber("in") - async def handle(value: Annotated[int, Field(title="Counter", gt=0)]): ... - - assert specification(broker)["components"]["schemas"]["Counter"] == { - "title": "Counter", - "type": "integer", - "exclusiveMinimum": 0, - } - - -def test_publisher_keeps_generic_annotation_encoding_contract(specification): - annotation = Annotated[int, PlainSerializer(str, return_type=str)] - factory = PydanticSerializer() - broker = RabbitBroker(serializer=factory) - - @broker.publisher("out") - async def handle() -> annotation: - return 42 - - schemas = specification(broker)["components"]["schemas"] - assert next(iter(schemas.values()))["type"] == "integer" - assert encode_message(42, factory)[0] == b"42" - - -def test_dependency_override_changes_body_schema(): - provider = Provider() - - async def dependency(count: int): ... - async def replacement(item: Item): ... - async def handler(value: Annotated[Any, Depends(dependency)]): ... - - call = FastDependsConfig( - serializer=MsgSpecSerializer(), provider=provider - ).build_call(handler) - assert parse_handler_params(call.dependent)["type"] == "integer" - with provider.scope(dependency, replacement): - assert parse_handler_params(call.dependent)["title"] == "Item" - assert parse_handler_params(call.dependent)["type"] == "integer" - - class Opaque: pass class NativeFactory(SerializerProto): - def __init__(self): - self.document = { + def __init__(self) -> None: + self.document: dict[str, Any] = { "$ref": "#/definitions/Actual", "definitions": { "Unused": {"type": "integer"}, @@ -215,14 +95,22 @@ def __init__(self): }, } - def __call__(self, *, name, options, response_type): + def __call__( + self, *, name: str, options: list[OptionItem], response_type: Any + ) -> Serializer: document = self.document class NativeSerializer(Serializer): - def __call__(self, kwargs): + def __call__(self, kwargs: dict[str, Any]) -> dict[str, Any]: return kwargs - def get_schema(self, *, embed=False, exclude=(), resolve_refs=False): + def get_schema( + self, + *, + embed: bool = False, + exclude: Iterable[SchemaExclude] = (), + resolve_refs: bool = False, + ) -> dict[str, Any]: schema = { "type": "object", "properties": { @@ -235,78 +123,23 @@ def get_schema(self, *, embed=False, exclude=(), resolve_refs=False): return NativeSerializer(name=name, options=options, response_type=response_type) -def test_custom_backend_uses_exact_ref_and_preserves_data(specification): - factory = NativeFactory() - original = deepcopy(factory.document) - broker = RabbitBroker(serializer=factory) - - @broker.subscriber("in") - async def handler(value: Opaque): ... - - document = specification(broker) - schema = document["components"]["schemas"]["Actual"] - assert schema == { - "title": "Actual", - "type": "string", - "pattern": "^x", - "description": "literal #/definitions/Unused", - "examples": [{"$ref": "#/definitions/Unused"}], - } - assert factory.document == original - assert_local_refs_resolve(document) - - -def test_disabled_serializer_fails_clearly(): - async def handler(value: int): ... - - call = FastDependsConfig(serializer=None).build_call(handler) - with pytest.raises(SetupError, match="serializer with JSON Schema support"): - parse_handler_params(call.dependent) - - -@pytest.mark.parametrize( - ("annotation", "default", "title"), - ( - (Annotated[int, Field(title="First"), Field(title="Second")], ..., "Second"), - (Annotated[int, Field(title="Inner")], Field(title="Outer"), "Outer"), - ), +@pytest.fixture( + params=( + pytest.param("v2_6_0", id="asyncapi-2.6"), + pytest.param("v3_0_0", id="asyncapi-3.0"), + ) ) -def test_field_title_uses_backend_precedence(specification, annotation, default, title): - broker = RabbitBroker() - - @broker.subscriber("in") - async def handle(value: annotation = default): ... - - schema = specification(broker)["components"]["schemas"][title] - assert schema["title"] == title - assert schema["type"] == "integer" - - -def test_single_field_alias_does_not_merge_unrelated_components(specification): - broker = RabbitBroker() - - @broker.subscriber("first") - async def first(value: int = Field(alias="wire")): ... - @broker.subscriber("second") - async def second(value: str = Field(alias="wire")): ... - - schemas = specification(broker)["components"]["schemas"] - assert schemas["First:Message:Payload"]["type"] == "integer" - assert schemas["Second:Message:Payload"]["type"] == "string" - assert "Wire" not in schemas - - -@pytest.fixture(params=("v2_6_0", "v3_0_0")) -def component_payload(request): +def component_payload(request: pytest.FixtureRequest) -> ComponentGenerator: module = import_module(f"faststream.specification.asyncapi.{request.param}.generate") - def generate(native): - schemas, messages = {}, {} + def generate(native: dict[str, Any]) -> dict[str, Any]: + schemas: dict[str, Any] = {} + messages: dict[str, Any] = {} message = module.Message( title="Message", payload=prepare_payload(native, prefix="Case") ) - kwargs = { + kwargs: dict[str, Any] = { "m": message, "channel_name": "Channel", "payloads": schemas, @@ -320,254 +153,535 @@ def generate(native): return generate -def test_root_pointer_ref_is_rebased(component_payload): - native = { - "title": "Payload", - "type": "object", - "properties": { - "actual": {"type": "string"}, - "copy": {"$ref": "#/properties/actual"}, - }, - } - document = component_payload(native) - assert document["components"]["schemas"]["Payload"]["properties"]["copy"] == { - "$ref": "#/components/schemas/Payload/properties/actual" - } - assert_local_refs_resolve(document) - - -def test_schema_dependencies_refs_are_rebased(component_payload): - native = { - "title": "Payload", - "type": "object", - "dependencies": { - "name": {"properties": {"alias": {"$ref": "#/definitions/Value"}}} - }, - "definitions": {"Value": {"type": "string"}}, - } - document = component_payload(native) - assert document["components"]["schemas"]["Payload"]["dependencies"]["name"][ - "properties" - ]["alias"] == {"$ref": "#/components/schemas/Value"} - assert_local_refs_resolve(document) - - -def test_scoped_resource_keeps_recursive_definitions(component_payload): - native = { - "$id": "https://example.test/payload", - "$ref": "#/$defs/Node", - "$defs": { - "Node": { - "title": "Node", - "type": "object", - "properties": {"child": {"$ref": "#/$defs/Node"}}, +class TestMsgspecPayloads: + @pytest.mark.parametrize( + "publisher", + (pytest.param(False, id="subscriber"), pytest.param(True, id="publisher")), + ) + @pytest.mark.parametrize( + "annotation", + ( + pytest.param(Item, id="struct"), + pytest.param(list[Item], id="struct-list"), + pytest.param(Tree, id="recursive-struct"), + ), + ) + def test_msgspec_struct_payloads( + self, specification: SpecificationGenerator, publisher: bool, annotation: Any + ) -> None: + broker = RabbitBroker(serializer=MsgSpecSerializer()) + if publisher: + + @broker.publisher("out") + async def handle() -> annotation: ... + + else: + + @broker.subscriber("in") + async def handle(value: annotation) -> None: ... + + document = specification(broker) + schemas = document["components"]["schemas"] + assert_local_refs_resolve(document) + if annotation is Tree: + assert schemas["Tree"]["properties"]["children"]["items"] == { + "$ref": "#/components/schemas/Tree" } - }, - } - schema = component_payload(native)["components"]["schemas"]["Case:Payload"] - assert schema == {**native, "title": "Case:Payload"} - - -def test_root_ref_keeps_all_sibling_constraints(component_payload): - native = { - "$ref": "#/$defs/Actual", - "allOf": [{"minLength": 3}], - "$defs": {"Actual": {"type": "string"}}, - } - schema = component_payload(native)["components"]["schemas"]["Case:Payload"] - assert schema["allOf"] == [{"type": "string"}, {"minLength": 3}] - - -def test_conflicting_definition_names_fail_clearly(component_payload): - native = { - "title": "Payload", - "properties": { - "text": {"$ref": "#/$defs/Shared"}, - "count": {"$ref": "#/definitions/Shared"}, - }, - "$defs": {"Shared": {"type": "string"}}, - "definitions": {"Shared": {"type": "integer"}}, - } - with pytest.raises(ValueError, match="Conflicting schema definitions for 'Shared'"): - component_payload(native) - - -def test_unrelated_definition_matching_title_is_preserved(): - - native = { - "title": "Payload", - "properties": {"value": {"$ref": "#/$defs/Payload"}}, - "$defs": {"Payload": {"type": "string"}}, - } - assert prepare_payload(native, prefix="Case")["$defs"] == native["$defs"] - - -def test_nested_scoped_resource_from_options_aware_backend(specification): - resource = { - "$id": "https://example.test/record", - "$ref": "#/$defs/Node", - "$defs": { - "Node": { - "title": "Node", - "type": "object", - "properties": {"child": {"$ref": "#/$defs/Node"}}, + else: + assert schemas["Item"]["properties"] == { + "type": {"enum": ["item"]}, + "itemId": {"type": "integer", "exclusiveMinimum": 0}, + "label": {"type": "string", "default": ""}, } - }, - } - - class ResourceFactory(SerializerProto): - def __call__(self, *, name, options, response_type): - class ResourceSerializer(Serializer): - def __call__(self, kwargs): - return kwargs - - def get_schema(self, *, embed=False, exclude=(), resolve_refs=False): - schema = { - "type": "object", - "properties": {p.field_name: deepcopy(resource) for p in options}, - } - return process_schema(schema, embed=embed, resolve_refs=resolve_refs) - - return ResourceSerializer( - name=name, options=options, response_type=response_type - ) - - broker = RabbitBroker(serializer=ResourceFactory()) - - @broker.subscriber("in") - async def handle(value: Opaque): ... - - document = specification(broker) - schemas = document["components"]["schemas"] - assert schemas["__fast_depends_input"]["properties"]["value"] == resource - assert ( - schemas["Handle:Message:Payload"]["$ref"] - == "#/components/schemas/__fast_depends_input/properties/value" + assert schemas["Item"]["required"] == ["type", "itemId"] + if annotation == list[Item]: + assert any( + value.get("items") == {"$ref": "#/components/schemas/Item"} + for value in schemas.values() + ) + + def test_explicit_msgspec_publisher_schema( + self, specification: SpecificationGenerator + ) -> None: + broker = RabbitBroker(serializer=MsgSpecSerializer()) + broker.publisher("out", schema=Item) + document = specification(broker) + assert document["components"]["schemas"]["Item"]["required"] == ["type", "itemId"] + assert_local_refs_resolve(document) + + def test_msgspec_field_alias_and_constraint( + self, specification: SpecificationGenerator + ) -> None: + broker = RabbitBroker(serializer=MsgSpecSerializer()) + + @broker.subscriber("in") + async def handle( + count: Annotated[int, msgspec.Meta(ge=1)] = msgspec.field(name="size"), + label: Literal["a", "b"] = "a", + ) -> None: ... + + schema = specification(broker)["components"]["schemas"]["Handle:Message:Payload"] + assert schema["properties"]["size"] == {"type": "integer", "minimum": 1} + assert schema["properties"]["label"] == {"enum": ["a", "b"], "default": "a"} + assert schema["required"] == ["size"] + + +class TestSerializerSelection: + @pytest.mark.parametrize( + "factory", + ( + pytest.param(PydanticSerializer, id="pydantic"), + pytest.param(MsgSpecSerializer, id="msgspec"), + ), ) - assert_local_refs_resolve(document) - - -def test_reference_tail_preserves_literal_percent_encoding(component_payload): - native = { - "title": "Payload", - "type": "object", - "properties": {"value": {"$ref": "#/$defs/Container/properties/%252F"}}, - "$defs": { - "Container": {"type": "object", "properties": {"%2F": {"type": "string"}}} - }, - } - document = component_payload(native) - assert document["components"]["schemas"]["Payload"]["properties"]["value"] == { - "$ref": "#/components/schemas/Container/properties/%252F" - } - assert_local_refs_resolve(document) - - -def test_input_resource_scope_is_preserved_during_embedding(specification): - native = { - "$id": "https://example.test/inputs", - "type": "object", - "properties": {"value": {"$ref": "#/$defs/Node"}}, - "$defs": { - "Node": { - "type": "object", - "properties": { - "children": {"type": "array", "items": {"$ref": "#/$defs/Node"}} - }, - } - }, - } - - class ResourceFactory(SerializerProto): - def __call__(self, *, name, options, response_type): - class ResourceSerializer(Serializer): - def __call__(self, kwargs): - return kwargs - - def get_schema(self, *, embed=False, exclude=(), resolve_refs=False): - return process_schema( - deepcopy(native), embed=embed, resolve_refs=resolve_refs - ) - - return ResourceSerializer( - name=name, options=options, response_type=response_type - ) - - broker = RabbitBroker(serializer=ResourceFactory()) - - @broker.subscriber("in") - async def handle(value: Opaque): ... - - document = specification(broker) - schemas = document["components"]["schemas"] - assert schemas["__fast_depends_input"] == native - assert ( - schemas["Handle:Message:Payload"]["$ref"] - == "#/components/schemas/__fast_depends_input/properties/value" + def test_custom_field_schemas_stay_outside_body( + self, factory: type[SerializerProto] + ) -> None: + class Header(CustomField): + def get_schema(self, parameter: OptionItem) -> SchemaField: + return SchemaField( + parameter.field_name, parameter.field_type, source="headers" + ) + + async def handler(payload: int, token: Annotated[str, Header()]) -> None: ... + + call = FastDependsConfig(serializer=factory()).build_call(handler) + assert parse_handler_params(call.dependent, "Handler:Message") == { + "title": "Handler:Message:Payload", + "type": "integer", + } + + def test_selected_factory_configuration( + self, specification: SpecificationGenerator + ) -> None: + broker = RabbitBroker( + serializer=PydanticSerializer(pydantic_config={"alias_generator": str.upper}) + ) + + @broker.subscriber("in") + async def handle(first: int, second: str) -> None: ... + + schema = specification(broker)["components"]["schemas"]["Handle:Message:Payload"] + assert set(schema["properties"]) == {"FIRST", "SECOND"} + assert schema["required"] == ["FIRST", "SECOND"] + + def test_dependency_override_changes_body_schema(self) -> None: + provider = Provider() + + async def dependency(count: int) -> None: ... + async def replacement(item: Item) -> None: ... + async def handler(value: Annotated[Any, Depends(dependency)]) -> None: ... + + call = FastDependsConfig( + serializer=MsgSpecSerializer(), provider=provider + ).build_call(handler) + assert parse_handler_params(call.dependent)["type"] == "integer" + with provider.scope(dependency, replacement): + assert parse_handler_params(call.dependent)["title"] == "Item" + assert parse_handler_params(call.dependent)["type"] == "integer" + + def test_disabled_serializer_fails_clearly(self) -> None: + async def handler(value: int) -> None: ... + + call = FastDependsConfig(serializer=None).build_call(handler) + with pytest.raises(SetupError, match="serializer with JSON Schema support"): + parse_handler_params(call.dependent) + + +class TestPayloadTitles: + def test_explicit_field_title(self, specification: SpecificationGenerator) -> None: + broker = RabbitBroker() + + @broker.subscriber("in") + async def handle(value: Annotated[int, Field(title="Counter", gt=0)]) -> None: ... + + assert specification(broker)["components"]["schemas"]["Counter"] == { + "title": "Counter", + "type": "integer", + "exclusiveMinimum": 0, + } + + @pytest.mark.parametrize( + ("annotation", "default", "title"), + ( + pytest.param( + Annotated[int, Field(title="First"), Field(title="Second")], + ..., + "Second", + id="last-annotation-title", + ), + pytest.param( + Annotated[int, Field(title="Inner")], + Field(title="Outer"), + "Outer", + id="default-title", + ), + ), ) - assert_local_refs_resolve(document) + def test_field_title_uses_backend_precedence( + self, + specification: SpecificationGenerator, + annotation: Any, + default: Any, + title: str, + ) -> None: + broker = RabbitBroker() + @broker.subscriber("in") + async def handle(value: annotation = default) -> None: ... -@pytest.mark.parametrize( - ("factory", "metadata"), - ((PydanticSerializer, Field), (MsgSpecSerializer, msgspec.Meta)), -) -@pytest.mark.parametrize("title", ("Payload", "Counter")) -def test_publisher_preserves_explicit_scalar_title( - specification, factory, metadata, title -): - broker = RabbitBroker(serializer=factory()) - annotation = Annotated[int, metadata(title=title)] - - @broker.publisher("out") - async def handle() -> annotation: ... - - assert specification(broker)["components"]["schemas"] == { - title: {"title": title, "type": "integer"} - } - - -def test_shared_schema_nodes_are_rewritten_once(component_payload): - shared = {"$ref": "#/$defs/Leaf"} - native = { - "title": "Payload", - "type": "object", - "properties": {"first": shared, "second": shared}, - "$defs": {"Leaf": {"type": "string"}}, - } - original = deepcopy(native) - document = component_payload(native) - schema = document["components"]["schemas"]["Payload"] - assert schema["properties"] == { - "first": {"$ref": "#/components/schemas/Leaf"}, - "second": {"$ref": "#/components/schemas/Leaf"}, - } - assert native == original - assert_local_refs_resolve(document) - - -def test_shared_nodes_preserve_resource_scope_and_data_literals(component_payload): - shared = {"$ref": "#/$defs/Leaf"} - resource = { - "$id": "https://example.test/local", - "type": "object", - "properties": {"local": shared}, - "$defs": {"Leaf": {"type": "integer"}}, - } - native = { - "title": "Payload", - "type": "object", - "properties": {"global": shared, "scoped": resource}, - "default": shared, - "examples": [shared], - "$defs": {"Leaf": {"type": "string"}}, - } - original = deepcopy(native) - document = component_payload(native) - schema = document["components"]["schemas"]["Payload"] - assert schema["properties"]["global"] == {"$ref": "#/components/schemas/Leaf"} - assert schema["properties"]["scoped"] == resource - assert schema["default"] == {"$ref": "#/$defs/Leaf"} - assert schema["examples"] == [{"$ref": "#/$defs/Leaf"}] - assert native == original - assert_local_refs_resolve(document) + schema = specification(broker)["components"]["schemas"][title] + assert schema["title"] == title + assert schema["type"] == "integer" + + def test_single_field_alias_does_not_merge_unrelated_components( + self, specification: SpecificationGenerator + ) -> None: + broker = RabbitBroker() + + @broker.subscriber("first") + async def first(value: int = Field(alias="wire")) -> None: ... + @broker.subscriber("second") + async def second(value: str = Field(alias="wire")) -> None: ... + + schemas = specification(broker)["components"]["schemas"] + assert schemas["First:Message:Payload"]["type"] == "integer" + assert schemas["Second:Message:Payload"]["type"] == "string" + assert "Wire" not in schemas + + def test_unrelated_definition_matching_title_is_preserved(self) -> None: + + native = { + "title": "Payload", + "properties": {"value": {"$ref": "#/$defs/Payload"}}, + "$defs": {"Payload": {"type": "string"}}, + } + assert prepare_payload(native, prefix="Case")["$defs"] == native["$defs"] + + @pytest.mark.parametrize( + ("factory", "metadata"), + ( + pytest.param(PydanticSerializer, Field, id="pydantic"), + pytest.param(MsgSpecSerializer, msgspec.Meta, id="msgspec"), + ), + ) + @pytest.mark.parametrize( + "title", + ( + pytest.param("Payload", id="default-title"), + pytest.param("Counter", id="custom-title"), + ), + ) + def test_publisher_preserves_explicit_scalar_title( + self, + specification: SpecificationGenerator, + factory: type[SerializerProto], + metadata: Callable[..., Any], + title: str, + ) -> None: + broker = RabbitBroker(serializer=factory()) + Payload: TypeAlias = Annotated[int, metadata(title=title)] + + @broker.publisher("out") + async def handle() -> Payload: ... + + assert specification(broker)["components"]["schemas"] == { + title: {"title": title, "type": "integer"} + } + + +class TestPublisherEncoding: + def test_publisher_keeps_generic_annotation_encoding_contract( + self, specification: SpecificationGenerator + ) -> None: + Payload: TypeAlias = Annotated[int, PlainSerializer(str, return_type=str)] + factory = PydanticSerializer() + broker = RabbitBroker(serializer=factory) + + @broker.publisher("out") + async def handle() -> Payload: + return 42 + + schemas = specification(broker)["components"]["schemas"] + assert next(iter(schemas.values()))["type"] == "integer" + assert encode_message(42, factory)[0] == b"42" + + +class TestSchemaReferences: + def test_custom_backend_uses_exact_ref_and_preserves_data( + self, specification: SpecificationGenerator + ) -> None: + factory = NativeFactory() + original = deepcopy(factory.document) + broker = RabbitBroker(serializer=factory) + + @broker.subscriber("in") + async def handler(value: Opaque) -> None: ... + + document = specification(broker) + schema = document["components"]["schemas"]["Actual"] + assert schema == { + "title": "Actual", + "type": "string", + "pattern": "^x", + "description": "literal #/definitions/Unused", + "examples": [{"$ref": "#/definitions/Unused"}], + } + assert factory.document == original + assert_local_refs_resolve(document) + + def test_root_pointer_ref_is_rebased( + self, component_payload: ComponentGenerator + ) -> None: + native = { + "title": "Payload", + "type": "object", + "properties": { + "actual": {"type": "string"}, + "copy": {"$ref": "#/properties/actual"}, + }, + } + document = component_payload(native) + assert document["components"]["schemas"]["Payload"]["properties"]["copy"] == { + "$ref": "#/components/schemas/Payload/properties/actual" + } + assert_local_refs_resolve(document) + + def test_schema_dependencies_refs_are_rebased( + self, component_payload: ComponentGenerator + ) -> None: + native = { + "title": "Payload", + "type": "object", + "dependencies": { + "name": {"properties": {"alias": {"$ref": "#/definitions/Value"}}} + }, + "definitions": {"Value": {"type": "string"}}, + } + document = component_payload(native) + assert document["components"]["schemas"]["Payload"]["dependencies"]["name"][ + "properties" + ]["alias"] == {"$ref": "#/components/schemas/Value"} + assert_local_refs_resolve(document) + + def test_scoped_resource_keeps_recursive_definitions( + self, component_payload: ComponentGenerator + ) -> None: + native = { + "$id": "https://example.test/payload", + "$ref": "#/$defs/Node", + "$defs": { + "Node": { + "title": "Node", + "type": "object", + "properties": {"child": {"$ref": "#/$defs/Node"}}, + } + }, + } + schema = component_payload(native)["components"]["schemas"]["Case:Payload"] + assert schema == {**native, "title": "Case:Payload"} + + def test_root_ref_keeps_all_sibling_constraints( + self, component_payload: ComponentGenerator + ) -> None: + native = { + "$ref": "#/$defs/Actual", + "allOf": [{"minLength": 3}], + "$defs": {"Actual": {"type": "string"}}, + } + schema = component_payload(native)["components"]["schemas"]["Case:Payload"] + assert schema["allOf"] == [{"type": "string"}, {"minLength": 3}] + + def test_conflicting_definition_names_fail_clearly( + self, component_payload: ComponentGenerator + ) -> None: + native = { + "title": "Payload", + "properties": { + "text": {"$ref": "#/$defs/Shared"}, + "count": {"$ref": "#/definitions/Shared"}, + }, + "$defs": {"Shared": {"type": "string"}}, + "definitions": {"Shared": {"type": "integer"}}, + } + with pytest.raises( + ValueError, match="Conflicting schema definitions for 'Shared'" + ): + component_payload(native) + + def test_nested_scoped_resource_from_options_aware_backend( + self, specification: SpecificationGenerator + ) -> None: + resource = { + "$id": "https://example.test/record", + "$ref": "#/$defs/Node", + "$defs": { + "Node": { + "title": "Node", + "type": "object", + "properties": {"child": {"$ref": "#/$defs/Node"}}, + } + }, + } + + class ResourceFactory(SerializerProto): + def __call__( + self, *, name: str, options: list[OptionItem], response_type: Any + ) -> Serializer: + class ResourceSerializer(Serializer): + def __call__(self, kwargs: dict[str, Any]) -> dict[str, Any]: + return kwargs + + def get_schema( + self, + *, + embed: bool = False, + exclude: Iterable[SchemaExclude] = (), + resolve_refs: bool = False, + ) -> dict[str, Any]: + schema = { + "type": "object", + "properties": { + p.field_name: deepcopy(resource) for p in options + }, + } + return process_schema( + schema, embed=embed, resolve_refs=resolve_refs + ) + + return ResourceSerializer( + name=name, options=options, response_type=response_type + ) + + broker = RabbitBroker(serializer=ResourceFactory()) + + @broker.subscriber("in") + async def handle(value: Opaque) -> None: ... + + document = specification(broker) + schemas = document["components"]["schemas"] + assert schemas["__fast_depends_input"]["properties"]["value"] == resource + assert ( + schemas["Handle:Message:Payload"]["$ref"] + == "#/components/schemas/__fast_depends_input/properties/value" + ) + assert_local_refs_resolve(document) + + def test_reference_tail_preserves_literal_percent_encoding( + self, component_payload: ComponentGenerator + ) -> None: + native = { + "title": "Payload", + "type": "object", + "properties": {"value": {"$ref": "#/$defs/Container/properties/%252F"}}, + "$defs": { + "Container": {"type": "object", "properties": {"%2F": {"type": "string"}}} + }, + } + document = component_payload(native) + assert document["components"]["schemas"]["Payload"]["properties"]["value"] == { + "$ref": "#/components/schemas/Container/properties/%252F" + } + assert_local_refs_resolve(document) + + def test_input_resource_scope_is_preserved_during_embedding( + self, specification: SpecificationGenerator + ) -> None: + native = { + "$id": "https://example.test/inputs", + "type": "object", + "properties": {"value": {"$ref": "#/$defs/Node"}}, + "$defs": { + "Node": { + "type": "object", + "properties": { + "children": {"type": "array", "items": {"$ref": "#/$defs/Node"}} + }, + } + }, + } + + class ResourceFactory(SerializerProto): + def __call__( + self, *, name: str, options: list[OptionItem], response_type: Any + ) -> Serializer: + class ResourceSerializer(Serializer): + def __call__(self, kwargs: dict[str, Any]) -> dict[str, Any]: + return kwargs + + def get_schema( + self, + *, + embed: bool = False, + exclude: Iterable[SchemaExclude] = (), + resolve_refs: bool = False, + ) -> dict[str, Any]: + return process_schema( + deepcopy(native), embed=embed, resolve_refs=resolve_refs + ) + + return ResourceSerializer( + name=name, options=options, response_type=response_type + ) + + broker = RabbitBroker(serializer=ResourceFactory()) + + @broker.subscriber("in") + async def handle(value: Opaque) -> None: ... + + document = specification(broker) + schemas = document["components"]["schemas"] + assert schemas["__fast_depends_input"] == native + assert ( + schemas["Handle:Message:Payload"]["$ref"] + == "#/components/schemas/__fast_depends_input/properties/value" + ) + assert_local_refs_resolve(document) + + def test_shared_schema_nodes_are_rewritten_once( + self, component_payload: ComponentGenerator + ) -> None: + shared = {"$ref": "#/$defs/Leaf"} + native = { + "title": "Payload", + "type": "object", + "properties": {"first": shared, "second": shared}, + "$defs": {"Leaf": {"type": "string"}}, + } + original = deepcopy(native) + document = component_payload(native) + schema = document["components"]["schemas"]["Payload"] + assert schema["properties"] == { + "first": {"$ref": "#/components/schemas/Leaf"}, + "second": {"$ref": "#/components/schemas/Leaf"}, + } + assert native == original + assert_local_refs_resolve(document) + + def test_shared_nodes_preserve_resource_scope_and_data_literals( + self, component_payload: ComponentGenerator + ) -> None: + shared = {"$ref": "#/$defs/Leaf"} + resource = { + "$id": "https://example.test/local", + "type": "object", + "properties": {"local": shared}, + "$defs": {"Leaf": {"type": "integer"}}, + } + native = { + "title": "Payload", + "type": "object", + "properties": {"global": shared, "scoped": resource}, + "default": shared, + "examples": [shared], + "$defs": {"Leaf": {"type": "string"}}, + } + original = deepcopy(native) + document = component_payload(native) + schema = document["components"]["schemas"]["Payload"] + assert schema["properties"]["global"] == {"$ref": "#/components/schemas/Leaf"} + assert schema["properties"]["scoped"] == resource + assert schema["default"] == {"$ref": "#/$defs/Leaf"} + assert schema["examples"] == [{"$ref": "#/$defs/Leaf"}] + assert native == original + assert_local_refs_resolve(document) diff --git a/uv.lock b/uv.lock index 853d80e342e..24535505b2f 100644 --- a/uv.lock +++ b/uv.lock @@ -756,16 +756,16 @@ wheels = [ [[package]] name = "fast-depends" -version = "3.0.9" +version = "4.0.0a1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, { name = "typing-extensions", version = "4.15.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.13'" }, { name = "typing-extensions", version = "4.16.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.13'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/4d/8e/0da74a68d1fab3370962802bde8726fbd9248d8156f9cf98f3562e654cc3/fast_depends-3.0.9.tar.gz", hash = "sha256:c31c3985d0196ea4998da9f5913a76ede75cc4484d89eeafcea1a6bd64fbca82", size = 18437, upload-time = "2026-09-19T12:37:28.181Z" } +sdist = { url = "https://files.pythonhosted.org/packages/1b/3c/8dafef5fa8b3314e463b9b8c5dfb0a412b439c02db55288f3b76c86412bf/fast_depends-4.0.0a1.tar.gz", hash = "sha256:5e0c957c58d03f6234566d61fd2f89a9d409f1bb07af4f7c9969006fefea8aa4", size = 27054, upload-time = "2026-11-15T13:32:17.896Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b6/c3/a4e6a88229798f5afe0e79a9e81947731a89e3f19659b7e90980cfedeee4/fast_depends-3.0.9-py3-none-any.whl", hash = "sha256:a9fda223e4f9f92ade11dabfdc31d20e62fedc25340f1a5b1f01db2ae25ab1d9", size = 25521, upload-time = "2026-09-19T12:37:26.863Z" }, + { url = "https://files.pythonhosted.org/packages/f4/36/319eb6ea0d3a38bacc3b449117a8f5fbff8b1676760a9f616744d3c95ca7/fast_depends-4.0.0a1-py3-none-any.whl", hash = "sha256:14333097774234fb359c92d185e0919085125411c0dd4788438f44e92b1c6dcb", size = 34426, upload-time = "2026-11-15T13:32:16.58Z" }, ] [package.optional-dependencies] @@ -974,7 +974,7 @@ requires-dist = [ { name = "anyio", specifier = ">=4.14.2,<5" }, { name = "confluent-kafka", marker = "python_full_version >= '3.13' and extra == 'confluent'", specifier = ">=2.6,!=2.8.1,<3" }, { name = "confluent-kafka", marker = "python_full_version < '3.13' and extra == 'confluent'", specifier = ">=2,!=2.8.1,<3" }, - { name = "fast-depends", extras = ["pydantic"], specifier = ">=3.0.9" }, + { name = "fast-depends", extras = ["pydantic"], specifier = ">=4.0.0a0,<5.0.0" }, { name = "nats-py", marker = "extra == 'nats'", specifier = ">=2.14.0,<=3.0.0" }, { name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.24.0,<2.0.0" }, { name = "prometheus-client", marker = "extra == 'prometheus'", specifier = ">=0.20.0,<0.30.0" }, From 4aa69015a3a75c91a379380f609bd32ea61af417 Mon Sep 17 00:00:00 2001 From: Lancetnik Date: Sun, 15 Nov 2026 21:23:06 +0300 Subject: [PATCH 5/8] test: share AsyncAPI serializer cases across brokers --- tests/asyncapi/base/arguments.py | 278 +++++++ tests/asyncapi/base/publisher.py | 85 +++ tests/asyncapi/base/serialization.py | 109 +++ .../confluent/v2_6_0/test_arguments.py | 3 +- .../confluent/v2_6_0/test_publisher.py | 3 +- .../confluent/v3_0_0/test_arguments.py | 3 +- .../confluent/v3_0_0/test_publisher.py | 3 +- tests/asyncapi/kafka/v2_6_0/test_arguments.py | 3 +- tests/asyncapi/kafka/v2_6_0/test_publisher.py | 3 +- tests/asyncapi/kafka/v3_0_0/test_arguments.py | 3 +- tests/asyncapi/kafka/v3_0_0/test_publisher.py | 3 +- tests/asyncapi/mqtt/v2_6_0/test_arguments.py | 3 +- tests/asyncapi/mqtt/v2_6_0/test_publisher.py | 3 +- tests/asyncapi/mqtt/v3_0_0/test_arguments.py | 3 +- tests/asyncapi/mqtt/v3_0_0/test_publisher.py | 3 +- tests/asyncapi/nats/v2_6_0/test_arguments.py | 3 +- tests/asyncapi/nats/v2_6_0/test_publisher.py | 3 +- tests/asyncapi/nats/v3_0_0/test_arguments.py | 3 +- tests/asyncapi/nats/v3_0_0/test_publisher.py | 3 +- .../asyncapi/rabbit/v2_6_0/test_arguments.py | 3 +- .../asyncapi/rabbit/v2_6_0/test_publisher.py | 3 +- .../asyncapi/rabbit/v3_0_0/test_arguments.py | 3 +- .../asyncapi/rabbit/v3_0_0/test_publisher.py | 3 +- tests/asyncapi/redis/v2_6_0/test_arguments.py | 3 +- tests/asyncapi/redis/v2_6_0/test_publisher.py | 3 +- tests/asyncapi/redis/v3_0_0/test_arguments.py | 3 +- tests/asyncapi/redis/v3_0_0/test_publisher.py | 3 +- tests/asyncapi/test_message.py | 58 ++ tests/asyncapi/test_schema_refs.py | 187 +++++ tests/asyncapi/test_serializers.py | 687 ------------------ 30 files changed, 765 insertions(+), 711 deletions(-) create mode 100644 tests/asyncapi/base/arguments.py create mode 100644 tests/asyncapi/base/publisher.py create mode 100644 tests/asyncapi/base/serialization.py create mode 100644 tests/asyncapi/test_message.py create mode 100644 tests/asyncapi/test_schema_refs.py delete mode 100644 tests/asyncapi/test_serializers.py diff --git a/tests/asyncapi/base/arguments.py b/tests/asyncapi/base/arguments.py new file mode 100644 index 00000000000..b9c5916eb10 --- /dev/null +++ b/tests/asyncapi/base/arguments.py @@ -0,0 +1,278 @@ +from collections.abc import Iterable +from copy import deepcopy +from typing import Annotated, Any, Literal + +import msgspec +import pytest +from dirty_equals import IsPartialDict +from fast_depends import Depends, Provider +from fast_depends.library.schema_processing import SchemaExclude, process_schema +from fast_depends.library.serializer import OptionItem, Serializer, SerializerProto +from fast_depends.msgspec import MsgSpecSerializer +from fast_depends.pydantic import PydanticSerializer +from pydantic import Field + +from .basic import SpecificationFactory +from .serialization import ( + Item, + NativeFactory, + Opaque, + Tree, + assert_local_refs_resolve, + assert_msgspec_payload, +) + + +class SerializerArgumentsTestcase(SpecificationFactory): + broker_class: Any + + @pytest.mark.parametrize( + "annotation", + ( + pytest.param(Item, id="struct"), + pytest.param(list[Item], id="struct-list"), + pytest.param(Tree, id="recursive-struct"), + ), + ) + def test_msgspec_subscriber_payloads(self, annotation: Any) -> None: + broker = self.broker_class(serializer=MsgSpecSerializer()) + + @broker.subscriber("in") + async def handle(value: annotation) -> None: ... + + document = self.get_spec(broker).to_jsonable() + assert_msgspec_payload(document, annotation) + + def test_msgspec_field_alias_and_constraint(self) -> None: + broker = self.broker_class(serializer=MsgSpecSerializer()) + + @broker.subscriber("in") + async def handle( + count: Annotated[int, msgspec.Meta(ge=1)] = msgspec.field(name="size"), + label: Literal["a", "b"] = "a", + ) -> None: ... + + schema = self.get_spec(broker).to_jsonable()["components"]["schemas"][ + "Handle:Message:Payload" + ] + assert schema["properties"]["size"] == {"type": "integer", "minimum": 1} + assert schema["properties"]["label"] == {"enum": ["a", "b"], "default": "a"} + assert schema["required"] == ["size"] + + def test_selected_factory_configuration(self) -> None: + broker = self.broker_class( + serializer=PydanticSerializer(pydantic_config={"alias_generator": str.upper}) + ) + + @broker.subscriber("in") + async def handle(first: int, second: str) -> None: ... + + schema = self.get_spec(broker).to_jsonable()["components"]["schemas"][ + "Handle:Message:Payload" + ] + assert set(schema["properties"]) == {"FIRST", "SECOND"} + assert schema["required"] == ["FIRST", "SECOND"] + + def test_explicit_field_title(self) -> None: + broker = self.broker_class() + + @broker.subscriber("in") + async def handle(value: Annotated[int, Field(title="Counter", gt=0)]) -> None: ... + + assert self.get_spec(broker).to_jsonable()["components"]["schemas"][ + "Counter" + ] == { + "title": "Counter", + "type": "integer", + "exclusiveMinimum": 0, + } + + @pytest.mark.parametrize( + ("annotation", "default", "title"), + ( + pytest.param( + Annotated[int, Field(title="First"), Field(title="Second")], + ..., + "Second", + id="last-annotation-title", + ), + pytest.param( + Annotated[int, Field(title="Inner")], + Field(title="Outer"), + "Outer", + id="default-title", + ), + ), + ) + def test_field_title_uses_backend_precedence( + self, + annotation: Any, + default: Any, + title: str, + ) -> None: + broker = self.broker_class() + + @broker.subscriber("in") + async def handle(value: annotation = default) -> None: ... + + schema = self.get_spec(broker).to_jsonable()["components"]["schemas"][title] + assert schema["title"] == title + assert schema["type"] == "integer" + + def test_single_field_alias_does_not_merge_unrelated_components(self) -> None: + broker = self.broker_class() + + @broker.subscriber("first") + async def first(value: int = Field(alias="wire")) -> None: ... + @broker.subscriber("second") + async def second(value: str = Field(alias="wire")) -> None: ... + + schemas = self.get_spec(broker).to_jsonable()["components"]["schemas"] + assert schemas["First:Message:Payload"]["type"] == "integer" + assert schemas["Second:Message:Payload"]["type"] == "string" + assert "Wire" not in schemas + + def test_custom_backend_uses_exact_ref_and_preserves_data(self) -> None: + factory = NativeFactory() + original = deepcopy(factory.document) + broker = self.broker_class(serializer=factory) + + @broker.subscriber("in") + async def handler(value: Opaque) -> None: ... + + document = self.get_spec(broker).to_jsonable() + schema = document["components"]["schemas"]["Actual"] + assert schema == { + "title": "Actual", + "type": "string", + "pattern": "^x", + "description": "literal #/definitions/Unused", + "examples": [{"$ref": "#/definitions/Unused"}], + } + assert factory.document == original + assert_local_refs_resolve(document) + + def test_nested_scoped_resource_from_options_aware_backend(self) -> None: + resource = { + "$id": "https://example.test/record", + "$ref": "#/$defs/Node", + "$defs": { + "Node": { + "title": "Node", + "type": "object", + "properties": {"child": {"$ref": "#/$defs/Node"}}, + } + }, + } + + class ResourceFactory(SerializerProto): + def __call__( + self, *, name: str, options: list[OptionItem], response_type: Any + ) -> Serializer: + class ResourceSerializer(Serializer): + def __call__(self, kwargs: dict[str, Any]) -> dict[str, Any]: + return kwargs + + def get_schema( + self, + *, + embed: bool = False, + exclude: Iterable[SchemaExclude] = (), + resolve_refs: bool = False, + ) -> dict[str, Any]: + schema = { + "type": "object", + "properties": { + p.field_name: deepcopy(resource) for p in options + }, + } + return process_schema( + schema, embed=embed, resolve_refs=resolve_refs + ) + + return ResourceSerializer( + name=name, options=options, response_type=response_type + ) + + broker = self.broker_class(serializer=ResourceFactory()) + + @broker.subscriber("in") + async def handle(value: Opaque) -> None: ... + + document = self.get_spec(broker).to_jsonable() + schemas = document["components"]["schemas"] + assert schemas["__fast_depends_input"]["properties"]["value"] == resource + assert ( + schemas["Handle:Message:Payload"]["$ref"] + == "#/components/schemas/__fast_depends_input/properties/value" + ) + assert_local_refs_resolve(document) + + def test_input_resource_scope_is_preserved_during_embedding(self) -> None: + native = { + "$id": "https://example.test/inputs", + "type": "object", + "properties": {"value": {"$ref": "#/$defs/Node"}}, + "$defs": { + "Node": { + "type": "object", + "properties": { + "children": {"type": "array", "items": {"$ref": "#/$defs/Node"}} + }, + } + }, + } + + class ResourceFactory(SerializerProto): + def __call__( + self, *, name: str, options: list[OptionItem], response_type: Any + ) -> Serializer: + class ResourceSerializer(Serializer): + def __call__(self, kwargs: dict[str, Any]) -> dict[str, Any]: + return kwargs + + def get_schema( + self, + *, + embed: bool = False, + exclude: Iterable[SchemaExclude] = (), + resolve_refs: bool = False, + ) -> dict[str, Any]: + return process_schema( + deepcopy(native), embed=embed, resolve_refs=resolve_refs + ) + + return ResourceSerializer( + name=name, options=options, response_type=response_type + ) + + broker = self.broker_class(serializer=ResourceFactory()) + + @broker.subscriber("in") + async def handle(value: Opaque) -> None: ... + + document = self.get_spec(broker).to_jsonable() + schemas = document["components"]["schemas"] + assert schemas["__fast_depends_input"] == native + assert ( + schemas["Handle:Message:Payload"]["$ref"] + == "#/components/schemas/__fast_depends_input/properties/value" + ) + assert_local_refs_resolve(document) + + def test_dependency_override_changes_body_schema(self) -> None: + provider = Provider() + + async def dependency(count: int) -> None: ... + async def replacement(item: Item) -> None: ... + async def handler(value: Annotated[Any, Depends(dependency)]) -> None: ... + + broker = self.broker_class(serializer=MsgSpecSerializer(), provider=provider) + broker.subscriber("in")(handler) + schemas = self.get_spec(broker).to_jsonable()["components"]["schemas"] + assert list(schemas.values()) == [IsPartialDict({"type": "integer"})] + with provider.scope(dependency, replacement): + schemas = self.get_spec(broker).to_jsonable()["components"]["schemas"] + assert list(schemas) == ["Item"] + schemas = self.get_spec(broker).to_jsonable()["components"]["schemas"] + assert list(schemas.values()) == [IsPartialDict({"type": "integer"})] diff --git a/tests/asyncapi/base/publisher.py b/tests/asyncapi/base/publisher.py new file mode 100644 index 00000000000..3e408d3e397 --- /dev/null +++ b/tests/asyncapi/base/publisher.py @@ -0,0 +1,85 @@ +from collections.abc import Callable +from typing import Annotated, Any, TypeAlias + +import msgspec +import pytest +from fast_depends.library.serializer import SerializerProto +from fast_depends.msgspec import MsgSpecSerializer +from fast_depends.pydantic import PydanticSerializer +from pydantic import Field, PlainSerializer + +from faststream.message import encode_message + +from .basic import SpecificationFactory +from .serialization import Item, Tree, assert_local_refs_resolve, assert_msgspec_payload + + +class SerializerPublisherTestcase(SpecificationFactory): + broker_class: Any + + @pytest.mark.parametrize( + "annotation", + ( + pytest.param(Item, id="struct"), + pytest.param(list[Item], id="struct-list"), + pytest.param(Tree, id="recursive-struct"), + ), + ) + def test_msgspec_publisher_payloads(self, annotation: Any) -> None: + broker = self.broker_class(serializer=MsgSpecSerializer()) + + @broker.publisher("out") + async def handle() -> annotation: ... + + document = self.get_spec(broker).to_jsonable() + assert_msgspec_payload(document, annotation) + + def test_explicit_msgspec_publisher_schema(self) -> None: + broker = self.broker_class(serializer=MsgSpecSerializer()) + broker.publisher("out", schema=Item) + document = self.get_spec(broker).to_jsonable() + assert document["components"]["schemas"]["Item"]["required"] == ["type", "itemId"] + assert_local_refs_resolve(document) + + @pytest.mark.parametrize( + ("factory", "metadata"), + ( + pytest.param(PydanticSerializer, Field, id="pydantic"), + pytest.param(MsgSpecSerializer, msgspec.Meta, id="msgspec"), + ), + ) + @pytest.mark.parametrize( + "title", + ( + pytest.param("Payload", id="default-title"), + pytest.param("Counter", id="custom-title"), + ), + ) + def test_publisher_preserves_explicit_scalar_title( + self, + factory: type[SerializerProto], + metadata: Callable[..., Any], + title: str, + ) -> None: + broker = self.broker_class(serializer=factory()) + Payload: TypeAlias = Annotated[int, metadata(title=title)] + + @broker.publisher("out") + async def handle() -> Payload: ... + + assert self.get_spec(broker).to_jsonable()["components"]["schemas"] == { + title: {"title": title, "type": "integer"} + } + + def test_publisher_keeps_generic_annotation_encoding_contract(self) -> None: + Payload: TypeAlias = Annotated[int, PlainSerializer(str, return_type=str)] + factory = PydanticSerializer() + broker = self.broker_class(serializer=factory) + + @broker.publisher("out") + async def handle() -> Payload: + return 42 + + schemas = self.get_spec(broker).to_jsonable()["components"]["schemas"] + assert next(iter(schemas.values()))["type"] == "integer" + assert encode_message(42, factory)[0] == b"42" diff --git a/tests/asyncapi/base/serialization.py b/tests/asyncapi/base/serialization.py new file mode 100644 index 00000000000..a27c2b0675a --- /dev/null +++ b/tests/asyncapi/base/serialization.py @@ -0,0 +1,109 @@ +from collections.abc import Iterable +from typing import Annotated, Any +from urllib.parse import unquote + +import msgspec +from dirty_equals import IsPartialDict +from fast_depends.library.schema_processing import SchemaExclude, process_schema +from fast_depends.library.serializer import OptionItem, Serializer, SerializerProto + + +class Item(msgspec.Struct, rename="camel", tag="item", omit_defaults=True): + item_id: Annotated[int, msgspec.Meta(gt=0)] + label: str = "" + + +class Tree(msgspec.Struct): + children: list["Tree"] = msgspec.field(default_factory=list) + + +class Opaque: + pass + + +def assert_local_refs_resolve(document: dict[str, Any]) -> None: + def visit(value: Any) -> None: + if isinstance(value, dict): + if "$id" in value: + return + if isinstance(reference := value.get("$ref"), str) and reference.startswith( + "#/" + ): + target = document + for token in unquote(reference[2:]).split("/"): + target = target[token.replace("~1", "/").replace("~0", "~")] + for key, child in value.items(): + if key not in {"default", "examples", "enum", "const"}: + visit(child) + elif isinstance(value, list): + for child in value: + visit(child) + + visit(document) + + +class NativeFactory(SerializerProto): + def __init__(self) -> None: + self.document: dict[str, Any] = { + "$ref": "#/definitions/Actual", + "definitions": { + "Unused": {"type": "integer"}, + "Actual": { + "title": "Actual", + "type": "string", + "pattern": "^x", + "description": "literal #/definitions/Unused", + "examples": [{"$ref": "#/definitions/Unused"}], + }, + }, + } + + def __call__( + self, *, name: str, options: list[OptionItem], response_type: Any + ) -> Serializer: + document = self.document + + class NativeSerializer(Serializer): + def __call__(self, kwargs: dict[str, Any]) -> dict[str, Any]: + return kwargs + + def get_schema( + self, + *, + embed: bool = False, + exclude: Iterable[SchemaExclude] = (), + resolve_refs: bool = False, + ) -> dict[str, Any]: + schema = { + "type": "object", + "properties": { + p.field_name: {"$ref": document["$ref"]} for p in options + }, + "definitions": document["definitions"], + } + return process_schema(schema, embed=embed, resolve_refs=resolve_refs) + + return NativeSerializer(name=name, options=options, response_type=response_type) + + +def assert_msgspec_payload(document: dict[str, Any], annotation: Any) -> None: + schemas = document["components"]["schemas"] + assert_local_refs_resolve(document) + if annotation is Tree: + assert schemas["Tree"]["properties"]["children"]["items"] == { + "$ref": "#/components/schemas/Tree" + } + else: + assert schemas["Item"] == IsPartialDict({ + "properties": { + "type": {"enum": ["item"]}, + "itemId": {"type": "integer", "exclusiveMinimum": 0}, + "label": {"type": "string", "default": ""}, + }, + "required": ["type", "itemId"], + }) + if annotation == list[Item]: + assert any( + value.get("items") == {"$ref": "#/components/schemas/Item"} + for value in schemas.values() + ) diff --git a/tests/asyncapi/confluent/v2_6_0/test_arguments.py b/tests/asyncapi/confluent/v2_6_0/test_arguments.py index 331bf04ecd9..afaae10e887 100644 --- a/tests/asyncapi/confluent/v2_6_0/test_arguments.py +++ b/tests/asyncapi/confluent/v2_6_0/test_arguments.py @@ -3,12 +3,13 @@ import pytest from faststream.confluent import KafkaBroker, TopicPartition +from tests.asyncapi.base.arguments import SerializerArgumentsTestcase from tests.asyncapi.base.body_binding import BodyBindingTestcase from tests.asyncapi.base.v2_6_0.arguments import ArgumentsTestcase @pytest.mark.confluent() -class TestArguments(BodyBindingTestcase, ArgumentsTestcase): +class TestArguments(SerializerArgumentsTestcase, BodyBindingTestcase, ArgumentsTestcase): broker_class = KafkaBroker def test_subscriber_bindings(self) -> None: diff --git a/tests/asyncapi/confluent/v2_6_0/test_publisher.py b/tests/asyncapi/confluent/v2_6_0/test_publisher.py index d514a41dd92..c87fb6f4846 100644 --- a/tests/asyncapi/confluent/v2_6_0/test_publisher.py +++ b/tests/asyncapi/confluent/v2_6_0/test_publisher.py @@ -3,11 +3,12 @@ import pytest from faststream.confluent import KafkaBroker +from tests.asyncapi.base.publisher import SerializerPublisherTestcase from tests.asyncapi.base.v2_6_0.publisher import PublisherTestcase @pytest.mark.confluent() -class TestArguments(PublisherTestcase): +class TestArguments(SerializerPublisherTestcase, PublisherTestcase): broker_class = KafkaBroker def test_publisher_bindings(self) -> None: diff --git a/tests/asyncapi/confluent/v3_0_0/test_arguments.py b/tests/asyncapi/confluent/v3_0_0/test_arguments.py index 4784ac60294..e4d5fb42b2f 100644 --- a/tests/asyncapi/confluent/v3_0_0/test_arguments.py +++ b/tests/asyncapi/confluent/v3_0_0/test_arguments.py @@ -3,12 +3,13 @@ import pytest from faststream.confluent import KafkaBroker +from tests.asyncapi.base.arguments import SerializerArgumentsTestcase from tests.asyncapi.base.body_binding import BodyBindingTestcase from tests.asyncapi.base.v3_0_0.arguments import ArgumentsTestcase @pytest.mark.confluent() -class TestArguments(BodyBindingTestcase, ArgumentsTestcase): +class TestArguments(SerializerArgumentsTestcase, BodyBindingTestcase, ArgumentsTestcase): broker_class = KafkaBroker def test_subscriber_bindings(self) -> None: diff --git a/tests/asyncapi/confluent/v3_0_0/test_publisher.py b/tests/asyncapi/confluent/v3_0_0/test_publisher.py index 8c127f58c9a..3e67e19efe4 100644 --- a/tests/asyncapi/confluent/v3_0_0/test_publisher.py +++ b/tests/asyncapi/confluent/v3_0_0/test_publisher.py @@ -3,11 +3,12 @@ import pytest from faststream.confluent import KafkaBroker +from tests.asyncapi.base.publisher import SerializerPublisherTestcase from tests.asyncapi.base.v3_0_0.publisher import PublisherTestcase @pytest.mark.confluent() -class TestArguments(PublisherTestcase): +class TestArguments(SerializerPublisherTestcase, PublisherTestcase): broker_class = KafkaBroker def test_publisher_bindings(self) -> None: diff --git a/tests/asyncapi/kafka/v2_6_0/test_arguments.py b/tests/asyncapi/kafka/v2_6_0/test_arguments.py index f0ae35ab599..75d18228f4a 100644 --- a/tests/asyncapi/kafka/v2_6_0/test_arguments.py +++ b/tests/asyncapi/kafka/v2_6_0/test_arguments.py @@ -3,12 +3,13 @@ import pytest from faststream.kafka import KafkaBroker, TopicPartition +from tests.asyncapi.base.arguments import SerializerArgumentsTestcase from tests.asyncapi.base.body_binding import BodyBindingTestcase from tests.asyncapi.base.v2_6_0.arguments import ArgumentsTestcase @pytest.mark.kafka() -class TestArguments(BodyBindingTestcase, ArgumentsTestcase): +class TestArguments(SerializerArgumentsTestcase, BodyBindingTestcase, ArgumentsTestcase): broker_class = KafkaBroker def test_subscriber_bindings(self) -> None: diff --git a/tests/asyncapi/kafka/v2_6_0/test_publisher.py b/tests/asyncapi/kafka/v2_6_0/test_publisher.py index b28a8e35c4d..00a67097607 100644 --- a/tests/asyncapi/kafka/v2_6_0/test_publisher.py +++ b/tests/asyncapi/kafka/v2_6_0/test_publisher.py @@ -3,11 +3,12 @@ import pytest from faststream.kafka import KafkaBroker +from tests.asyncapi.base.publisher import SerializerPublisherTestcase from tests.asyncapi.base.v2_6_0.publisher import PublisherTestcase @pytest.mark.kafka() -class TestArguments(PublisherTestcase): +class TestArguments(SerializerPublisherTestcase, PublisherTestcase): broker_class = KafkaBroker def test_publisher_bindings(self) -> None: diff --git a/tests/asyncapi/kafka/v3_0_0/test_arguments.py b/tests/asyncapi/kafka/v3_0_0/test_arguments.py index be3498e9ae2..de48b694061 100644 --- a/tests/asyncapi/kafka/v3_0_0/test_arguments.py +++ b/tests/asyncapi/kafka/v3_0_0/test_arguments.py @@ -3,12 +3,13 @@ import pytest from faststream.kafka import KafkaBroker +from tests.asyncapi.base.arguments import SerializerArgumentsTestcase from tests.asyncapi.base.body_binding import BodyBindingTestcase from tests.asyncapi.base.v3_0_0.arguments import ArgumentsTestcase @pytest.mark.kafka() -class TestArguments(BodyBindingTestcase, ArgumentsTestcase): +class TestArguments(SerializerArgumentsTestcase, BodyBindingTestcase, ArgumentsTestcase): broker_class = KafkaBroker def test_subscriber_bindings(self) -> None: diff --git a/tests/asyncapi/kafka/v3_0_0/test_publisher.py b/tests/asyncapi/kafka/v3_0_0/test_publisher.py index 3def8f5f917..2b4feccf358 100644 --- a/tests/asyncapi/kafka/v3_0_0/test_publisher.py +++ b/tests/asyncapi/kafka/v3_0_0/test_publisher.py @@ -3,11 +3,12 @@ import pytest from faststream.kafka import KafkaBroker +from tests.asyncapi.base.publisher import SerializerPublisherTestcase from tests.asyncapi.base.v3_0_0.publisher import PublisherTestcase @pytest.mark.kafka() -class TestArguments(PublisherTestcase): +class TestArguments(SerializerPublisherTestcase, PublisherTestcase): broker_class = KafkaBroker def test_publisher_bindings(self) -> None: diff --git a/tests/asyncapi/mqtt/v2_6_0/test_arguments.py b/tests/asyncapi/mqtt/v2_6_0/test_arguments.py index ca8593a972d..d592229db05 100644 --- a/tests/asyncapi/mqtt/v2_6_0/test_arguments.py +++ b/tests/asyncapi/mqtt/v2_6_0/test_arguments.py @@ -4,12 +4,13 @@ from syrupy.assertion import SnapshotAssertion from faststream.mqtt import MQTTBroker +from tests.asyncapi.base.arguments import SerializerArgumentsTestcase from tests.asyncapi.base.body_binding import BodyBindingTestcase from tests.asyncapi.base.v2_6_0.arguments import ArgumentsTestcase @pytest.mark.mqtt() -class TestArguments(BodyBindingTestcase, ArgumentsTestcase): +class TestArguments(SerializerArgumentsTestcase, BodyBindingTestcase, ArgumentsTestcase): broker_class = MQTTBroker def test_subscriber_bindings(self, snapshot_json: SnapshotAssertion) -> None: diff --git a/tests/asyncapi/mqtt/v2_6_0/test_publisher.py b/tests/asyncapi/mqtt/v2_6_0/test_publisher.py index 91864aa0f32..c5181295724 100644 --- a/tests/asyncapi/mqtt/v2_6_0/test_publisher.py +++ b/tests/asyncapi/mqtt/v2_6_0/test_publisher.py @@ -4,11 +4,12 @@ from syrupy.assertion import SnapshotAssertion from faststream.mqtt import MQTTBroker +from tests.asyncapi.base.publisher import SerializerPublisherTestcase from tests.asyncapi.base.v2_6_0.publisher import PublisherTestcase @pytest.mark.mqtt() -class TestArguments(PublisherTestcase): +class TestArguments(SerializerPublisherTestcase, PublisherTestcase): broker_class = MQTTBroker def test_publisher_bindings(self, snapshot_json: SnapshotAssertion) -> None: diff --git a/tests/asyncapi/mqtt/v3_0_0/test_arguments.py b/tests/asyncapi/mqtt/v3_0_0/test_arguments.py index a82cd3245b0..bc44d1c4527 100644 --- a/tests/asyncapi/mqtt/v3_0_0/test_arguments.py +++ b/tests/asyncapi/mqtt/v3_0_0/test_arguments.py @@ -4,12 +4,13 @@ from syrupy.assertion import SnapshotAssertion from faststream.mqtt import MQTTBroker +from tests.asyncapi.base.arguments import SerializerArgumentsTestcase from tests.asyncapi.base.body_binding import BodyBindingTestcase from tests.asyncapi.base.v3_0_0.arguments import ArgumentsTestcase @pytest.mark.mqtt() -class TestArguments(BodyBindingTestcase, ArgumentsTestcase): +class TestArguments(SerializerArgumentsTestcase, BodyBindingTestcase, ArgumentsTestcase): broker_class = MQTTBroker def test_subscriber_bindings(self, snapshot_json: SnapshotAssertion) -> None: diff --git a/tests/asyncapi/mqtt/v3_0_0/test_publisher.py b/tests/asyncapi/mqtt/v3_0_0/test_publisher.py index 085cb4852d5..8c1522b4c8a 100644 --- a/tests/asyncapi/mqtt/v3_0_0/test_publisher.py +++ b/tests/asyncapi/mqtt/v3_0_0/test_publisher.py @@ -4,11 +4,12 @@ from syrupy.assertion import SnapshotAssertion from faststream.mqtt import MQTTBroker +from tests.asyncapi.base.publisher import SerializerPublisherTestcase from tests.asyncapi.base.v3_0_0.publisher import PublisherTestcase @pytest.mark.mqtt() -class TestArguments(PublisherTestcase): +class TestArguments(SerializerPublisherTestcase, PublisherTestcase): broker_class = MQTTBroker def test_publisher_bindings(self, snapshot_json: SnapshotAssertion) -> None: diff --git a/tests/asyncapi/nats/v2_6_0/test_arguments.py b/tests/asyncapi/nats/v2_6_0/test_arguments.py index 5ae7511ad76..21405b33442 100644 --- a/tests/asyncapi/nats/v2_6_0/test_arguments.py +++ b/tests/asyncapi/nats/v2_6_0/test_arguments.py @@ -4,12 +4,13 @@ from syrupy.assertion import SnapshotAssertion from faststream.nats import NatsBroker +from tests.asyncapi.base.arguments import SerializerArgumentsTestcase from tests.asyncapi.base.body_binding import BodyBindingTestcase from tests.asyncapi.base.v2_6_0.arguments import ArgumentsTestcase @pytest.mark.nats() -class TestArguments(BodyBindingTestcase, ArgumentsTestcase): +class TestArguments(SerializerArgumentsTestcase, BodyBindingTestcase, ArgumentsTestcase): broker_class = NatsBroker def test_subscriber_bindings(self, snapshot_json: SnapshotAssertion) -> None: diff --git a/tests/asyncapi/nats/v2_6_0/test_publisher.py b/tests/asyncapi/nats/v2_6_0/test_publisher.py index 95e52e46392..11fbb56ac26 100644 --- a/tests/asyncapi/nats/v2_6_0/test_publisher.py +++ b/tests/asyncapi/nats/v2_6_0/test_publisher.py @@ -4,11 +4,12 @@ from syrupy.assertion import SnapshotAssertion from faststream.nats import NatsBroker +from tests.asyncapi.base.publisher import SerializerPublisherTestcase from tests.asyncapi.base.v2_6_0.publisher import PublisherTestcase @pytest.mark.nats() -class TestArguments(PublisherTestcase): +class TestArguments(SerializerPublisherTestcase, PublisherTestcase): broker_class = NatsBroker def test_publisher_bindings(self, snapshot_json: SnapshotAssertion) -> None: diff --git a/tests/asyncapi/nats/v3_0_0/test_arguments.py b/tests/asyncapi/nats/v3_0_0/test_arguments.py index 76ad130f77f..e09e379c6dc 100644 --- a/tests/asyncapi/nats/v3_0_0/test_arguments.py +++ b/tests/asyncapi/nats/v3_0_0/test_arguments.py @@ -4,12 +4,13 @@ from syrupy.assertion import SnapshotAssertion from faststream.nats import NatsBroker +from tests.asyncapi.base.arguments import SerializerArgumentsTestcase from tests.asyncapi.base.body_binding import BodyBindingTestcase from tests.asyncapi.base.v3_0_0.arguments import ArgumentsTestcase @pytest.mark.nats() -class TestArguments(BodyBindingTestcase, ArgumentsTestcase): +class TestArguments(SerializerArgumentsTestcase, BodyBindingTestcase, ArgumentsTestcase): broker_class = NatsBroker def test_subscriber_bindings(self, snapshot_json: SnapshotAssertion) -> None: diff --git a/tests/asyncapi/nats/v3_0_0/test_publisher.py b/tests/asyncapi/nats/v3_0_0/test_publisher.py index 873257e03e7..221e7a5157f 100644 --- a/tests/asyncapi/nats/v3_0_0/test_publisher.py +++ b/tests/asyncapi/nats/v3_0_0/test_publisher.py @@ -4,11 +4,12 @@ from syrupy.assertion import SnapshotAssertion from faststream.nats import NatsBroker +from tests.asyncapi.base.publisher import SerializerPublisherTestcase from tests.asyncapi.base.v3_0_0.publisher import PublisherTestcase @pytest.mark.nats() -class TestArguments(PublisherTestcase): +class TestArguments(SerializerPublisherTestcase, PublisherTestcase): broker_class = NatsBroker def test_publisher_bindings(self, snapshot_json: SnapshotAssertion) -> None: diff --git a/tests/asyncapi/rabbit/v2_6_0/test_arguments.py b/tests/asyncapi/rabbit/v2_6_0/test_arguments.py index 468b775c7cf..1701892c4ac 100644 --- a/tests/asyncapi/rabbit/v2_6_0/test_arguments.py +++ b/tests/asyncapi/rabbit/v2_6_0/test_arguments.py @@ -4,12 +4,13 @@ from syrupy.assertion import SnapshotAssertion from faststream.rabbit import ExchangeType, RabbitBroker, RabbitExchange, RabbitQueue +from tests.asyncapi.base.arguments import SerializerArgumentsTestcase from tests.asyncapi.base.body_binding import BodyBindingTestcase from tests.asyncapi.base.v2_6_0.arguments import ArgumentsTestcase @pytest.mark.rabbit() -class TestArguments(BodyBindingTestcase, ArgumentsTestcase): +class TestArguments(SerializerArgumentsTestcase, BodyBindingTestcase, ArgumentsTestcase): broker_class = RabbitBroker def test_subscriber_bindings(self, snapshot_json: SnapshotAssertion) -> None: diff --git a/tests/asyncapi/rabbit/v2_6_0/test_publisher.py b/tests/asyncapi/rabbit/v2_6_0/test_publisher.py index b83d6b8e621..5dbbdd2a822 100644 --- a/tests/asyncapi/rabbit/v2_6_0/test_publisher.py +++ b/tests/asyncapi/rabbit/v2_6_0/test_publisher.py @@ -4,11 +4,12 @@ from syrupy.assertion import SnapshotAssertion from faststream.rabbit import ExchangeType, RabbitBroker, RabbitExchange, RabbitQueue +from tests.asyncapi.base.publisher import SerializerPublisherTestcase from tests.asyncapi.base.v2_6_0.publisher import PublisherTestcase @pytest.mark.rabbit() -class TestArguments(PublisherTestcase): +class TestArguments(SerializerPublisherTestcase, PublisherTestcase): broker_class = RabbitBroker def test_just_exchange(self, snapshot_json: SnapshotAssertion) -> None: diff --git a/tests/asyncapi/rabbit/v3_0_0/test_arguments.py b/tests/asyncapi/rabbit/v3_0_0/test_arguments.py index 3921eae5f9b..eb6b3d7d85c 100644 --- a/tests/asyncapi/rabbit/v3_0_0/test_arguments.py +++ b/tests/asyncapi/rabbit/v3_0_0/test_arguments.py @@ -4,12 +4,13 @@ from syrupy.assertion import SnapshotAssertion from faststream.rabbit import ExchangeType, RabbitBroker, RabbitExchange, RabbitQueue +from tests.asyncapi.base.arguments import SerializerArgumentsTestcase from tests.asyncapi.base.body_binding import BodyBindingTestcase from tests.asyncapi.base.v3_0_0.arguments import ArgumentsTestcase @pytest.mark.rabbit() -class TestArguments(BodyBindingTestcase, ArgumentsTestcase): +class TestArguments(SerializerArgumentsTestcase, BodyBindingTestcase, ArgumentsTestcase): broker_class = RabbitBroker def test_subscriber_bindings(self, snapshot_json: SnapshotAssertion) -> None: diff --git a/tests/asyncapi/rabbit/v3_0_0/test_publisher.py b/tests/asyncapi/rabbit/v3_0_0/test_publisher.py index 8c267ce376a..0867e1aa41c 100644 --- a/tests/asyncapi/rabbit/v3_0_0/test_publisher.py +++ b/tests/asyncapi/rabbit/v3_0_0/test_publisher.py @@ -4,11 +4,12 @@ from syrupy.assertion import SnapshotAssertion from faststream.rabbit import ExchangeType, RabbitBroker, RabbitExchange, RabbitQueue +from tests.asyncapi.base.publisher import SerializerPublisherTestcase from tests.asyncapi.base.v3_0_0.publisher import PublisherTestcase @pytest.mark.rabbit() -class TestArguments(PublisherTestcase): +class TestArguments(SerializerPublisherTestcase, PublisherTestcase): broker_class = RabbitBroker def test_just_exchange(self, snapshot_json: SnapshotAssertion) -> None: diff --git a/tests/asyncapi/redis/v2_6_0/test_arguments.py b/tests/asyncapi/redis/v2_6_0/test_arguments.py index e26b4ad7329..1f07776c47e 100644 --- a/tests/asyncapi/redis/v2_6_0/test_arguments.py +++ b/tests/asyncapi/redis/v2_6_0/test_arguments.py @@ -4,12 +4,13 @@ from syrupy.assertion import SnapshotAssertion from faststream.redis import RedisBroker, StreamSub +from tests.asyncapi.base.arguments import SerializerArgumentsTestcase from tests.asyncapi.base.body_binding import BodyBindingTestcase from tests.asyncapi.base.v2_6_0.arguments import ArgumentsTestcase @pytest.mark.redis() -class TestArguments(BodyBindingTestcase, ArgumentsTestcase): +class TestArguments(SerializerArgumentsTestcase, BodyBindingTestcase, ArgumentsTestcase): broker_class = RedisBroker def test_channel_subscriber(self, snapshot_json: SnapshotAssertion) -> None: diff --git a/tests/asyncapi/redis/v2_6_0/test_publisher.py b/tests/asyncapi/redis/v2_6_0/test_publisher.py index 21ea4c3e2bc..3a5d33d61f2 100644 --- a/tests/asyncapi/redis/v2_6_0/test_publisher.py +++ b/tests/asyncapi/redis/v2_6_0/test_publisher.py @@ -4,11 +4,12 @@ from syrupy.assertion import SnapshotAssertion from faststream.redis import RedisBroker +from tests.asyncapi.base.publisher import SerializerPublisherTestcase from tests.asyncapi.base.v2_6_0.publisher import PublisherTestcase @pytest.mark.redis() -class TestArguments(PublisherTestcase): +class TestArguments(SerializerPublisherTestcase, PublisherTestcase): broker_class = RedisBroker def test_channel_publisher(self, snapshot_json: SnapshotAssertion) -> None: diff --git a/tests/asyncapi/redis/v3_0_0/test_arguments.py b/tests/asyncapi/redis/v3_0_0/test_arguments.py index fe3b55e8d25..691f64e6393 100644 --- a/tests/asyncapi/redis/v3_0_0/test_arguments.py +++ b/tests/asyncapi/redis/v3_0_0/test_arguments.py @@ -4,12 +4,13 @@ from syrupy.assertion import SnapshotAssertion from faststream.redis import RedisBroker, StreamSub +from tests.asyncapi.base.arguments import SerializerArgumentsTestcase from tests.asyncapi.base.body_binding import BodyBindingTestcase from tests.asyncapi.base.v3_0_0.arguments import ArgumentsTestcase @pytest.mark.redis() -class TestArguments(BodyBindingTestcase, ArgumentsTestcase): +class TestArguments(SerializerArgumentsTestcase, BodyBindingTestcase, ArgumentsTestcase): broker_class = RedisBroker def test_channel_subscriber(self, snapshot_json: SnapshotAssertion) -> None: diff --git a/tests/asyncapi/redis/v3_0_0/test_publisher.py b/tests/asyncapi/redis/v3_0_0/test_publisher.py index e91332a7413..3069218bb3e 100644 --- a/tests/asyncapi/redis/v3_0_0/test_publisher.py +++ b/tests/asyncapi/redis/v3_0_0/test_publisher.py @@ -4,11 +4,12 @@ from syrupy.assertion import SnapshotAssertion from faststream.redis import RedisBroker +from tests.asyncapi.base.publisher import SerializerPublisherTestcase from tests.asyncapi.base.v3_0_0.publisher import PublisherTestcase @pytest.mark.redis() -class TestArguments(PublisherTestcase): +class TestArguments(SerializerPublisherTestcase, PublisherTestcase): broker_class = RedisBroker def test_channel_publisher(self, snapshot_json: SnapshotAssertion) -> None: diff --git a/tests/asyncapi/test_message.py b/tests/asyncapi/test_message.py new file mode 100644 index 00000000000..bfd8fe694ad --- /dev/null +++ b/tests/asyncapi/test_message.py @@ -0,0 +1,58 @@ +from typing import Annotated + +import pytest +from fast_depends.library import CustomField, SchemaField +from fast_depends.library.serializer import OptionItem, SerializerProto +from fast_depends.msgspec import MsgSpecSerializer +from fast_depends.pydantic import PydanticSerializer + +from faststream._internal.di import FastDependsConfig +from faststream.exceptions import SetupError +from faststream.specification.asyncapi.message import ( + parse_handler_params, + prepare_payload, +) + + +class TestHandlerPayloads: + @pytest.mark.parametrize( + "factory", + ( + pytest.param(PydanticSerializer, id="pydantic"), + pytest.param(MsgSpecSerializer, id="msgspec"), + ), + ) + def test_custom_field_schemas_stay_outside_body( + self, factory: type[SerializerProto] + ) -> None: + class Header(CustomField): + def get_schema(self, parameter: OptionItem) -> SchemaField: + return SchemaField( + parameter.field_name, parameter.field_type, source="headers" + ) + + async def handler(payload: int, token: Annotated[str, Header()]) -> None: ... + + call = FastDependsConfig(serializer=factory()).build_call(handler) + assert parse_handler_params(call.dependent, "Handler:Message") == { + "title": "Handler:Message:Payload", + "type": "integer", + } + + def test_disabled_serializer_fails_clearly(self) -> None: + async def handler(value: int) -> None: ... + + call = FastDependsConfig(serializer=None).build_call(handler) + with pytest.raises(SetupError, match="serializer with JSON Schema support"): + parse_handler_params(call.dependent) + + +class TestPayloadPreparation: + def test_unrelated_definition_matching_title_is_preserved(self) -> None: + + native = { + "title": "Payload", + "properties": {"value": {"$ref": "#/$defs/Payload"}}, + "$defs": {"Payload": {"type": "string"}}, + } + assert prepare_payload(native, prefix="Case")["$defs"] == native["$defs"] diff --git a/tests/asyncapi/test_schema_refs.py b/tests/asyncapi/test_schema_refs.py new file mode 100644 index 00000000000..975c54bebcb --- /dev/null +++ b/tests/asyncapi/test_schema_refs.py @@ -0,0 +1,187 @@ +from collections.abc import Callable +from copy import deepcopy +from importlib import import_module +from typing import Any, TypeAlias + +import pytest + +from faststream.specification.asyncapi.message import prepare_payload +from tests.asyncapi.base.serialization import assert_local_refs_resolve + +ComponentGenerator: TypeAlias = Callable[[dict[str, Any]], dict[str, Any]] + + +@pytest.fixture( + params=( + pytest.param("v2_6_0", id="asyncapi-2.6"), + pytest.param("v3_0_0", id="asyncapi-3.0"), + ) +) +def component_payload(request: pytest.FixtureRequest) -> ComponentGenerator: + + module = import_module(f"faststream.specification.asyncapi.{request.param}.generate") + + def generate(native: dict[str, Any]) -> dict[str, Any]: + schemas: dict[str, Any] = {} + messages: dict[str, Any] = {} + message = module.Message( + title="Message", payload=prepare_payload(native, prefix="Case") + ) + kwargs: dict[str, Any] = { + "m": message, + "channel_name": "Channel", + "payloads": schemas, + "messages": messages, + } + if request.param == "v3_0_0": + kwargs["message_name"] = "Message" + module._resolve_msg_payloads(**kwargs) + return {"components": {"schemas": schemas}} + + return generate + + +class TestSchemaReferences: + def test_root_pointer_ref_is_rebased( + self, component_payload: ComponentGenerator + ) -> None: + native = { + "title": "Payload", + "type": "object", + "properties": { + "actual": {"type": "string"}, + "copy": {"$ref": "#/properties/actual"}, + }, + } + document = component_payload(native) + assert document["components"]["schemas"]["Payload"]["properties"]["copy"] == { + "$ref": "#/components/schemas/Payload/properties/actual" + } + assert_local_refs_resolve(document) + + def test_schema_dependencies_refs_are_rebased( + self, component_payload: ComponentGenerator + ) -> None: + native = { + "title": "Payload", + "type": "object", + "dependencies": { + "name": {"properties": {"alias": {"$ref": "#/definitions/Value"}}} + }, + "definitions": {"Value": {"type": "string"}}, + } + document = component_payload(native) + assert document["components"]["schemas"]["Payload"]["dependencies"]["name"][ + "properties" + ]["alias"] == {"$ref": "#/components/schemas/Value"} + assert_local_refs_resolve(document) + + def test_scoped_resource_keeps_recursive_definitions( + self, component_payload: ComponentGenerator + ) -> None: + native = { + "$id": "https://example.test/payload", + "$ref": "#/$defs/Node", + "$defs": { + "Node": { + "title": "Node", + "type": "object", + "properties": {"child": {"$ref": "#/$defs/Node"}}, + } + }, + } + schema = component_payload(native)["components"]["schemas"]["Case:Payload"] + assert schema == {**native, "title": "Case:Payload"} + + def test_root_ref_keeps_all_sibling_constraints( + self, component_payload: ComponentGenerator + ) -> None: + native = { + "$ref": "#/$defs/Actual", + "allOf": [{"minLength": 3}], + "$defs": {"Actual": {"type": "string"}}, + } + schema = component_payload(native)["components"]["schemas"]["Case:Payload"] + assert schema["allOf"] == [{"type": "string"}, {"minLength": 3}] + + def test_conflicting_definition_names_fail_clearly( + self, component_payload: ComponentGenerator + ) -> None: + native = { + "title": "Payload", + "properties": { + "text": {"$ref": "#/$defs/Shared"}, + "count": {"$ref": "#/definitions/Shared"}, + }, + "$defs": {"Shared": {"type": "string"}}, + "definitions": {"Shared": {"type": "integer"}}, + } + with pytest.raises( + ValueError, match="Conflicting schema definitions for 'Shared'" + ): + component_payload(native) + + def test_reference_tail_preserves_literal_percent_encoding( + self, component_payload: ComponentGenerator + ) -> None: + native = { + "title": "Payload", + "type": "object", + "properties": {"value": {"$ref": "#/$defs/Container/properties/%252F"}}, + "$defs": { + "Container": {"type": "object", "properties": {"%2F": {"type": "string"}}} + }, + } + document = component_payload(native) + assert document["components"]["schemas"]["Payload"]["properties"]["value"] == { + "$ref": "#/components/schemas/Container/properties/%252F" + } + assert_local_refs_resolve(document) + + def test_shared_schema_nodes_are_rewritten_once( + self, component_payload: ComponentGenerator + ) -> None: + shared = {"$ref": "#/$defs/Leaf"} + native = { + "title": "Payload", + "type": "object", + "properties": {"first": shared, "second": shared}, + "$defs": {"Leaf": {"type": "string"}}, + } + original = deepcopy(native) + document = component_payload(native) + schema = document["components"]["schemas"]["Payload"] + assert schema["properties"] == { + "first": {"$ref": "#/components/schemas/Leaf"}, + "second": {"$ref": "#/components/schemas/Leaf"}, + } + assert native == original + assert_local_refs_resolve(document) + + def test_shared_nodes_preserve_resource_scope_and_data_literals( + self, component_payload: ComponentGenerator + ) -> None: + shared = {"$ref": "#/$defs/Leaf"} + resource = { + "$id": "https://example.test/local", + "type": "object", + "properties": {"local": shared}, + "$defs": {"Leaf": {"type": "integer"}}, + } + native = { + "title": "Payload", + "type": "object", + "properties": {"global": shared, "scoped": resource}, + "default": shared, + "examples": [shared], + "$defs": {"Leaf": {"type": "string"}}, + } + original = deepcopy(native) + document = component_payload(native) + schema = document["components"]["schemas"]["Payload"] + assert schema["properties"]["global"] == {"$ref": "#/components/schemas/Leaf"} + assert schema["properties"]["scoped"] == resource + assert schema["default"] == {"$ref": "#/$defs/Leaf"} + assert schema["examples"] == [{"$ref": "#/$defs/Leaf"}] + assert native == original + assert_local_refs_resolve(document) diff --git a/tests/asyncapi/test_serializers.py b/tests/asyncapi/test_serializers.py deleted file mode 100644 index b28fc1d8525..00000000000 --- a/tests/asyncapi/test_serializers.py +++ /dev/null @@ -1,687 +0,0 @@ -from collections.abc import Callable, Iterable -from copy import deepcopy -from importlib import import_module -from typing import Annotated, Any, Literal, TypeAlias -from urllib.parse import unquote - -import msgspec -import pytest -from fast_depends import Depends, Provider -from fast_depends.library import CustomField, SchemaField -from fast_depends.library.schema_processing import SchemaExclude, process_schema -from fast_depends.library.serializer import OptionItem, Serializer, SerializerProto -from fast_depends.msgspec import MsgSpecSerializer -from fast_depends.pydantic import PydanticSerializer -from pydantic import Field, PlainSerializer - -from faststream._internal.di import FastDependsConfig -from faststream.exceptions import SetupError -from faststream.message import encode_message -from faststream.rabbit import RabbitBroker -from faststream.specification import AsyncAPI -from faststream.specification.asyncapi.message import ( - parse_handler_params, - prepare_payload, -) - -SpecificationGenerator: TypeAlias = Callable[[RabbitBroker], dict[str, Any]] -ComponentGenerator: TypeAlias = Callable[[dict[str, Any]], dict[str, Any]] - - -class Item(msgspec.Struct, rename="camel", tag="item", omit_defaults=True): - item_id: Annotated[int, msgspec.Meta(gt=0)] - label: str = "" - - -class Tree(msgspec.Struct): - children: list["Tree"] = msgspec.field(default_factory=list) - - -@pytest.fixture( - params=( - pytest.param("2.6.0", id="asyncapi-2.6"), - pytest.param("3.0.0", id="asyncapi-3.0"), - ) -) -def specification(request: pytest.FixtureRequest) -> SpecificationGenerator: - def generate(broker: RabbitBroker) -> dict[str, Any]: - factory = AsyncAPI(schema_version=request.param) - factory.add_broker(broker) - document = factory.to_specification().to_jsonable() - assert isinstance(document, dict) - return document - - return generate - - -def assert_local_refs_resolve(document: dict[str, Any]) -> None: - def visit(value: Any) -> None: - if isinstance(value, dict): - if "$id" in value: - return - if isinstance(reference := value.get("$ref"), str) and reference.startswith( - "#/" - ): - target = document - for token in unquote(reference[2:]).split("/"): - target = target[token.replace("~1", "/").replace("~0", "~")] - for key, child in value.items(): - if key not in {"default", "examples", "enum", "const"}: - visit(child) - elif isinstance(value, list): - for child in value: - visit(child) - - visit(document) - - -class Opaque: - pass - - -class NativeFactory(SerializerProto): - def __init__(self) -> None: - self.document: dict[str, Any] = { - "$ref": "#/definitions/Actual", - "definitions": { - "Unused": {"type": "integer"}, - "Actual": { - "title": "Actual", - "type": "string", - "pattern": "^x", - "description": "literal #/definitions/Unused", - "examples": [{"$ref": "#/definitions/Unused"}], - }, - }, - } - - def __call__( - self, *, name: str, options: list[OptionItem], response_type: Any - ) -> Serializer: - document = self.document - - class NativeSerializer(Serializer): - def __call__(self, kwargs: dict[str, Any]) -> dict[str, Any]: - return kwargs - - def get_schema( - self, - *, - embed: bool = False, - exclude: Iterable[SchemaExclude] = (), - resolve_refs: bool = False, - ) -> dict[str, Any]: - schema = { - "type": "object", - "properties": { - p.field_name: {"$ref": document["$ref"]} for p in options - }, - "definitions": document["definitions"], - } - return process_schema(schema, embed=embed, resolve_refs=resolve_refs) - - return NativeSerializer(name=name, options=options, response_type=response_type) - - -@pytest.fixture( - params=( - pytest.param("v2_6_0", id="asyncapi-2.6"), - pytest.param("v3_0_0", id="asyncapi-3.0"), - ) -) -def component_payload(request: pytest.FixtureRequest) -> ComponentGenerator: - - module = import_module(f"faststream.specification.asyncapi.{request.param}.generate") - - def generate(native: dict[str, Any]) -> dict[str, Any]: - schemas: dict[str, Any] = {} - messages: dict[str, Any] = {} - message = module.Message( - title="Message", payload=prepare_payload(native, prefix="Case") - ) - kwargs: dict[str, Any] = { - "m": message, - "channel_name": "Channel", - "payloads": schemas, - "messages": messages, - } - if request.param == "v3_0_0": - kwargs["message_name"] = "Message" - module._resolve_msg_payloads(**kwargs) - return {"components": {"schemas": schemas}} - - return generate - - -class TestMsgspecPayloads: - @pytest.mark.parametrize( - "publisher", - (pytest.param(False, id="subscriber"), pytest.param(True, id="publisher")), - ) - @pytest.mark.parametrize( - "annotation", - ( - pytest.param(Item, id="struct"), - pytest.param(list[Item], id="struct-list"), - pytest.param(Tree, id="recursive-struct"), - ), - ) - def test_msgspec_struct_payloads( - self, specification: SpecificationGenerator, publisher: bool, annotation: Any - ) -> None: - broker = RabbitBroker(serializer=MsgSpecSerializer()) - if publisher: - - @broker.publisher("out") - async def handle() -> annotation: ... - - else: - - @broker.subscriber("in") - async def handle(value: annotation) -> None: ... - - document = specification(broker) - schemas = document["components"]["schemas"] - assert_local_refs_resolve(document) - if annotation is Tree: - assert schemas["Tree"]["properties"]["children"]["items"] == { - "$ref": "#/components/schemas/Tree" - } - else: - assert schemas["Item"]["properties"] == { - "type": {"enum": ["item"]}, - "itemId": {"type": "integer", "exclusiveMinimum": 0}, - "label": {"type": "string", "default": ""}, - } - assert schemas["Item"]["required"] == ["type", "itemId"] - if annotation == list[Item]: - assert any( - value.get("items") == {"$ref": "#/components/schemas/Item"} - for value in schemas.values() - ) - - def test_explicit_msgspec_publisher_schema( - self, specification: SpecificationGenerator - ) -> None: - broker = RabbitBroker(serializer=MsgSpecSerializer()) - broker.publisher("out", schema=Item) - document = specification(broker) - assert document["components"]["schemas"]["Item"]["required"] == ["type", "itemId"] - assert_local_refs_resolve(document) - - def test_msgspec_field_alias_and_constraint( - self, specification: SpecificationGenerator - ) -> None: - broker = RabbitBroker(serializer=MsgSpecSerializer()) - - @broker.subscriber("in") - async def handle( - count: Annotated[int, msgspec.Meta(ge=1)] = msgspec.field(name="size"), - label: Literal["a", "b"] = "a", - ) -> None: ... - - schema = specification(broker)["components"]["schemas"]["Handle:Message:Payload"] - assert schema["properties"]["size"] == {"type": "integer", "minimum": 1} - assert schema["properties"]["label"] == {"enum": ["a", "b"], "default": "a"} - assert schema["required"] == ["size"] - - -class TestSerializerSelection: - @pytest.mark.parametrize( - "factory", - ( - pytest.param(PydanticSerializer, id="pydantic"), - pytest.param(MsgSpecSerializer, id="msgspec"), - ), - ) - def test_custom_field_schemas_stay_outside_body( - self, factory: type[SerializerProto] - ) -> None: - class Header(CustomField): - def get_schema(self, parameter: OptionItem) -> SchemaField: - return SchemaField( - parameter.field_name, parameter.field_type, source="headers" - ) - - async def handler(payload: int, token: Annotated[str, Header()]) -> None: ... - - call = FastDependsConfig(serializer=factory()).build_call(handler) - assert parse_handler_params(call.dependent, "Handler:Message") == { - "title": "Handler:Message:Payload", - "type": "integer", - } - - def test_selected_factory_configuration( - self, specification: SpecificationGenerator - ) -> None: - broker = RabbitBroker( - serializer=PydanticSerializer(pydantic_config={"alias_generator": str.upper}) - ) - - @broker.subscriber("in") - async def handle(first: int, second: str) -> None: ... - - schema = specification(broker)["components"]["schemas"]["Handle:Message:Payload"] - assert set(schema["properties"]) == {"FIRST", "SECOND"} - assert schema["required"] == ["FIRST", "SECOND"] - - def test_dependency_override_changes_body_schema(self) -> None: - provider = Provider() - - async def dependency(count: int) -> None: ... - async def replacement(item: Item) -> None: ... - async def handler(value: Annotated[Any, Depends(dependency)]) -> None: ... - - call = FastDependsConfig( - serializer=MsgSpecSerializer(), provider=provider - ).build_call(handler) - assert parse_handler_params(call.dependent)["type"] == "integer" - with provider.scope(dependency, replacement): - assert parse_handler_params(call.dependent)["title"] == "Item" - assert parse_handler_params(call.dependent)["type"] == "integer" - - def test_disabled_serializer_fails_clearly(self) -> None: - async def handler(value: int) -> None: ... - - call = FastDependsConfig(serializer=None).build_call(handler) - with pytest.raises(SetupError, match="serializer with JSON Schema support"): - parse_handler_params(call.dependent) - - -class TestPayloadTitles: - def test_explicit_field_title(self, specification: SpecificationGenerator) -> None: - broker = RabbitBroker() - - @broker.subscriber("in") - async def handle(value: Annotated[int, Field(title="Counter", gt=0)]) -> None: ... - - assert specification(broker)["components"]["schemas"]["Counter"] == { - "title": "Counter", - "type": "integer", - "exclusiveMinimum": 0, - } - - @pytest.mark.parametrize( - ("annotation", "default", "title"), - ( - pytest.param( - Annotated[int, Field(title="First"), Field(title="Second")], - ..., - "Second", - id="last-annotation-title", - ), - pytest.param( - Annotated[int, Field(title="Inner")], - Field(title="Outer"), - "Outer", - id="default-title", - ), - ), - ) - def test_field_title_uses_backend_precedence( - self, - specification: SpecificationGenerator, - annotation: Any, - default: Any, - title: str, - ) -> None: - broker = RabbitBroker() - - @broker.subscriber("in") - async def handle(value: annotation = default) -> None: ... - - schema = specification(broker)["components"]["schemas"][title] - assert schema["title"] == title - assert schema["type"] == "integer" - - def test_single_field_alias_does_not_merge_unrelated_components( - self, specification: SpecificationGenerator - ) -> None: - broker = RabbitBroker() - - @broker.subscriber("first") - async def first(value: int = Field(alias="wire")) -> None: ... - @broker.subscriber("second") - async def second(value: str = Field(alias="wire")) -> None: ... - - schemas = specification(broker)["components"]["schemas"] - assert schemas["First:Message:Payload"]["type"] == "integer" - assert schemas["Second:Message:Payload"]["type"] == "string" - assert "Wire" not in schemas - - def test_unrelated_definition_matching_title_is_preserved(self) -> None: - - native = { - "title": "Payload", - "properties": {"value": {"$ref": "#/$defs/Payload"}}, - "$defs": {"Payload": {"type": "string"}}, - } - assert prepare_payload(native, prefix="Case")["$defs"] == native["$defs"] - - @pytest.mark.parametrize( - ("factory", "metadata"), - ( - pytest.param(PydanticSerializer, Field, id="pydantic"), - pytest.param(MsgSpecSerializer, msgspec.Meta, id="msgspec"), - ), - ) - @pytest.mark.parametrize( - "title", - ( - pytest.param("Payload", id="default-title"), - pytest.param("Counter", id="custom-title"), - ), - ) - def test_publisher_preserves_explicit_scalar_title( - self, - specification: SpecificationGenerator, - factory: type[SerializerProto], - metadata: Callable[..., Any], - title: str, - ) -> None: - broker = RabbitBroker(serializer=factory()) - Payload: TypeAlias = Annotated[int, metadata(title=title)] - - @broker.publisher("out") - async def handle() -> Payload: ... - - assert specification(broker)["components"]["schemas"] == { - title: {"title": title, "type": "integer"} - } - - -class TestPublisherEncoding: - def test_publisher_keeps_generic_annotation_encoding_contract( - self, specification: SpecificationGenerator - ) -> None: - Payload: TypeAlias = Annotated[int, PlainSerializer(str, return_type=str)] - factory = PydanticSerializer() - broker = RabbitBroker(serializer=factory) - - @broker.publisher("out") - async def handle() -> Payload: - return 42 - - schemas = specification(broker)["components"]["schemas"] - assert next(iter(schemas.values()))["type"] == "integer" - assert encode_message(42, factory)[0] == b"42" - - -class TestSchemaReferences: - def test_custom_backend_uses_exact_ref_and_preserves_data( - self, specification: SpecificationGenerator - ) -> None: - factory = NativeFactory() - original = deepcopy(factory.document) - broker = RabbitBroker(serializer=factory) - - @broker.subscriber("in") - async def handler(value: Opaque) -> None: ... - - document = specification(broker) - schema = document["components"]["schemas"]["Actual"] - assert schema == { - "title": "Actual", - "type": "string", - "pattern": "^x", - "description": "literal #/definitions/Unused", - "examples": [{"$ref": "#/definitions/Unused"}], - } - assert factory.document == original - assert_local_refs_resolve(document) - - def test_root_pointer_ref_is_rebased( - self, component_payload: ComponentGenerator - ) -> None: - native = { - "title": "Payload", - "type": "object", - "properties": { - "actual": {"type": "string"}, - "copy": {"$ref": "#/properties/actual"}, - }, - } - document = component_payload(native) - assert document["components"]["schemas"]["Payload"]["properties"]["copy"] == { - "$ref": "#/components/schemas/Payload/properties/actual" - } - assert_local_refs_resolve(document) - - def test_schema_dependencies_refs_are_rebased( - self, component_payload: ComponentGenerator - ) -> None: - native = { - "title": "Payload", - "type": "object", - "dependencies": { - "name": {"properties": {"alias": {"$ref": "#/definitions/Value"}}} - }, - "definitions": {"Value": {"type": "string"}}, - } - document = component_payload(native) - assert document["components"]["schemas"]["Payload"]["dependencies"]["name"][ - "properties" - ]["alias"] == {"$ref": "#/components/schemas/Value"} - assert_local_refs_resolve(document) - - def test_scoped_resource_keeps_recursive_definitions( - self, component_payload: ComponentGenerator - ) -> None: - native = { - "$id": "https://example.test/payload", - "$ref": "#/$defs/Node", - "$defs": { - "Node": { - "title": "Node", - "type": "object", - "properties": {"child": {"$ref": "#/$defs/Node"}}, - } - }, - } - schema = component_payload(native)["components"]["schemas"]["Case:Payload"] - assert schema == {**native, "title": "Case:Payload"} - - def test_root_ref_keeps_all_sibling_constraints( - self, component_payload: ComponentGenerator - ) -> None: - native = { - "$ref": "#/$defs/Actual", - "allOf": [{"minLength": 3}], - "$defs": {"Actual": {"type": "string"}}, - } - schema = component_payload(native)["components"]["schemas"]["Case:Payload"] - assert schema["allOf"] == [{"type": "string"}, {"minLength": 3}] - - def test_conflicting_definition_names_fail_clearly( - self, component_payload: ComponentGenerator - ) -> None: - native = { - "title": "Payload", - "properties": { - "text": {"$ref": "#/$defs/Shared"}, - "count": {"$ref": "#/definitions/Shared"}, - }, - "$defs": {"Shared": {"type": "string"}}, - "definitions": {"Shared": {"type": "integer"}}, - } - with pytest.raises( - ValueError, match="Conflicting schema definitions for 'Shared'" - ): - component_payload(native) - - def test_nested_scoped_resource_from_options_aware_backend( - self, specification: SpecificationGenerator - ) -> None: - resource = { - "$id": "https://example.test/record", - "$ref": "#/$defs/Node", - "$defs": { - "Node": { - "title": "Node", - "type": "object", - "properties": {"child": {"$ref": "#/$defs/Node"}}, - } - }, - } - - class ResourceFactory(SerializerProto): - def __call__( - self, *, name: str, options: list[OptionItem], response_type: Any - ) -> Serializer: - class ResourceSerializer(Serializer): - def __call__(self, kwargs: dict[str, Any]) -> dict[str, Any]: - return kwargs - - def get_schema( - self, - *, - embed: bool = False, - exclude: Iterable[SchemaExclude] = (), - resolve_refs: bool = False, - ) -> dict[str, Any]: - schema = { - "type": "object", - "properties": { - p.field_name: deepcopy(resource) for p in options - }, - } - return process_schema( - schema, embed=embed, resolve_refs=resolve_refs - ) - - return ResourceSerializer( - name=name, options=options, response_type=response_type - ) - - broker = RabbitBroker(serializer=ResourceFactory()) - - @broker.subscriber("in") - async def handle(value: Opaque) -> None: ... - - document = specification(broker) - schemas = document["components"]["schemas"] - assert schemas["__fast_depends_input"]["properties"]["value"] == resource - assert ( - schemas["Handle:Message:Payload"]["$ref"] - == "#/components/schemas/__fast_depends_input/properties/value" - ) - assert_local_refs_resolve(document) - - def test_reference_tail_preserves_literal_percent_encoding( - self, component_payload: ComponentGenerator - ) -> None: - native = { - "title": "Payload", - "type": "object", - "properties": {"value": {"$ref": "#/$defs/Container/properties/%252F"}}, - "$defs": { - "Container": {"type": "object", "properties": {"%2F": {"type": "string"}}} - }, - } - document = component_payload(native) - assert document["components"]["schemas"]["Payload"]["properties"]["value"] == { - "$ref": "#/components/schemas/Container/properties/%252F" - } - assert_local_refs_resolve(document) - - def test_input_resource_scope_is_preserved_during_embedding( - self, specification: SpecificationGenerator - ) -> None: - native = { - "$id": "https://example.test/inputs", - "type": "object", - "properties": {"value": {"$ref": "#/$defs/Node"}}, - "$defs": { - "Node": { - "type": "object", - "properties": { - "children": {"type": "array", "items": {"$ref": "#/$defs/Node"}} - }, - } - }, - } - - class ResourceFactory(SerializerProto): - def __call__( - self, *, name: str, options: list[OptionItem], response_type: Any - ) -> Serializer: - class ResourceSerializer(Serializer): - def __call__(self, kwargs: dict[str, Any]) -> dict[str, Any]: - return kwargs - - def get_schema( - self, - *, - embed: bool = False, - exclude: Iterable[SchemaExclude] = (), - resolve_refs: bool = False, - ) -> dict[str, Any]: - return process_schema( - deepcopy(native), embed=embed, resolve_refs=resolve_refs - ) - - return ResourceSerializer( - name=name, options=options, response_type=response_type - ) - - broker = RabbitBroker(serializer=ResourceFactory()) - - @broker.subscriber("in") - async def handle(value: Opaque) -> None: ... - - document = specification(broker) - schemas = document["components"]["schemas"] - assert schemas["__fast_depends_input"] == native - assert ( - schemas["Handle:Message:Payload"]["$ref"] - == "#/components/schemas/__fast_depends_input/properties/value" - ) - assert_local_refs_resolve(document) - - def test_shared_schema_nodes_are_rewritten_once( - self, component_payload: ComponentGenerator - ) -> None: - shared = {"$ref": "#/$defs/Leaf"} - native = { - "title": "Payload", - "type": "object", - "properties": {"first": shared, "second": shared}, - "$defs": {"Leaf": {"type": "string"}}, - } - original = deepcopy(native) - document = component_payload(native) - schema = document["components"]["schemas"]["Payload"] - assert schema["properties"] == { - "first": {"$ref": "#/components/schemas/Leaf"}, - "second": {"$ref": "#/components/schemas/Leaf"}, - } - assert native == original - assert_local_refs_resolve(document) - - def test_shared_nodes_preserve_resource_scope_and_data_literals( - self, component_payload: ComponentGenerator - ) -> None: - shared = {"$ref": "#/$defs/Leaf"} - resource = { - "$id": "https://example.test/local", - "type": "object", - "properties": {"local": shared}, - "$defs": {"Leaf": {"type": "integer"}}, - } - native = { - "title": "Payload", - "type": "object", - "properties": {"global": shared, "scoped": resource}, - "default": shared, - "examples": [shared], - "$defs": {"Leaf": {"type": "string"}}, - } - original = deepcopy(native) - document = component_payload(native) - schema = document["components"]["schemas"]["Payload"] - assert schema["properties"]["global"] == {"$ref": "#/components/schemas/Leaf"} - assert schema["properties"]["scoped"] == resource - assert schema["default"] == {"$ref": "#/$defs/Leaf"} - assert schema["examples"] == [{"$ref": "#/$defs/Leaf"}] - assert native == original - assert_local_refs_resolve(document) From 3415ad7d9b1f501148dd4160d72f8a0f4ab3f4dc Mon Sep 17 00:00:00 2001 From: Tseluiko Aleksandr Date: Mon, 16 Nov 2026 12:14:48 +0300 Subject: [PATCH 6/8] fix: isolate retained AsyncAPI schema definitions --- faststream/specification/asyncapi/message.py | 9 ++- faststream/specification/asyncapi/utils.py | 42 +++++++++--- .../specification/asyncapi/v2_6_0/generate.py | 2 +- tests/asyncapi/base/arguments.py | 68 +++++++++++++++---- tests/asyncapi/base/serialization.py | 11 ++- tests/asyncapi/test_schema_refs.py | 56 +++++++++++++-- 6 files changed, 156 insertions(+), 32 deletions(-) diff --git a/faststream/specification/asyncapi/message.py b/faststream/specification/asyncapi/message.py index 23e79a83e17..19bc9f57f1d 100644 --- a/faststream/specification/asyncapi/message.py +++ b/faststream/specification/asyncapi/message.py @@ -78,7 +78,14 @@ def prepare_payload(schema: dict[str, Any], *, prefix: str) -> dict[str, Any]: reference = body.get("$ref") if isinstance(reference, str) and reference.startswith("#/"): target = _lookup_reference(schema, reference) - if isinstance(target, dict) and target is not schema and "$id" not in target: + path = unquote(reference[2:]).split("/") + retained = len(path) > 2 and path[0] in _DEFINITIONS + if ( + not retained + and isinstance(target, dict) + and target is not schema + and "$id" not in target + ): siblings = {k: v for k, v in body.items() if k != "$ref"} annotations = { "title", diff --git a/faststream/specification/asyncapi/utils.py b/faststream/specification/asyncapi/utils.py index b36c468a3cd..ee1d189caff 100644 --- a/faststream/specification/asyncapi/utils.py +++ b/faststream/specification/asyncapi/utils.py @@ -88,13 +88,15 @@ def move_schema_refs(original: Any, *, root_name: str) -> Any: """Move local definitions to AsyncAPI components without changing data literals.""" data = deepcopy(original) - def rewrite(value: str, root_ref: str) -> str: + def rewrite(value: str, root_ref: str, names: dict[str, str]) -> str: for key in ("$defs", "definitions"): prefix = f"#/{key}/" if value.startswith(prefix): name, *tail = unquote(value[len(prefix) :]).split("/") name = name.replace("~1", "/").replace("~0", "~") - target = ref("components", "schemas", clear_key(name))["$ref"] + target = ref("components", "schemas", clear_key(names.get(name, name)))[ + "$ref" + ] return target + ( "/" + quote("/".join(tail), safe="/~:._-") if tail else "" ) @@ -102,20 +104,35 @@ def rewrite(value: str, root_ref: str) -> str: return root_ref + value[1:] return value - def visit(schema: Any, root_ref: str) -> Any: + def visit( + schema: Any, root_ref: str, names: dict[str, str], namespace: str = "" + ) -> Any: if not isinstance(schema, dict) or "$id" in schema: return schema schema = schema.copy() + # Retained input definitions belong to one payload, unlike shared models. + if namespace and "$ref" in schema: + local_names = { + name: f"{namespace}:{name}" + for key in ("$defs", "definitions") + for name in schema.get(key, {}) + } + names = {**names, **local_names} + for key in ("$defs", "definitions"): + if key in schema: + schema[key] = { + local_names[name]: child for name, child in schema[key].items() + } for key in ("$ref", "$dynamicRef", "$recursiveRef"): if isinstance(value := schema.get(key), str): - schema[key] = rewrite(value, root_ref) + schema[key] = rewrite(value, root_ref, names) discriminator = schema.get("discriminator") if isinstance(discriminator, dict): discriminator = discriminator.copy() schema["discriminator"] = discriminator if isinstance(mapping := discriminator.get("mapping"), dict): discriminator["mapping"] = { - k: rewrite(v, root_ref) if isinstance(v, str) else v + k: rewrite(v, root_ref, names) if isinstance(v, str) else v for k, v in mapping.items() } if "propertyName" in discriminator: @@ -123,7 +140,7 @@ def visit(schema: Any, root_ref: str) -> Any: for key, value in schema.items(): if key in _SCHEMA_MAPS and isinstance(value, dict): schema[key] = { - name: visit(child, root_ref) for name, child in value.items() + name: visit(child, root_ref, names) for name, child in value.items() } elif key == "oneOf" and isinstance(value, dict): # FastStream's overloaded-handler payloads use a named map. @@ -135,17 +152,22 @@ def visit(schema: Any, root_ref: str) -> Any: if not isinstance(child_name, str): child_name = name children[name] = visit( - child, ref("components", "schemas", clear_key(child_name))["$ref"] + child, + ref("components", "schemas", clear_key(child_name))["$ref"], + names, + f"{namespace or root_name}:{child_name}", ) schema[key] = children elif (key in _SCHEMA_LISTS or key == "items") and isinstance(value, list): - schema[key] = [visit(child, root_ref) for child in value] + schema[key] = [visit(child, root_ref, names) for child in value] elif key in _SCHEMA_VALUES: - schema[key] = visit(value, root_ref) + schema[key] = visit(value, root_ref, names) return schema title = data.get("title", root_name) if isinstance(data, dict) else root_name - return visit(data, ref("components", "schemas", clear_key(title))["$ref"]) + return visit( + data, ref("components", "schemas", clear_key(title))["$ref"], {}, root_name + ) def pop_schema_definitions(payload: dict[str, Any]) -> dict[str, Any]: diff --git a/faststream/specification/asyncapi/v2_6_0/generate.py b/faststream/specification/asyncapi/v2_6_0/generate.py index 4e9a703f223..d29550cf519 100644 --- a/faststream/specification/asyncapi/v2_6_0/generate.py +++ b/faststream/specification/asyncapi/v2_6_0/generate.py @@ -273,7 +273,7 @@ def _resolve_msg_payloads( Payloads and messages are editable dicts to store schemas for reference in AsyncAPI. """ one_of_list: list[Reference] = [] - m.payload = move_schema_refs(m.payload, root_name=f"{channel_name}Payload") + m.payload = move_schema_refs(m.payload, root_name=f"{channel_name}:{m.title}:Payload") payloads.update(pop_schema_definitions(m.payload)) diff --git a/tests/asyncapi/base/arguments.py b/tests/asyncapi/base/arguments.py index b9c5916eb10..ea62bd7d88c 100644 --- a/tests/asyncapi/base/arguments.py +++ b/tests/asyncapi/base/arguments.py @@ -1,4 +1,4 @@ -from collections.abc import Iterable +from collections.abc import Callable, Iterable from copy import deepcopy from typing import Annotated, Any, Literal @@ -20,6 +20,7 @@ Tree, assert_local_refs_resolve, assert_msgspec_payload, + resolve_local_ref, ) @@ -55,9 +56,54 @@ async def handle( schema = self.get_spec(broker).to_jsonable()["components"]["schemas"][ "Handle:Message:Payload" ] - assert schema["properties"]["size"] == {"type": "integer", "minimum": 1} - assert schema["properties"]["label"] == {"enum": ["a", "b"], "default": "a"} - assert schema["required"] == ["size"] + assert schema == IsPartialDict({ + "properties": { + "size": {"type": "integer", "minimum": 1}, + "label": {"enum": ["a", "b"], "default": "a"}, + }, + "required": ["size"], + }) + + @pytest.mark.parametrize( + ("factory", "metadata"), + ( + pytest.param( + PydanticSerializer, + lambda uri: Field(json_schema_extra={"$id": uri}), + id="pydantic", + ), + pytest.param( + MsgSpecSerializer, + lambda uri: msgspec.Meta(extra_json_schema={"$id": uri}), + id="msgspec", + ), + ), + ) + def test_payload_resources_remain_separate( + self, factory: type[SerializerProto], metadata: Callable[[str], Any] + ) -> None: + broker = self.broker_class(serializer=factory()) + + @broker.subscriber("first") + async def first( + value: Annotated[int, metadata("https://example.test/A")], + ) -> None: ... + + @broker.subscriber("second") + async def second( + value: Annotated[str, metadata("https://example.test/B")], + ) -> None: ... + + document = self.get_spec(broker).to_jsonable() + schemas = document["components"]["schemas"] + assert [ + resolve_local_ref(document, schemas[f"{name}:Message:Payload"]["$ref"]) + for name in ("First", "Second") + ] == [ + IsPartialDict({"$id": "https://example.test/A", "type": "integer"}), + IsPartialDict({"$id": "https://example.test/B", "type": "string"}), + ] + assert_local_refs_resolve(document) def test_selected_factory_configuration(self) -> None: broker = self.broker_class( @@ -201,10 +247,9 @@ async def handle(value: Opaque) -> None: ... document = self.get_spec(broker).to_jsonable() schemas = document["components"]["schemas"] - assert schemas["__fast_depends_input"]["properties"]["value"] == resource assert ( - schemas["Handle:Message:Payload"]["$ref"] - == "#/components/schemas/__fast_depends_input/properties/value" + resolve_local_ref(document, schemas["Handle:Message:Payload"]["$ref"]) + == resource ) assert_local_refs_resolve(document) @@ -253,11 +298,10 @@ async def handle(value: Opaque) -> None: ... document = self.get_spec(broker).to_jsonable() schemas = document["components"]["schemas"] - assert schemas["__fast_depends_input"] == native - assert ( - schemas["Handle:Message:Payload"]["$ref"] - == "#/components/schemas/__fast_depends_input/properties/value" - ) + assert resolve_local_ref(document, schemas["Handle:Message:Payload"]["$ref"]) == { + "$ref": "#/$defs/Node" + } + assert native in schemas.values() assert_local_refs_resolve(document) def test_dependency_override_changes_body_schema(self) -> None: diff --git a/tests/asyncapi/base/serialization.py b/tests/asyncapi/base/serialization.py index a27c2b0675a..6bcac39954c 100644 --- a/tests/asyncapi/base/serialization.py +++ b/tests/asyncapi/base/serialization.py @@ -21,6 +21,13 @@ class Opaque: pass +def resolve_local_ref(document: dict[str, Any], reference: str) -> dict[str, Any]: + target = document + for token in unquote(reference[2:]).split("/"): + target = target[token.replace("~1", "/").replace("~0", "~")] + return target + + def assert_local_refs_resolve(document: dict[str, Any]) -> None: def visit(value: Any) -> None: if isinstance(value, dict): @@ -29,9 +36,7 @@ def visit(value: Any) -> None: if isinstance(reference := value.get("$ref"), str) and reference.startswith( "#/" ): - target = document - for token in unquote(reference[2:]).split("/"): - target = target[token.replace("~1", "/").replace("~0", "~")] + resolve_local_ref(document, reference) for key, child in value.items(): if key not in {"default", "examples", "enum", "const"}: visit(child) diff --git a/tests/asyncapi/test_schema_refs.py b/tests/asyncapi/test_schema_refs.py index 975c54bebcb..9085e660396 100644 --- a/tests/asyncapi/test_schema_refs.py +++ b/tests/asyncapi/test_schema_refs.py @@ -4,9 +4,11 @@ from typing import Any, TypeAlias import pytest +from dirty_equals import IsPartialDict +from fast_depends.library.schema_processing import process_schema from faststream.specification.asyncapi.message import prepare_payload -from tests.asyncapi.base.serialization import assert_local_refs_resolve +from tests.asyncapi.base.serialization import assert_local_refs_resolve, resolve_local_ref ComponentGenerator: TypeAlias = Callable[[dict[str, Any]], dict[str, Any]] @@ -42,6 +44,46 @@ def generate(native: dict[str, Any]) -> dict[str, Any]: class TestSchemaReferences: + def test_overloaded_payloads_keep_separate_definitions( + self, component_payload: ComponentGenerator + ) -> None: + native = { + "oneOf": { + f"{name}:Payload": prepare_payload( + process_schema( + { + "type": "object", + "additionalProperties": {"type": field_type}, + "properties": { + "value": { + "type": field_type, + "allOf": [{"$ref": "#/additionalProperties"}], + } + }, + }, + embed=True, + ), + prefix=name, + ) + for name, field_type in (("First", "integer"), ("Second", "string")) + }, + } + document = component_payload(native) + schemas = document["components"]["schemas"] + selected = [schemas[f"{name}:Payload"] for name in ("First", "Second")] + selected = [ + resolve_local_ref(document, value["$ref"]) if "$ref" in value else value + for value in selected + ] + assert [ + ( + value["type"], + resolve_local_ref(document, value["allOf"][0]["$ref"])["type"], + ) + for value in selected + ] == [("integer", "integer"), ("string", "string")] + assert_local_refs_resolve(document) + def test_root_pointer_ref_is_rebased( self, component_payload: ComponentGenerator ) -> None: @@ -179,9 +221,13 @@ def test_shared_nodes_preserve_resource_scope_and_data_literals( original = deepcopy(native) document = component_payload(native) schema = document["components"]["schemas"]["Payload"] - assert schema["properties"]["global"] == {"$ref": "#/components/schemas/Leaf"} - assert schema["properties"]["scoped"] == resource - assert schema["default"] == {"$ref": "#/$defs/Leaf"} - assert schema["examples"] == [{"$ref": "#/$defs/Leaf"}] + assert schema == IsPartialDict({ + "properties": { + "global": {"$ref": "#/components/schemas/Leaf"}, + "scoped": resource, + }, + "default": {"$ref": "#/$defs/Leaf"}, + "examples": [{"$ref": "#/$defs/Leaf"}], + }) assert native == original assert_local_refs_resolve(document) From b4656d05f1452860f0b5c49719f782ff419b1a41 Mon Sep 17 00:00:00 2001 From: Tseluiko Aleksandr Date: Mon, 23 Nov 2026 20:33:55 +0300 Subject: [PATCH 7/8] fix: preserve AsyncAPI schema definitions and union constraints --- faststream/specification/asyncapi/utils.py | 137 +++++++++++++----- .../specification/asyncapi/v2_6_0/generate.py | 14 +- .../specification/asyncapi/v3_0_0/generate.py | 2 +- tests/asyncapi/base/arguments.py | 79 ++++++++++ tests/asyncapi/base/v2_6_0/arguments.py | 17 ++- tests/asyncapi/base/v3_0_0/arguments.py | 2 + tests/asyncapi/test_schema_refs.py | 42 +++++- 7 files changed, 232 insertions(+), 61 deletions(-) diff --git a/faststream/specification/asyncapi/utils.py b/faststream/specification/asyncapi/utils.py index ee1d189caff..231e5ac7b99 100644 --- a/faststream/specification/asyncapi/utils.py +++ b/faststream/specification/asyncapi/utils.py @@ -1,3 +1,5 @@ +from collections import ChainMap +from collections.abc import Callable from copy import deepcopy from typing import Any from urllib.parse import quote, unquote @@ -84,39 +86,66 @@ def _encode_json_pointer_part(part: str) -> str: } -def move_schema_refs(original: Any, *, root_name: str) -> Any: +def _rewrite_schema_ref(value: str, root_ref: str, names: dict[str, str]) -> str: + for key in ("$defs", "definitions"): + prefix = f"#/{key}/" + if value.startswith(prefix): + name, *tail = unquote(value[len(prefix) :]).split("/") + name = name.replace("~1", "/").replace("~0", "~") + target = ref("components", "schemas", clear_key(names.get(name, name)))[ + "$ref" + ] + return target + ("/" + quote("/".join(tail), safe="/~:._-") if tail else "") + if value == "#" or value.startswith("#/"): + return root_ref + value[1:] + return value + + +def move_schema_refs(original: Any, *, root_name: str, components: dict[str, Any]) -> Any: """Move local definitions to AsyncAPI components without changing data literals.""" data = deepcopy(original) - - def rewrite(value: str, root_ref: str, names: dict[str, str]) -> str: - for key in ("$defs", "definitions"): - prefix = f"#/{key}/" - if value.startswith(prefix): - name, *tail = unquote(value[len(prefix) :]).split("/") - name = name.replace("~1", "/").replace("~0", "~") - target = ref("components", "schemas", clear_key(names.get(name, name)))[ - "$ref" - ] - return target + ( - "/" + quote("/".join(tail), safe="/~:._-") if tail else "" - ) - if value == "#" or value.startswith("#/"): - return root_ref + value[1:] - return value + known: ChainMap[str, Any] = ChainMap({}, components) def visit( - schema: Any, root_ref: str, names: dict[str, str], namespace: str = "" + schema: Any, + root_ref: str, + names: dict[str, str], + namespace: str = "", + *, + register: bool = True, ) -> Any: if not isinstance(schema, dict) or "$id" in schema: return schema schema = schema.copy() - # Retained input definitions belong to one payload, unlike shared models. - if namespace and "$ref" in schema: - local_names = { - name: f"{namespace}:{name}" + if namespace and register: + definitions = { + name: child for key in ("$defs", "definitions") - for name in schema.get(key, {}) + for name, child in schema.get(key, {}).items() + } + local_names = { + name: f"{namespace}:{name}" if "$ref" in schema else name + for name in definitions } + index = 0 + while definitions: + current_names = {**names, **local_names} + candidates = { + clear_key(local_names[name]): visit( + child, root_ref, current_names, register=False + ) + for name, child in definitions.items() + if clear_key(local_names[name]) in known + } + if not any( + name in known and known[name] != child + for name, child in candidates.items() + ): + break + # Rename the whole bundle so dependent definitions stay together. + index += 1 + prefix = namespace if index == 1 else f"{namespace}:{index}" + local_names = {name: f"{prefix}:{name}" for name in definitions} names = {**names, **local_names} for key in ("$defs", "definitions"): if key in schema: @@ -125,22 +154,19 @@ def visit( } for key in ("$ref", "$dynamicRef", "$recursiveRef"): if isinstance(value := schema.get(key), str): - schema[key] = rewrite(value, root_ref, names) + schema[key] = _rewrite_schema_ref(value, root_ref, names) discriminator = schema.get("discriminator") if isinstance(discriminator, dict): - discriminator = discriminator.copy() - schema["discriminator"] = discriminator - if isinstance(mapping := discriminator.get("mapping"), dict): - discriminator["mapping"] = { - k: rewrite(v, root_ref, names) if isinstance(v, str) else v - for k, v in mapping.items() - } - if "propertyName" in discriminator: - schema["discriminator"] = discriminator["propertyName"] + _convert_discriminator( + schema, + discriminator, + lambda value: _rewrite_schema_ref(value, root_ref, names), + ) for key, value in schema.items(): if key in _SCHEMA_MAPS and isinstance(value, dict): schema[key] = { - name: visit(child, root_ref, names) for name, child in value.items() + name: visit(child, root_ref, names, register=register) + for name, child in value.items() } elif key == "oneOf" and isinstance(value, dict): # FastStream's overloaded-handler payloads use a named map. @@ -156,18 +182,51 @@ def visit( ref("components", "schemas", clear_key(child_name))["$ref"], names, f"{namespace or root_name}:{child_name}", + register=register, ) schema[key] = children elif (key in _SCHEMA_LISTS or key == "items") and isinstance(value, list): - schema[key] = [visit(child, root_ref, names) for child in value] + schema[key] = [ + visit(child, root_ref, names, register=register) for child in value + ] elif key in _SCHEMA_VALUES: - schema[key] = visit(value, root_ref, names) + schema[key] = visit(value, root_ref, names, register=register) + if namespace and register: + for key in ("$defs", "definitions"): + known.update({ + clear_key(name): child for name, child in schema.get(key, {}).items() + }) return schema title = data.get("title", root_name) if isinstance(data, dict) else root_name - return visit( - data, ref("components", "schemas", clear_key(title))["$ref"], {}, root_name - ) + try: + return visit( + data, ref("components", "schemas", clear_key(title))["$ref"], {}, root_name + ) + finally: + # Avoid retaining the component registry until cyclic garbage collection. + known.maps = [{}] + + +def _convert_discriminator( + schema: dict[str, Any], + original: dict[str, Any], + rewrite: Callable[[str], str], +) -> None: + discriminator = original.copy() + schema["discriminator"] = discriminator + if isinstance(mapping := discriminator.get("mapping"), dict): + discriminator["mapping"] = { + key: rewrite(value) if isinstance(value, str) else value + for key, value in mapping.items() + } + if "propertyName" in discriminator: + name = discriminator["propertyName"] + schema["discriminator"] = name + schema["properties"] = {name: {}, **schema.get("properties", {})} + required = schema.get("required", []) + if name not in required: + schema["required"] = [*required, name] def pop_schema_definitions(payload: dict[str, Any]) -> dict[str, Any]: diff --git a/faststream/specification/asyncapi/v2_6_0/generate.py b/faststream/specification/asyncapi/v2_6_0/generate.py index d29550cf519..03813a7352f 100644 --- a/faststream/specification/asyncapi/v2_6_0/generate.py +++ b/faststream/specification/asyncapi/v2_6_0/generate.py @@ -273,7 +273,9 @@ def _resolve_msg_payloads( Payloads and messages are editable dicts to store schemas for reference in AsyncAPI. """ one_of_list: list[Reference] = [] - m.payload = move_schema_refs(m.payload, root_name=f"{channel_name}:{m.title}:Payload") + m.payload = move_schema_refs( + m.payload, root_name=f"{channel_name}:{m.title}:Payload", components=payloads + ) payloads.update(pop_schema_definitions(m.payload)) @@ -290,16 +292,6 @@ def _resolve_msg_payloads( Reference(**ref("components", "schemas", formatted_payload_title)), ) - elif one_of is not None: - # Discriminator case - for p in one_of: - p_value = next(iter(p.values())) - p_title = p_value.split("/")[-1] - p_title = clear_key(p_title) - if p_title not in payloads: - payloads[p_title] = p - one_of_list.append(Reference(**ref("components", "schemas", p_title))) - if not one_of_list: p_title = m.payload.get("title", f"{channel_name}Payload") p_title = clear_key(p_title) diff --git a/faststream/specification/asyncapi/v3_0_0/generate.py b/faststream/specification/asyncapi/v3_0_0/generate.py index dd24a6893c3..37e959caad7 100644 --- a/faststream/specification/asyncapi/v3_0_0/generate.py +++ b/faststream/specification/asyncapi/v3_0_0/generate.py @@ -336,7 +336,7 @@ def _resolve_msg_payloads( assert isinstance(m.payload, dict) m.payload = move_schema_refs( - m.payload, root_name=f"{channel_name}:{message_name}:Payload" + m.payload, root_name=f"{channel_name}:{message_name}:Payload", components=payloads ) message_name = clear_key(message_name) diff --git a/tests/asyncapi/base/arguments.py b/tests/asyncapi/base/arguments.py index ea62bd7d88c..35d7835e751 100644 --- a/tests/asyncapi/base/arguments.py +++ b/tests/asyncapi/base/arguments.py @@ -44,6 +44,85 @@ async def handle(value: annotation) -> None: ... document = self.get_spec(broker).to_jsonable() assert_msgspec_payload(document, annotation) + def test_msgspec_same_name_models_keep_distinct_schemas(self) -> None: + """https://github.com/ag2ai/faststream/pull/3334#pullrequestreview-6020282539.""" + + class First: + class Record(msgspec.Struct): + left_id: int + + class Second: + class Record(msgspec.Struct): + right_id: str + + broker = self.broker_class(serializer=MsgSpecSerializer()) + + @broker.subscriber("first") + async def first(value: list[First.Record]) -> None: ... + + @broker.subscriber("second") + async def second(value: list[Second.Record]) -> None: ... + + document = self.get_spec(broker).to_jsonable() + schemas = document["components"]["schemas"] + assert [ + resolve_local_ref(document, schemas[name]["items"]["$ref"]) + for name in ("First:Message:Payload", "Second:Message:Payload") + ] == [ + IsPartialDict({"properties": {"left_id": {"type": "integer"}}}), + IsPartialDict({"properties": {"right_id": {"type": "string"}}}), + ] + assert_local_refs_resolve(document) + + def test_msgspec_one_of_constraints(self) -> None: + """https://github.com/ag2ai/faststream/pull/3334#pullrequestreview-6020282539.""" + broker = self.broker_class(serializer=MsgSpecSerializer()) + + @broker.subscriber("in") + async def handle( + value: Annotated[ + int, + msgspec.Meta( + extra_json_schema={"oneOf": [{"minimum": 1}, {"maximum": -1}]} + ), + ], + ) -> None: ... + + document = self.get_spec(broker).to_jsonable() + assert document["components"]["schemas"][ + "Handle:Message:Payload" + ] == IsPartialDict({ + "type": "integer", + "oneOf": [{"minimum": 1}, {"maximum": -1}], + }) + + def test_msgspec_discriminator_is_declared_on_union(self) -> None: + """https://github.com/ag2ai/faststream/pull/3334#pullrequestreview-6020282539.""" + + class Created(msgspec.Struct, tag=True): + id: int + + class Removed(msgspec.Struct, tag=True): + reason: str + + broker = self.broker_class(serializer=MsgSpecSerializer()) + + @broker.subscriber("in") + async def handle(value: Created | Removed) -> None: ... + + document = self.get_spec(broker).to_jsonable() + assert document["components"]["schemas"][ + "Handle:Message:Payload" + ] == IsPartialDict({ + "discriminator": "type", + "properties": {"type": {}}, + "required": ["type"], + "anyOf": [ + {"$ref": "#/components/schemas/Created"}, + {"$ref": "#/components/schemas/Removed"}, + ], + }) + def test_msgspec_field_alias_and_constraint(self) -> None: broker = self.broker_class(serializer=MsgSpecSerializer()) diff --git a/tests/asyncapi/base/v2_6_0/arguments.py b/tests/asyncapi/base/v2_6_0/arguments.py index 293cc3d349a..ee11ff8c1ec 100644 --- a/tests/asyncapi/base/v2_6_0/arguments.py +++ b/tests/asyncapi/base/v2_6_0/arguments.py @@ -624,23 +624,22 @@ async def handle( "title": "Handle:Message:Payload", }) - fastapi_payload = schema["components"]["schemas"].get("Handle:Message:Payload") if self.is_fastapi: - if fastapi_payload: - assert fastapi_payload == IsPartialDict({ + expected_schema = ( + IsPartialDict({ "anyOf": [ {"$ref": "#/components/schemas/Sub2"}, {"$ref": "#/components/schemas/Sub"}, ], }) - - expected_schema = ( - IsPartialDict({"$ref": "#/components/schemas/Handle:Message:Payload"}) | expected_schema ) - assert schema["components"]["messages"][key]["payload"] == expected_schema, ( - schema["components"] + assert schema["components"]["messages"][key]["payload"] == { + "$ref": "#/components/schemas/Handle:Message:Payload" + } + assert ( + schema["components"]["schemas"]["Handle:Message:Payload"] == expected_schema ) assert schema["components"]["schemas"] == IsPartialDict({ @@ -709,6 +708,8 @@ async def handle(user: Model) -> None: ... "properties": { "msg": { "discriminator": "type", + "properties": {"type": {}}, + "required": ["type"], "oneOf": [ {"$ref": "#/components/schemas/Sub2"}, {"$ref": "#/components/schemas/Sub"}, diff --git a/tests/asyncapi/base/v3_0_0/arguments.py b/tests/asyncapi/base/v3_0_0/arguments.py index 3fe4bccca1d..0f978b19786 100644 --- a/tests/asyncapi/base/v3_0_0/arguments.py +++ b/tests/asyncapi/base/v3_0_0/arguments.py @@ -702,6 +702,8 @@ async def handle(user: Model) -> None: ... "properties": { "msg": { "discriminator": "type", + "properties": {"type": {}}, + "required": ["type"], "oneOf": [ {"$ref": "#/components/schemas/Sub2"}, {"$ref": "#/components/schemas/Sub"}, diff --git a/tests/asyncapi/test_schema_refs.py b/tests/asyncapi/test_schema_refs.py index 9085e660396..8a70bf8e8b4 100644 --- a/tests/asyncapi/test_schema_refs.py +++ b/tests/asyncapi/test_schema_refs.py @@ -23,9 +23,10 @@ def component_payload(request: pytest.FixtureRequest) -> ComponentGenerator: module = import_module(f"faststream.specification.asyncapi.{request.param}.generate") + schemas: dict[str, Any] = {} + messages: dict[str, Any] = {} + def generate(native: dict[str, Any]) -> dict[str, Any]: - schemas: dict[str, Any] = {} - messages: dict[str, Any] = {} message = module.Message( title="Message", payload=prepare_payload(native, prefix="Case") ) @@ -44,6 +45,43 @@ def generate(native: dict[str, Any]) -> dict[str, Any]: class TestSchemaReferences: + def test_colliding_bundles_keep_internal_references( + self, component_payload: ComponentGenerator + ) -> None: + """https://github.com/ag2ai/faststream/pull/3334#pullrequestreview-6020282539.""" + documents = [ + component_payload({ + "title": title, + "type": "array", + "items": {"$ref": "#/$defs/Container"}, + "$defs": { + "Container": { + "properties": {"record": {"$ref": "#/$defs/Record"}}, + }, + "Record": { + "properties": { + "value": {"type": field_type}, + "child": {"$ref": "#/$defs/Record"}, + }, + }, + }, + }) + for title, field_type in (("First", "integer"), ("Second", "string")) + ] + document = documents[-1] + schemas = document["components"]["schemas"] + records = [ + resolve_local_ref(document, schemas[title]["items"]["$ref"])["properties"][ + "record" + ]["$ref"] + for title in ("First", "Second") + ] + assert [resolve_local_ref(document, reference) for reference in records] == [ + {"properties": {"value": {"type": "integer"}, "child": {"$ref": records[0]}}}, + {"properties": {"value": {"type": "string"}, "child": {"$ref": records[1]}}}, + ] + assert_local_refs_resolve(document) + def test_overloaded_payloads_keep_separate_definitions( self, component_payload: ComponentGenerator ) -> None: From aac0b089c171d4a23ac3900893158ba9dfcbe4a4 Mon Sep 17 00:00:00 2001 From: Tseluiko Aleksandr Date: Thu, 26 Nov 2026 13:05:12 +0300 Subject: [PATCH 8/8] test: fix Redis security transport mocks --- tests/docs/redis/test_security.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/docs/redis/test_security.py b/tests/docs/redis/test_security.py index 99dbc510b3c..b36e91cf430 100644 --- a/tests/docs/redis/test_security.py +++ b/tests/docs/redis/test_security.py @@ -15,6 +15,7 @@ def patch_asyncio_open_connection() -> Generator[AsyncMock, None, None]: reader.read = AsyncMock(return_value=b"") writer = MagicMock() + writer.transport.is_closing.return_value = False writer.drain = AsyncMock() writer.wait_closed = AsyncMock() @@ -31,6 +32,8 @@ async def test_base_security() -> None: with patch_asyncio_open_connection() as connection: from docs.docs_src.redis.security.basic import broker + broker.config.broker_config.connection._options["protocol"] = 2 + async with broker: await broker.ping(0.01)