Skip to content

Commit

Permalink
Allow basic types used as serialization method to be json schema inst…
Browse files Browse the repository at this point in the history
…ance type
  • Loading branch information
Fatal1ty committed Sep 3, 2023
1 parent 7349f73 commit 2e6a218
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
5 changes: 5 additions & 0 deletions mashumaro/jsonschema/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,9 @@ class Config(config_cls): # type: ignore
register = Registry.register


BASIC_TYPES = {str, int, float, bool}


@register
def on_type_with_overridden_serialization(
instance: Instance, ctx: Context
Expand All @@ -301,6 +304,8 @@ def override_with_any(reason: Any) -> None:
overridden_method = instance.get_overridden_serialization_method()
if overridden_method is pass_through:
return None
elif overridden_method in BASIC_TYPES:
instance.update_type(overridden_method) # type: ignore
elif callable(overridden_method):
try:
new_type = get_function_return_annotation(overridden_method)
Expand Down
30 changes: 30 additions & 0 deletions tests/test_jsonschema/test_jsonschema_generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1019,6 +1019,36 @@ class Config(BaseConfig):
)


@pytest.mark.parametrize(
("basic_type", "schema_type"),
(
(str, JSONSchemaInstanceType.STRING),
(int, JSONSchemaInstanceType.INTEGER),
(float, JSONSchemaInstanceType.NUMBER),
(bool, JSONSchemaInstanceType.BOOLEAN),
),
)
def test_basic_type_as_overridden_serialization_method(
basic_type, schema_type
):
@dataclass
class DataClass:
x: ThirdPartyType
y: List[ThirdPartyType]

class Config(BaseConfig):
serialization_strategy = {
ThirdPartyType: {"serialize": basic_type}
}

assert build_json_schema(DataClass).properties["x"] == JSONSchema(
type=schema_type
)
assert build_json_schema(DataClass).properties["y"] == JSONArraySchema(
items=JSONSchema(type=schema_type)
)


def test_dataclass_overridden_serialization_method():
def serialize_as_str(value: Any) -> str:
return str(value) # pragma no cover
Expand Down

0 comments on commit 2e6a218

Please sign in to comment.