Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

model_json_schema export with Annotated types misses 'required' parameters #8793

Merged
merged 3 commits into from Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions pydantic/fields.py
Expand Up @@ -402,6 +402,13 @@ def merge_field_infos(*field_infos: FieldInfo, **overrides: Any) -> FieldInfo:
# No merging necessary, but we still need to make a copy and apply the overrides
field_info = copy(field_infos[0])
field_info._attributes_set.update(overrides)

default_override = overrides.pop('default', PydanticUndefined)
if default_override is Ellipsis:
default_override = PydanticUndefined
if default_override is not PydanticUndefined:
field_info.default = default_override

for k, v in overrides.items():
setattr(field_info, k, v)
return field_info # type: ignore
Expand Down
78 changes: 61 additions & 17 deletions tests/test_json_schema.py
Expand Up @@ -6,14 +6,7 @@
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from enum import Enum, IntEnum
from ipaddress import (
IPv4Address,
IPv4Interface,
IPv4Network,
IPv6Address,
IPv6Interface,
IPv6Network,
)
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from typing import (
Any,
Expand Down Expand Up @@ -75,15 +68,7 @@
model_json_schema,
models_json_schema,
)
from pydantic.networks import (
AnyUrl,
EmailStr,
IPvAnyAddress,
IPvAnyInterface,
IPvAnyNetwork,
MultiHostUrl,
NameEmail,
)
from pydantic.networks import AnyUrl, EmailStr, IPvAnyAddress, IPvAnyInterface, IPvAnyNetwork, MultiHostUrl, NameEmail
from pydantic.type_adapter import TypeAdapter
from pydantic.types import (
UUID1,
Expand Down Expand Up @@ -5947,3 +5932,62 @@ class Model(BaseModel):
c: ModelC

assert Model.model_json_schema()


def test_json_schema_annotated_with_field() -> None:
"""Ensure field specified with Annotated in create_model call is still marked as required."""

from pydantic import create_model

Model = create_model(
'test_model',
bar=(Annotated[int, Field(description='Bar description')], ...),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you include this example as well? baz=(Annotated[int, Field(..., description="Baz description")], ...),

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe with this model:

Model = create_model(
    'test_model',
    foo=(int, ...),
    bar=(Annotated[int, Field(description="Bar description")], ...),
    baz=(Annotated[int, Field(..., description="Baz description")], ...),
)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done 😄

)

assert Model.model_json_schema() == {
'properties': {
'bar': {'description': 'Bar description', 'title': 'Bar', 'type': 'integer'},
},
'required': ['bar'],
'title': 'test_model',
'type': 'object',
}


def test_required_fields_in_annotated_with_create_model() -> None:
"""Ensure multiple field specified with Annotated in create_model call is still marked as required."""

from pydantic import create_model

Model = create_model(
'test_model',
foo=(int, ...),
bar=(Annotated[int, Field(description='Bar description')], ...),
baz=(Annotated[int, Field(..., description='Baz description')], ...),
)

assert Model.model_json_schema() == {
'properties': {
'foo': {'title': 'Foo', 'type': 'integer'},
'bar': {'description': 'Bar description', 'title': 'Bar', 'type': 'integer'},
'baz': {'description': 'Baz description', 'title': 'Baz', 'type': 'integer'},
},
'required': ['foo', 'bar', 'baz'],
'title': 'test_model',
'type': 'object',
}


def test_required_fields_in_annotated_with_basemodel() -> None:
"""
Ensure multiple field specified with Annotated in BaseModel is marked as required.
"""

class Model(BaseModel):
a: int = ...
b: Annotated[int, 'placeholder'] = ...
c: Annotated[int, Field()] = ...

assert Model.model_fields['a'].is_required()
assert Model.model_fields['b'].is_required()
assert Model.model_fields['c'].is_required()