Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions litestar/plugins/core/_msgspec.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,17 @@ def kwarg_definition_from_field(field: msgspec.inspect.Field) -> tuple[Parameter
kwargs["max_length"] = field_type.max_length
if isinstance(field_type, msgspec.inspect.StrType):
kwargs["pattern"] = field_type.pattern
elif isinstance(
field_type,
(
msgspec.inspect.ListType,
msgspec.inspect.SetType,
msgspec.inspect.FrozenSetType,
msgspec.inspect.VarTupleType,
),
):
kwargs["min_items"] = field_type.min_length
kwargs["max_items"] = field_type.max_length

parameter_defaults = {
f.name: default for f in dataclasses.fields(ParameterKwarg) if (default := f.default) is not dataclasses.MISSING
Expand Down
9 changes: 8 additions & 1 deletion tests/unit/test_openapi/test_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,13 +294,17 @@ class Foo(TypedDict):


def test_create_schema_from_msgspec_annotated_type() -> None:
from uuid import UUID

class Lookup(msgspec.Struct):
int_field: Annotated[int, msgspec.Meta(gt=0)]
str_field: Annotated[
str,
msgspec.Meta(max_length=16, examples=["example"], description="description", title="title", pattern=r"\w+"),
]
bytes_field: Annotated[bytes, msgspec.Meta(max_length=2, min_length=1)]
list_field: Annotated[list[UUID], msgspec.Meta(min_length=1, max_length=10)]
set_field: Annotated[set[int], msgspec.Meta(min_length=2)]
default_field: Annotated[str, msgspec.Meta(min_length=1)] = "a"

schema = get_schema_for_field_definition(FieldDefinition.from_kwarg(name="Lookup", annotation=Lookup))
Expand All @@ -312,13 +316,16 @@ class Lookup(msgspec.Struct):
assert schema.properties["str_field"].description == "description" # type: ignore[index]
assert schema.properties["str_field"].title == "title" # type: ignore[index, union-attr]
assert schema.properties["str_field"].max_length == 16 # type: ignore[index, union-attr]
assert sorted(schema.required) == sorted(["int_field", "str_field", "bytes_field"]) # type: ignore[arg-type]
assert sorted(schema.required) == sorted(["int_field", "str_field", "bytes_field", "list_field", "set_field"]) # type: ignore[arg-type]
assert schema.properties["bytes_field"].to_schema() == { # type: ignore[index]
"contentEncoding": "utf-8",
"maxLength": 2,
"minLength": 1,
"type": "string",
}
assert schema.properties["list_field"].min_items == 1 # type: ignore[index, union-attr]
assert schema.properties["list_field"].max_items == 10 # type: ignore[index, union-attr]
assert schema.properties["set_field"].min_items == 2 # type: ignore[index, union-attr]


def test_annotated_types() -> None:
Expand Down