serde/fix: round trip string sanitizing

This commit is contained in:
Johannes Kirschbauer
2024-09-03 18:03:13 +02:00
parent 6e6bc22128
commit 5defa9d49d
2 changed files with 13 additions and 2 deletions

View File

@@ -155,13 +155,12 @@ def construct_value(
return Path(field_value) return Path(field_value)
# Trivial values
if t is str: if t is str:
if not isinstance(field_value, str): if not isinstance(field_value, str):
msg = f"Expected string, got {field_value}" msg = f"Expected string, got {field_value}"
raise ClanError(msg, location=f"{loc}") raise ClanError(msg, location=f"{loc}")
return field_value return json.loads(f'"{field_value}"')
if t is int and not isinstance(field_value, str): if t is int and not isinstance(field_value, str):
return int(field_value) # type: ignore return int(field_value) # type: ignore

View File

@@ -265,6 +265,18 @@ def test_none_or_string() -> None:
assert checked3 is None assert checked3 is None
def test_roundtrip_escape() -> None:
assert from_dict(str, "\\n") == "\n"
assert dataclass_to_dict("\n") == "\\n"
# Test that the functions are inverses of each other
# f(g(x)) == x
# and
# g(f(x)) == x
assert from_dict(str, dataclass_to_dict("\n")) == "\n"
assert dataclass_to_dict(from_dict(str, "\\n")) == "\\n"
def test_path_field() -> None: def test_path_field() -> None:
@dataclass @dataclass
class Person: class Person: