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

Fix issue with JSON schema incorrectly using parent class core schema #7020

Merged
merged 2 commits into from Aug 16, 2023
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
5 changes: 4 additions & 1 deletion pydantic/json_schema.py
Expand Up @@ -41,7 +41,7 @@

from pydantic._internal import _annotated_handlers, _internal_dataclass

from ._internal import _core_metadata, _core_utils, _schema_generation_shared, _typing_extra
from ._internal import _core_metadata, _core_utils, _mock_validator, _schema_generation_shared, _typing_extra
from .config import JsonSchemaExtraCallable
from .errors import PydanticInvalidForJsonSchema, PydanticUserError

Expand Down Expand Up @@ -2127,6 +2127,9 @@ def model_json_schema(
The generated JSON Schema.
"""
schema_generator_instance = schema_generator(by_alias=by_alias, ref_template=ref_template)
if isinstance(cls.__pydantic_validator__, _mock_validator.MockValidator):
cls.__pydantic_validator__.rebuild()
assert '__pydantic_core_schema__' in cls.__dict__, 'this is a bug! please report it'
return schema_generator_instance.generate(cls.__pydantic_core_schema__, mode=mode)


Expand Down
33 changes: 33 additions & 0 deletions tests/test_json_schema.py
Expand Up @@ -5378,3 +5378,36 @@ class MyDataclass:
json_schema = adapter.json_schema()
for key in 'abcdef':
assert json_schema['properties'][key] == {'title': key.upper(), 'type': 'integer'} # default is not present


def test_model_rebuild_happens_even_with_parent_classes(create_module):
module = create_module(
# language=Python
"""
from __future__ import annotations
from pydantic import BaseModel

class MyBaseModel(BaseModel):
pass

class B(MyBaseModel):
b: A

class A(MyBaseModel):
a: str
"""
)
assert module.B.model_json_schema() == {
'$defs': {
'A': {
'properties': {'a': {'title': 'A', 'type': 'string'}},
'required': ['a'],
'title': 'A',
'type': 'object',
}
},
'properties': {'b': {'$ref': '#/$defs/A'}},
'required': ['b'],
'title': 'B',
'type': 'object',
}