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..19bc9f57f1d 100644 --- a/faststream/specification/asyncapi/message.py +++ b/faststream/specification/asyncapi/message.py @@ -1,166 +1,159 @@ -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, - ) - - -@overload -def get_model_schema( - call: None, - prefix: str = "", - exclude: Sequence[str] = (), -) -> None: ... + factory = call.serializer_cls + if factory is None: + msg = "AsyncAPI requires a serializer with JSON Schema support." + raise SetupError(msg) + return _payload_schema(factory, list(binding.params), prefix) -@overload -def get_model_schema( - call: type[BaseModel], +def payload_schema( + factory: "SerializerProto", + annotation: Any, prefix: str = "", - exclude: Sequence[str] = (), -) -> dict[str, Any]: ... - - -def get_model_schema( - call: type[BaseModel] | None, - 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.""" + 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=options, + response_type=Parameter.empty, ) + single = options[0] if len(options) == 1 else None + 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 -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 - if ( - param is not None - and param.annotation - and isclass(param.annotation) - and issubclass(param.annotation, BaseModel) # NOTE: 3.7-3.10 compatibility - ): - 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") +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) + 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", + "description", + "default", + "examples", + "deprecated", + "readOnly", + "writeOnly", + } + if siblings.keys() - annotations: + body = { + **siblings, + "allOf": [deepcopy(target), *siblings.get("allOf", [])], } - return ref_obj - param_body[DEF_KEY] = defs + 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 - original_title = param.title if PYDANTIC_V2 else param.field_info.title - if original_title: - use_original_model = True - param_body["title"] = original_title +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: - param_body["title"] = name - - body = param_body - - if not use_original_model: - body["title"] = f"{prefix}:Payload" - - return body + 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..231e5ac7b99 100644 --- a/faststream/specification/asyncapi/utils.py +++ b/faststream/specification/asyncapi/utils.py @@ -1,5 +1,8 @@ +from collections import ChainMap +from collections.abc import Callable +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 +61,183 @@ 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) - - if ( - isinstance(desciminator := data.get("discriminator"), dict) - and "propertyName" in desciminator - ): - data["discriminator"] = desciminator["propertyName"] - - return data +_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 _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) + known: ChainMap[str, Any] = ChainMap({}, components) + + def visit( + 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() + if namespace and register: + definitions = { + name: child + for key in ("$defs", "definitions") + 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: + 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_schema_ref(value, root_ref, names) + discriminator = schema.get("discriminator") + if isinstance(discriminator, dict): + _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, register=register) + 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 + children[name] = visit( + child, + 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, register=register) for child in value + ] + elif key in _SCHEMA_VALUES: + 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 + 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]: + 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..03813a7352f 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,11 @@ 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}:{m.title}:Payload", components=payloads + ) - 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,29 +285,14 @@ 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 {} - 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( 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: - payloads.update(m.payload.pop(DEF_KEY, {})) 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..37e959caad7 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", components=payloads + ) 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,10 +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 {} - for def_name, def_schema in defs.items(): - payloads[clear_key(def_name)] = def_schema + if isinstance(payload, dict): + payloads.update(pop_schema_definitions(payload)) processed_payloads[clear_key(name)] = payload one_of_list.append(Reference(**ref("components", "schemas", name))) @@ -361,7 +364,6 @@ def _resolve_msg_payloads( **ref("components", "messages", f"{channel_name}:{message_name}"), ) - payloads.update(m.payload.pop(DEF_KEY, {})) 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 8c7aebec087..8ea77e8f936 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,12 +52,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/base/arguments.py b/tests/asyncapi/base/arguments.py new file mode 100644 index 00000000000..35d7835e751 --- /dev/null +++ b/tests/asyncapi/base/arguments.py @@ -0,0 +1,401 @@ +from collections.abc import Callable, 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, + resolve_local_ref, +) + + +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_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()) + + @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 == 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( + 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 ( + resolve_local_ref(document, schemas["Handle:Message:Payload"]["$ref"]) + == resource + ) + 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 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: + 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..6bcac39954c --- /dev/null +++ b/tests/asyncapi/base/serialization.py @@ -0,0 +1,114 @@ +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 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): + if "$id" in value: + return + if isinstance(reference := value.get("$ref"), str) and reference.startswith( + "#/" + ): + resolve_local_ref(document, reference) + 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/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/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..8a70bf8e8b4 --- /dev/null +++ b/tests/asyncapi/test_schema_refs.py @@ -0,0 +1,271 @@ +from collections.abc import Callable +from copy import deepcopy +from importlib import import_module +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, resolve_local_ref + +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") + + schemas: dict[str, Any] = {} + messages: dict[str, Any] = {} + + def generate(native: dict[str, Any]) -> 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_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: + 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: + 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 == 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) 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) 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"] 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" },