1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
|
import sys
from dataclasses import dataclass
from datetime import date, datetime, timezone
from enum import Enum, auto
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generic,
List,
Literal,
Optional,
Tuple,
TypedDict,
TypeVar,
Union, # pyright: ignore
)
import annotated_types
import msgspec
import pytest
from msgspec import Struct
from typing_extensions import Annotated, TypeAlias, TypeAliasType
from litestar import Controller, MediaType, get, post
from litestar._openapi.schema_generation.plugins import openapi_schema_plugins
from litestar._openapi.schema_generation.schema import (
KWARG_DEFINITION_ATTRIBUTE_TO_OPENAPI_PROPERTY_MAP,
SchemaCreator,
)
from litestar.app import DEFAULT_OPENAPI_CONFIG, Litestar
from litestar.di import Provide
from litestar.enums import ParamType
from litestar.exceptions import ImproperlyConfiguredException
from litestar.openapi.spec import ExternalDocumentation, OpenAPIType, Reference
from litestar.openapi.spec.example import Example
from litestar.openapi.spec.parameter import Parameter as OpenAPIParameter
from litestar.openapi.spec.schema import Schema
from litestar.pagination import ClassicPagination, CursorPagination, OffsetPagination
from litestar.params import KwargDefinition, Parameter, ParameterKwarg
from litestar.testing import create_test_client
from litestar.typing import FieldDefinition
from litestar.utils.helpers import get_name
from tests.helpers import get_schema_for_field_definition
from tests.models import DataclassPerson, DataclassPet
if TYPE_CHECKING:
from types import ModuleType
from typing import Callable
T = TypeVar("T")
def test_process_schema_result() -> None:
test_str = "abc"
kwarg_definition = ParameterKwarg(
examples=[Example(value=1)],
external_docs=ExternalDocumentation(url="https://example.com/docs"),
content_encoding="utf-8",
default=test_str,
title=test_str,
description=test_str,
const=True,
gt=1,
ge=1,
lt=1,
le=1,
multiple_of=1,
min_items=1,
max_items=1,
min_length=1,
max_length=1,
pattern="^[a-z]$",
)
schema = get_schema_for_field_definition(
FieldDefinition.from_annotation(annotation=str, kwarg_definition=kwarg_definition)
)
assert schema.title
assert schema.const == test_str
assert kwarg_definition.examples
for signature_key, schema_key in KWARG_DEFINITION_ATTRIBUTE_TO_OPENAPI_PROPERTY_MAP.items():
if schema_key == "examples":
assert schema.examples == [kwarg_definition.examples[0].value]
else:
assert getattr(schema, schema_key) == getattr(kwarg_definition, signature_key)
def test_override_schema_component_key() -> None:
@dataclass
class Data:
pass
@post("/")
def handler(
data: Data,
) -> Annotated[Data, Parameter(schema_component_key="not_data")]:
return Data()
@get("/")
def handler_2() -> Annotated[Data, Parameter(schema_component_key="not_data")]:
return Data()
app = Litestar([handler, handler_2])
schema = app.openapi_schema.to_schema()
# we expect the annotated / non-annotated to generate independent components
assert schema["paths"]["/"]["post"]["requestBody"]["content"]["application/json"] == {
"schema": {"$ref": "#/components/schemas/test_override_schema_component_key.Data"}
}
assert schema["paths"]["/"]["post"]["responses"]["201"]["content"] == {
"application/json": {"schema": {"$ref": "#/components/schemas/not_data"}}
}
# a response with the same type and the same name should reference the same component
assert schema["paths"]["/"]["get"]["responses"]["200"]["content"] == {
"application/json": {"schema": {"$ref": "#/components/schemas/not_data"}}
}
assert app.openapi_schema.to_schema()["components"] == {
"schemas": {
"not_data": {"properties": {}, "type": "object", "required": [], "title": "Data"},
"test_override_schema_component_key.Data": {
"properties": {},
"type": "object",
"required": [],
"title": "Data",
},
}
}
def test_override_schema_component_key_raise_if_keys_are_not_unique() -> None:
@dataclass
class Data:
pass
@dataclass
class Data2:
pass
@post("/")
def handler(
data: Data,
) -> Annotated[Data, Parameter(schema_component_key="not_data")]:
return Data()
@get("/")
def handler_2() -> Annotated[Data2, Parameter(schema_component_key="not_data")]:
return Data2()
with pytest.raises(ImproperlyConfiguredException, match="Schema component keys must be unique"):
Litestar([handler, handler_2]).openapi_schema.to_schema()
def test_dependency_schema_generation() -> None:
async def top_dependency(query_param: int) -> int:
return query_param
async def mid_level_dependency(header_param: str = Parameter(header="header_param", required=False)) -> int:
return 5
async def local_dependency(path_param: int, mid_level: int, top_level: int) -> int:
return path_param + mid_level + top_level
class MyController(Controller):
path = "/test"
dependencies = {"mid_level": Provide(mid_level_dependency)}
@get(
path="/{path_param:int}",
dependencies={
"summed": Provide(local_dependency),
},
media_type=MediaType.TEXT,
)
def test_function(self, summed: int, handler_param: int) -> str:
return str(summed)
with create_test_client(
MyController,
dependencies={"top_level": Provide(top_dependency)},
openapi_config=DEFAULT_OPENAPI_CONFIG,
) as client:
handler = client.app.openapi_schema.paths["/test/{path_param}"]
data = {param.name: {"in": param.param_in, "required": param.required} for param in handler.get.parameters}
assert data == {
"path_param": {"in": ParamType.PATH, "required": True},
"header_param": {"in": ParamType.HEADER, "required": False},
"query_param": {"in": ParamType.QUERY, "required": True},
"handler_param": {"in": ParamType.QUERY, "required": True},
}
def test_get_schema_for_annotation_enum() -> None:
class Opts(str, Enum):
opt1 = "opt1"
opt2 = "opt2"
schema = get_schema_for_field_definition(FieldDefinition.from_annotation(Opts))
assert schema.enum == ["opt1", "opt2"]
ValueType: TypeAlias = Literal["a", "b", "c"]
ConstType: TypeAlias = Literal[1]
def test_handling_of_literals() -> None:
@dataclass
class DataclassWithLiteral:
value: ValueType
const: ConstType
composite: Literal[ValueType, ConstType]
schema = get_schema_for_field_definition(FieldDefinition.from_kwarg(name="", annotation=DataclassWithLiteral))
assert isinstance(schema, Schema)
assert schema.properties
value = schema.properties["value"]
assert isinstance(value, Schema)
assert value.enum == ["a", "b", "c"]
const = schema.properties["const"]
assert isinstance(const, Schema)
assert const.const == 1
composite = schema.properties["composite"]
assert isinstance(composite, Schema)
assert composite.enum == ["a", "b", "c", 1]
def test_schema_hashing() -> None:
schema = Schema(
one_of=[
Schema(type=OpenAPIType.STRING),
Schema(type=OpenAPIType.NUMBER),
Schema(type=OpenAPIType.OBJECT, properties={"key": Schema(type=OpenAPIType.STRING)}),
],
examples=[None, [1, 2, 3]],
)
assert hash(schema)
def test_title_validation() -> None:
# TODO: what is this actually testing?
creator = SchemaCreator(plugins=openapi_schema_plugins)
person_ref = creator.for_field_definition(FieldDefinition.from_kwarg(name="Person", annotation=DataclassPerson))
pet_ref = creator.for_field_definition(FieldDefinition.from_kwarg(name="Pet", annotation=DataclassPet))
assert isinstance(person_ref, Reference)
assert isinstance(pet_ref, Reference)
assert isinstance(creator.schema_registry.from_reference(person_ref).schema, Schema)
assert isinstance(creator.schema_registry.from_reference(pet_ref).schema, Schema)
@pytest.mark.parametrize("with_future_annotations", [True, False])
def test_create_schema_for_dataclass_with_annotated_model_attribute(
with_future_annotations: bool, create_module: "Callable[[str], ModuleType]"
) -> None:
"""Test that a model with an annotated attribute is correctly handled."""
module = create_module(
f"""
{"from __future__ import annotations" if with_future_annotations else ""}
from typing_extensions import Annotated
from dataclasses import dataclass
@dataclass
class Foo:
foo: Annotated[int, "Foo description"]
"""
)
schema = get_schema_for_field_definition(FieldDefinition.from_annotation(module.Foo))
assert schema.properties and "foo" in schema.properties
@pytest.mark.parametrize("with_future_annotations", [True, False])
def test_create_schema_for_typedict_with_annotated_required_and_not_required_model_attributes(
with_future_annotations: bool, create_module: "Callable[[str], ModuleType]"
) -> None:
"""Test that a model with an annotated attribute is correctly handled."""
module = create_module(
f"""
{"from __future__ import annotations" if with_future_annotations else ""}
from typing_extensions import Annotated, Required, NotRequired
from typing import TypedDict
class Foo(TypedDict):
foo: Annotated[int, "Foo description"]
bar: Annotated[Required[int], "Bar description"]
baz: Annotated[NotRequired[int], "Baz description"]
"""
)
schema = get_schema_for_field_definition(FieldDefinition.from_annotation(module.Foo))
assert schema.properties and all(key in schema.properties for key in ("foo", "bar", "baz"))
def test_create_schema_from_msgspec_annotated_type() -> None:
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)]
default_field: Annotated[str, msgspec.Meta(min_length=1)] = "a"
schema = get_schema_for_field_definition(FieldDefinition.from_kwarg(name="Lookup", annotation=Lookup))
assert schema.properties["int_field"].type == OpenAPIType.INTEGER # type: ignore[index, union-attr]
assert schema.properties["int_field"].exclusive_minimum == 0 # type: ignore[index, union-attr]
assert schema.properties["str_field"].type == OpenAPIType.STRING # type: ignore[index, union-attr]
assert schema.properties["str_field"].examples == ["example"] # type: ignore[index, union-attr]
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 schema.properties["bytes_field"].to_schema() == { # type: ignore[index]
"contentEncoding": "utf-8",
"maxLength": 2,
"minLength": 1,
"type": "string",
}
def test_annotated_types() -> None:
historical_date = date(year=1980, day=1, month=1)
today = date.today()
@dataclass
class MyDataclass:
constrained_int: Annotated[int, annotated_types.Gt(1), annotated_types.Lt(10)]
constrained_float: Annotated[float, annotated_types.Ge(1), annotated_types.Le(10)]
constrained_date: Annotated[date, annotated_types.Interval(gt=historical_date, lt=today)]
constrained_lower_case: annotated_types.LowerCase[str]
constrained_upper_case: annotated_types.UpperCase[str]
constrained_is_ascii: annotated_types.IsAscii[str]
constrained_is_digit: annotated_types.IsDigit[str]
schema = get_schema_for_field_definition(FieldDefinition.from_kwarg(name="MyDataclass", annotation=MyDataclass))
assert schema.properties["constrained_int"].exclusive_minimum == 1 # type: ignore[index, union-attr]
assert schema.properties["constrained_int"].exclusive_maximum == 10 # type: ignore[index, union-attr]
assert schema.properties["constrained_float"].minimum == 1 # type: ignore[index, union-attr]
assert schema.properties["constrained_float"].maximum == 10 # type: ignore[index, union-attr]
assert datetime.fromtimestamp(
schema.properties["constrained_date"].exclusive_minimum, # type: ignore[arg-type, index, union-attr]
tz=timezone.utc,
) == datetime.fromordinal(historical_date.toordinal()).replace(tzinfo=timezone.utc)
assert datetime.fromtimestamp(
schema.properties["constrained_date"].exclusive_maximum, # type: ignore[arg-type, index, union-attr]
tz=timezone.utc,
) == datetime.fromordinal(today.toordinal()).replace(tzinfo=timezone.utc)
assert schema.properties["constrained_lower_case"].description == "must be in lower case" # type: ignore[index]
assert schema.properties["constrained_upper_case"].description == "must be in upper case" # type: ignore[index]
assert schema.properties["constrained_is_ascii"].pattern == "[[:ascii:]]" # type: ignore[index, union-attr]
assert schema.properties["constrained_is_digit"].pattern == "[[:digit:]]" # type: ignore[index, union-attr]
def test_literal_enums() -> None:
class Foo(Enum):
A = auto()
B = auto()
schema = get_schema_for_field_definition(FieldDefinition.from_annotation(List[Literal[Foo.A]]))
assert isinstance(schema.items, Schema)
assert schema.items.const == 1
@dataclass
class DataclassGeneric(Generic[T]):
foo: T
optional_foo: Optional[T]
annotated_foo: Annotated[T, object()]
class MsgspecGeneric(Struct, Generic[T]):
foo: T
optional_foo: Optional[T]
annotated_foo: Annotated[T, object()]
annotations: List[type] = [DataclassGeneric[int], MsgspecGeneric[int]]
# Generic TypedDict was only supported from 3.11 onwards
if sys.version_info >= (3, 11):
class TypedDictGeneric(TypedDict, Generic[T]):
foo: T
optional_foo: Optional[T]
annotated_foo: Annotated[T, object()]
annotations.append(TypedDictGeneric[int])
@pytest.mark.parametrize("cls", annotations)
def test_schema_generation_with_generic_classes(cls: Any) -> None:
expected_foo_schema = Schema(type=OpenAPIType.INTEGER)
expected_optional_foo_schema = Schema(one_of=[Schema(type=OpenAPIType.INTEGER), Schema(type=OpenAPIType.NULL)])
properties = get_schema_for_field_definition(
FieldDefinition.from_kwarg(name=get_name(cls), annotation=cls)
).properties
assert properties
assert properties["foo"] == expected_foo_schema
assert properties["annotated_foo"] == expected_foo_schema
assert properties["optional_foo"] == expected_optional_foo_schema
B = TypeVar("B", bound=int)
C = TypeVar("C", int, str)
@dataclass
class ConstrainedGenericDataclass(Generic[T, B, C]):
bound: B
constrained: C
union: Union[T, bool]
union_constrained: Union[C, bool]
union_bound: Union[B, bool]
def test_schema_generation_with_generic_classes_constrained() -> None:
cls = ConstrainedGenericDataclass
properties = get_schema_for_field_definition(
FieldDefinition.from_kwarg(name=cls.__name__, annotation=cls)
).properties
assert properties
assert properties["bound"] == Schema(type=OpenAPIType.INTEGER)
assert properties["constrained"] == Schema(
one_of=[Schema(type=OpenAPIType.INTEGER), Schema(type=OpenAPIType.STRING)]
)
assert properties["union"] == Schema(one_of=[Schema(type=OpenAPIType.OBJECT), Schema(type=OpenAPIType.BOOLEAN)])
assert properties["union_constrained"] == Schema(
one_of=[Schema(type=OpenAPIType.INTEGER), Schema(type=OpenAPIType.STRING), Schema(type=OpenAPIType.BOOLEAN)]
)
assert properties["union_bound"] == Schema(
one_of=[Schema(type=OpenAPIType.INTEGER), Schema(type=OpenAPIType.BOOLEAN)]
)
@pytest.mark.parametrize(
"annotation",
(
ClassicPagination[DataclassGeneric[int]],
OffsetPagination[DataclassGeneric[int]],
CursorPagination[int, DataclassGeneric[int]],
),
)
def test_schema_generation_with_pagination(annotation: Any) -> None:
expected_foo_schema = Schema(type=OpenAPIType.INTEGER)
expected_optional_foo_schema = Schema(one_of=[Schema(type=OpenAPIType.INTEGER), Schema(type=OpenAPIType.NULL)])
properties = get_schema_for_field_definition(FieldDefinition.from_annotation(annotation).inner_types[-1]).properties
assert properties
assert properties["foo"] == expected_foo_schema
assert properties["annotated_foo"] == expected_foo_schema
assert properties["optional_foo"] == expected_optional_foo_schema
def test_schema_generation_with_ellipsis() -> None:
schema = get_schema_for_field_definition(FieldDefinition.from_annotation(Tuple[int, ...]))
assert isinstance(schema.items, Schema)
assert schema.items.type == OpenAPIType.INTEGER
def test_schema_tuple_with_union() -> None:
schema = get_schema_for_field_definition(FieldDefinition.from_annotation(Tuple[int, Union[int, str]]))
assert schema.prefix_items == [
Schema(type=OpenAPIType.INTEGER),
Schema(one_of=[Schema(type=OpenAPIType.INTEGER), Schema(type=OpenAPIType.STRING)]),
]
def test_schema_tuple() -> None:
schema = get_schema_for_field_definition(FieldDefinition.from_annotation(Tuple[int, str]))
assert schema == Schema(
prefix_items=[Schema(type=OpenAPIType.INTEGER), Schema(type=OpenAPIType.STRING)],
type=OpenAPIType.ARRAY,
)
def test_schema_optional_tuple() -> None:
schema = get_schema_for_field_definition(FieldDefinition.from_annotation(Optional[Tuple[int, str]]))
assert schema == Schema(
one_of=[
Schema(
prefix_items=[Schema(type=OpenAPIType.INTEGER), Schema(type=OpenAPIType.STRING)],
type=OpenAPIType.ARRAY,
),
Schema(type=OpenAPIType.NULL),
],
)
def test_optional_enum() -> None:
class Foo(Enum):
A = 1
B = "b"
creator = SchemaCreator(plugins=openapi_schema_plugins)
schema = creator.for_field_definition(FieldDefinition.from_annotation(Optional[Foo]))
assert isinstance(schema, Schema)
assert schema.type is None
assert schema.one_of is not None
null_schema = schema.one_of[1]
assert isinstance(null_schema, Schema)
assert null_schema.type is not None
assert null_schema.type is OpenAPIType.NULL
enum_ref = schema.one_of[0]
assert isinstance(enum_ref, Reference)
assert enum_ref.ref == "#/components/schemas/tests_unit_test_openapi_test_schema_test_optional_enum.Foo"
enum_schema = creator.schema_registry.from_reference(enum_ref).schema
assert enum_schema.type
assert set(enum_schema.type) == {OpenAPIType.INTEGER, OpenAPIType.STRING}
assert enum_schema.enum
assert enum_schema.enum[0] == 1
assert enum_schema.enum[1] == "b"
def test_optional_str_specified_enum() -> None:
class StringEnum(str, Enum):
A = "a"
B = "b"
creator = SchemaCreator(plugins=openapi_schema_plugins)
schema = creator.for_field_definition(FieldDefinition.from_annotation(Optional[StringEnum]))
assert isinstance(schema, Schema)
assert schema.type is None
assert schema.one_of is not None
enum_ref = schema.one_of[0]
assert isinstance(enum_ref, Reference)
assert (
enum_ref.ref
== "#/components/schemas/tests_unit_test_openapi_test_schema_test_optional_str_specified_enum.StringEnum"
)
enum_schema = creator.schema_registry.from_reference(enum_ref).schema
assert enum_schema.type
assert enum_schema.type == OpenAPIType.STRING
assert enum_schema.enum
assert enum_schema.enum[0] == "a"
assert enum_schema.enum[1] == "b"
null_schema = schema.one_of[1]
assert isinstance(null_schema, Schema)
assert null_schema.type is not None
assert null_schema.type is OpenAPIType.NULL
def test_optional_int_specified_enum() -> None:
class IntEnum(int, Enum):
A = 1
B = 2
creator = SchemaCreator(plugins=openapi_schema_plugins)
schema = creator.for_field_definition(FieldDefinition.from_annotation(Optional[IntEnum]))
assert isinstance(schema, Schema)
assert schema.type is None
assert schema.one_of is not None
enum_ref = schema.one_of[0]
assert isinstance(enum_ref, Reference)
assert (
enum_ref.ref
== "#/components/schemas/tests_unit_test_openapi_test_schema_test_optional_int_specified_enum.IntEnum"
)
enum_schema = creator.schema_registry.from_reference(enum_ref).schema
assert enum_schema.type
assert enum_schema.type == OpenAPIType.INTEGER
assert enum_schema.enum
assert enum_schema.enum[0] == 1
assert enum_schema.enum[1] == 2
null_schema = schema.one_of[1]
assert isinstance(null_schema, Schema)
assert null_schema.type is not None
assert null_schema.type is OpenAPIType.NULL
def test_optional_literal() -> None:
schema = get_schema_for_field_definition(FieldDefinition.from_annotation(Optional[Literal[1]]))
assert schema.type is not None
assert set(schema.type) == {OpenAPIType.INTEGER, OpenAPIType.NULL}
assert schema.enum == [1, None]
def test_not_generating_examples_property() -> None:
with_examples = SchemaCreator(generate_examples=True)
without_examples = with_examples.not_generating_examples
assert without_examples.generate_examples is False
def test_process_schema_result_with_unregistered_object_schema() -> None:
"""This test ensures that if a schema is created for an object and not registered in the schema registry, the
schema is returned as-is, and not referenced.
"""
schema = Schema(title="has title", type=OpenAPIType.OBJECT)
field_definition = FieldDefinition.from_annotation(dict)
assert SchemaCreator().process_schema_result(field_definition, schema) is schema
@pytest.mark.parametrize("base_type", [msgspec.Struct, TypedDict, dataclass])
def test_type_union(base_type: type) -> None:
if base_type is dataclass:
@dataclass
class ModelA: # pyright: ignore
pass
@dataclass
class ModelB: # pyright: ignore
pass
else:
class ModelA(base_type): # type: ignore[no-redef, misc]
pass
class ModelB(base_type): # type: ignore[no-redef, misc]
pass
schema = get_schema_for_field_definition(
FieldDefinition.from_kwarg(name="Lookup", annotation=Union[ModelA, ModelB])
)
assert schema.one_of == [
Reference(ref="#/components/schemas/tests_unit_test_openapi_test_schema_test_type_union.ModelA"),
Reference(ref="#/components/schemas/tests_unit_test_openapi_test_schema_test_type_union.ModelB"),
]
@pytest.mark.parametrize("base_type", [msgspec.Struct, TypedDict, dataclass])
def test_type_union_with_none(base_type: type) -> None:
# https://github.com/litestar-org/litestar/issues/2971
if base_type is dataclass:
@dataclass
class ModelA: # pyright: ignore
pass
@dataclass
class ModelB: # pyright: ignore
pass
else:
class ModelA(base_type): # type: ignore[no-redef, misc]
pass
class ModelB(base_type): # type: ignore[no-redef, misc]
pass
schema = get_schema_for_field_definition(
FieldDefinition.from_kwarg(name="Lookup", annotation=Union[ModelA, ModelB, None])
)
assert schema.one_of == [
Reference(ref="#/components/schemas/tests_unit_test_openapi_test_schema_test_type_union_with_none.ModelA"),
Reference("#/components/schemas/tests_unit_test_openapi_test_schema_test_type_union_with_none.ModelB"),
Schema(type=OpenAPIType.NULL),
]
def test_default_only_on_field_definition() -> None:
field_definition = FieldDefinition.from_annotation(int, default=10)
assert field_definition.kwarg_definition is None
schema = get_schema_for_field_definition(field_definition)
assert schema.default == 10
def test_default_not_provided_for_kwarg_but_for_field() -> None:
field_definition = FieldDefinition.from_annotation(int, default=10, kwarg_definition=KwargDefinition())
schema = get_schema_for_field_definition(field_definition)
assert schema.default == 10
def test_routes_with_different_path_param_types_get_merged() -> None:
# https://github.com/litestar-org/litestar/issues/2700
@get("/{param:int}")
async def get_handler(param: int) -> None:
pass
@post("/{param:str}")
async def post_handler(param: str) -> None:
pass
app = Litestar([get_handler, post_handler])
assert app.openapi_schema.paths
paths = app.openapi_schema.paths["/{param}"]
assert paths.get is not None
assert paths.post is not None
def test_unconsumed_path_parameters_are_documented() -> None:
# https://github.com/litestar-org/litestar/issues/3290
# https://github.com/litestar-org/litestar/issues/3369
async def dd(param3: Annotated[str, Parameter(description="123")]) -> str:
return param3
async def d(dep_dep: str, param2: Annotated[str, Parameter(description="abc")]) -> str:
return f"{dep_dep}_{param2}"
@get("/{param1:str}/{param2:str}/{param3:str}", dependencies={"dep": d, "dep_dep": dd})
async def handler(dep: str) -> None:
pass
app = Litestar([handler])
params = app.openapi_schema.paths["/{param1}/{param2}/{param3}"].get.parameters # type: ignore[index, union-attr]
assert params
assert len(params) == 3
for i, param in enumerate(sorted(params, key=lambda p: p.name), 1): # pyright: ignore
assert isinstance(param, OpenAPIParameter)
assert param.name == f"param{i}"
assert param.required is True
assert param.param_in is ParamType.PATH
def test_type_alias_type() -> None:
@get("/")
def handler(query_param: Annotated[TypeAliasType("IntAlias", int), Parameter(description="foo")]) -> None: # type: ignore[valid-type]
pass
app = Litestar([handler])
param = app.openapi_schema.paths["/"].get.parameters[0] # type: ignore[index, union-attr]
assert param.schema.type is OpenAPIType.INTEGER # type: ignore[union-attr]
# ensure other attributes than the plain type are carried over correctly
assert param.description == "foo"
@pytest.mark.skipif(sys.version_info < (3, 12), reason="type keyword not available before 3.12")
def test_type_alias_type_keyword() -> None:
ctx: Dict[str, Any] = {}
exec("type IntAlias = int", ctx, None)
annotation = ctx["IntAlias"]
@get("/")
def handler(query_param: Annotated[annotation, Parameter(description="foo")]) -> None: # type: ignore[valid-type]
pass
app = Litestar([handler])
param = app.openapi_schema.paths["/"].get.parameters[0] # type: ignore[union-attr, index]
assert param.schema.type is OpenAPIType.INTEGER # type: ignore[union-attr]
# ensure other attributes than the plain type are carried over correctly
assert param.description == "foo"
|