Skip to content

Commit

Permalink
fix(OpenAPI): Schema generation for Pydantic v2 constrained secrets (#…
Browse files Browse the repository at this point in the history
…3149)

Fix OpenAPI schema generation for Pydantic v2 constrained secrets
  • Loading branch information
provinzkraut authored Mar 2, 2024
1 parent fe72143 commit 1332983
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
2 changes: 2 additions & 0 deletions litestar/contrib/pydantic/pydantic_schema_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,8 @@
if pydantic_v2 is not None: # pragma: no cover
PYDANTIC_TYPE_MAP.update(
{
pydantic_v2.SecretStr: Schema(type=OpenAPIType.STRING),
pydantic_v2.SecretBytes: Schema(type=OpenAPIType.STRING),
pydantic_v2.ByteSize: Schema(type=OpenAPIType.INTEGER),
pydantic_v2.EmailStr: Schema(type=OpenAPIType.STRING, format=OpenAPIFormat.EMAIL),
pydantic_v2.IPvAnyAddress: Schema(
Expand Down
15 changes: 15 additions & 0 deletions tests/unit/test_contrib/test_pydantic/test_schema_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from pydantic.v1.generics import GenericModel
from typing_extensions import Annotated

from litestar._openapi.schema_generation import SchemaCreator
from litestar.contrib.pydantic.pydantic_schema_plugin import PydanticSchemaPlugin
from litestar.openapi.spec import OpenAPIType
from litestar.openapi.spec.schema import Schema
Expand Down Expand Up @@ -65,3 +66,17 @@ def test_schema_generation_with_generic_classes(model: Type[Union[PydanticV1Gene
)
def test_is_pydantic_constrained_field(constrained: Any) -> None:
PydanticSchemaPlugin.is_constrained_field(FieldDefinition.from_annotation(constrained))


def test_v2_constrained_secrets() -> None:
# https://github.com/litestar-org/litestar/issues/3148
class Model(pydantic_v2.BaseModel):
string: pydantic_v2.SecretStr = pydantic_v2.Field(min_length=1)
bytes_: pydantic_v2.SecretBytes = pydantic_v2.Field(min_length=1)

schema = PydanticSchemaPlugin.for_pydantic_model(
FieldDefinition.from_annotation(Model), schema_creator=SchemaCreator(plugins=[PydanticSchemaPlugin()])
)
assert schema.properties
assert schema.properties["string"] == Schema(min_length=1, type=OpenAPIType.STRING)
assert schema.properties["bytes_"] == Schema(min_length=1, type=OpenAPIType.STRING)

0 comments on commit 1332983

Please sign in to comment.