Skip to content

Commit

Permalink
Improve cols coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
Tinche committed Dec 2, 2024
1 parent 9f0450e commit 75a3094
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
14 changes: 14 additions & 0 deletions tests/test_defaultdicts.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from typing import DefaultDict

from cattrs import Converter
from cattrs.cols import defaultdict_structure_factory


def test_typing_defaultdicts(genconverter: Converter):
Expand All @@ -30,3 +31,16 @@ def test_collection_defaultdicts(genconverter: Converter):
genconverter.register_unstructure_hook(int, str)

assert genconverter.unstructure(res) == {"a": "1", "b": "0"}


def test_factory(genconverter: Converter):
"""Explicit factories work."""
genconverter.register_structure_hook_func(
lambda t: t == defaultdict[str, int],
defaultdict_structure_factory(defaultdict[str, int], genconverter, lambda: 2),
)
res = genconverter.structure({"a": 1}, defaultdict[str, int])

assert isinstance(res, defaultdict)
assert res["a"] == 1
assert res["b"] == 2
14 changes: 10 additions & 4 deletions tests/test_tuples.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,19 +69,25 @@ class Test(NamedTuple):
def test_simple_dict_nametuples(genconverter: Converter):
"""Namedtuples can be un/structured to/from dicts."""

class TestInner(NamedTuple):
a: int

class Test(NamedTuple):
a: int
b: str = "test"
c: TestInner = TestInner(1)

genconverter.register_unstructure_hook_factory(
lambda t: t is Test, namedtuple_dict_unstructure_factory
lambda t: t in (Test, TestInner), namedtuple_dict_unstructure_factory
)
genconverter.register_structure_hook_factory(
lambda t: t is Test, namedtuple_dict_structure_factory
lambda t: t in (Test, TestInner), namedtuple_dict_structure_factory
)

assert genconverter.unstructure(Test(1)) == {"a": 1, "b": "test"}
assert genconverter.structure({"a": 1, "b": "2"}, Test) == Test(1, "2")
assert genconverter.unstructure(Test(1)) == {"a": 1, "b": "test", "c": {"a": 1}}
assert genconverter.structure({"a": 1, "b": "2"}, Test) == Test(
1, "2", TestInner(1)
)

# Defaults work.
assert genconverter.structure({"a": 1}, Test) == Test(1, "test")
Expand Down

0 comments on commit 75a3094

Please sign in to comment.