Skip to content

Commit

Permalink
JSON schema: fix extra parameter handling (#7810)
Browse files Browse the repository at this point in the history
Co-authored-by: sydney-runkle <54324534+sydney-runkle@users.noreply.github.com>
Co-authored-by: David Hewitt <1939362+davidhewitt@users.noreply.github.com>
  • Loading branch information
3 people committed Oct 20, 2023
1 parent 6a4b329 commit 7cda00e
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
4 changes: 3 additions & 1 deletion pydantic/json_schema.py
Expand Up @@ -1195,7 +1195,9 @@ def typed_dict_schema(self, schema: core_schema.TypedDictSchema) -> JsonSchemaVa
with self._config_wrapper_stack.push(config):
json_schema = self._named_required_fields_schema(named_required_fields)

extra = config.get('extra', 'ignore')
extra = schema.get('extra_behavior')
if extra is None:
extra = config.get('extra', 'ignore')
if extra == 'forbid':
json_schema['additionalProperties'] = False
elif extra == 'allow':
Expand Down
50 changes: 50 additions & 0 deletions tests/test_json_schema.py
Expand Up @@ -2406,6 +2406,23 @@ class Model(TypedDict):
}


def test_typeddict_with_extra_behavior_allow():
class Model:
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
return core_schema.typed_dict_schema(
{'a': core_schema.typed_dict_field(core_schema.str_schema())},
extra_behavior='allow',
)

assert TypeAdapter(Model).json_schema() == {
'type': 'object',
'properties': {'a': {'title': 'A', 'type': 'string'}},
'required': ['a'],
'additionalProperties': True,
}


def test_typeddict_with_extra_ignore():
class Model(TypedDict):
__pydantic_config__ = ConfigDict(extra='ignore') # type: ignore
Expand All @@ -2419,6 +2436,22 @@ class Model(TypedDict):
}


def test_typeddict_with_extra_behavior_ignore():
class Model:
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
return core_schema.typed_dict_schema(
{'a': core_schema.typed_dict_field(core_schema.str_schema())},
extra_behavior='ignore',
)

assert TypeAdapter(Model).json_schema() == {
'type': 'object',
'properties': {'a': {'title': 'A', 'type': 'string'}},
'required': ['a'],
}


def test_typeddict_with_extra_forbid():
@pydantic.dataclasses.dataclass
class Model:
Expand All @@ -2434,6 +2467,23 @@ class Model:
}


def test_typeddict_with_extra_behavior_forbid():
class Model:
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
return core_schema.typed_dict_schema(
{'a': core_schema.typed_dict_field(core_schema.str_schema())},
extra_behavior='forbid',
)

assert TypeAdapter(Model).json_schema() == {
'type': 'object',
'properties': {'a': {'title': 'A', 'type': 'string'}},
'required': ['a'],
'additionalProperties': False,
}


@pytest.mark.parametrize(
'annotation,kwargs,field_schema',
[
Expand Down

0 comments on commit 7cda00e

Please sign in to comment.