Skip to content

Commit eb8cbf5

Browse files
committed
default value
1 parent 891b83a commit eb8cbf5

File tree

3 files changed

+12
-4
lines changed

3 files changed

+12
-4
lines changed

src/aiopenapi3/model.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -298,8 +298,14 @@ def from_schema(
298298

299299
r: list[_ClassInfo] = list()
300300

301-
for _type in Model.types(schema):
302-
args = dict()
301+
types: list[str] = list(Model.types(schema))
302+
multi: bool = len(types) > 1
303+
for _type in types:
304+
args = dict() if multi else None
305+
"""
306+
for schema with multiple types, the default value needs to be attached to the RootModel
307+
providing empty args creates a FieldInfo without a default value for the subtypes
308+
"""
303309
r.append(Model.createClassInfo(schema, _type, schemanames, discriminators, extra, args))
304310

305311
m = _ClassInfo.collapse(schema, r)
@@ -361,7 +367,6 @@ def createClassInfo(
361367
classinfo.root = Annotated[
362368
Union[t], Field(discriminator=Model.nameof(schema.discriminator.propertyName))
363369
]
364-
365370
else:
366371
if len(t):
367372
classinfo.root = Union[t]
@@ -614,7 +619,7 @@ def createAnnotation(
614619
return rr
615620

616621
@staticmethod
617-
def types(schema: "SchemaType"):
622+
def types(schema: "SchemaType") -> typing.Generator[str, None, None]:
618623
if isinstance(schema.type, str):
619624
yield schema.type
620625
if getattr(schema, "nullable", False):

tests/fixtures/schema-type-validators.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ components:
99
type: integer
1010
maximum: 10
1111
minimum: 10
12+
default: 10
1213
Number:
1314
type: number
1415
maximum: 10

tests/schema_test.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -653,6 +653,8 @@ def test_schema_type_validators(with_schema_type_validators):
653653
v = t.model_validate("10")
654654
with pytest.raises(ValidationError):
655655
v = t.model_validate("9")
656+
v = t()
657+
assert v.root == 10
656658

657659
t = (m := api.components.schemas["Number"]).get_type()
658660
v = t.model_validate("10.")

0 commit comments

Comments
 (0)