Skip to content

Commit

Permalink
Fix issue with JSON schema incorrectly using parent class core schema (
Browse files Browse the repository at this point in the history
  • Loading branch information
dmontagu committed Aug 16, 2023
1 parent 325a5e2 commit e1bc4e1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
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',
}

0 comments on commit e1bc4e1

Please sign in to comment.