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

Deserialization should be done after coercion #501

Merged
merged 2 commits into from
Dec 12, 2022
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion apischema/deserialization/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -647,7 +647,11 @@ def factory(constraints: Optional[Constraints], _) -> DeserializationMethod:
if fact.cls is not NoneType
)
return OptionalMethod(value_method, self.coercer)
elif len(method_by_cls) == len(alt_factories):
elif len(method_by_cls) == len(alt_factories) and not any(
isinstance(x, CoercerMethod) for x in alt_methods
):
# Coercion induces a different type in data than type to deserialize.
# Prefer UnionMethod in this case.
return UnionByTypeMethod(method_by_cls)
else:
return UnionMethod(alt_methods)
Expand Down
33 changes: 33 additions & 0 deletions tests/integration/test_deserialize_with_coercion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from __future__ import annotations

import json
from dataclasses import dataclass
from typing import Any, Mapping, Sequence, Union

from apischema import deserialize


def _coerce_json(cls, data):
if not isinstance(data, cls) and isinstance(data, str):
return json.loads(data)
else:
return data


@dataclass
class MyClass:
my_property: Union[Sequence[str], Mapping[str, Any]]


def test_coerce_json():
key = "test"
value = 2
ret = deserialize(
MyClass,
{
"my_property": f'{{"{key}": {value}}}',
},
coerce=_coerce_json,
)
assert isinstance(ret, MyClass)
assert isinstance(ret.my_property, dict) and ret.my_property[key] == value
3 changes: 2 additions & 1 deletion tests/integration/test_object_fields_overriding.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ class Foo:


@pytest.mark.skipif(
sys.version_info < (3, 8), reason="dataclasses.replace bug with InitVar"
(sys.version_info < (3, 8) or ((3, 9) < sys.version_info < (3, 9, 5))),
reason="dataclasses.replace bug with InitVar",
)
def test_object_fields_overriding():
set_object_fields(Foo, [])
Expand Down