File: test_final.py

package info (click to toggle)
python-cattrs 25.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,812 kB
  • sloc: python: 12,236; makefile: 155
file content (49 lines) | stat: -rw-r--r-- 1,626 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from attrs import Factory, define

from cattrs import Converter
from cattrs._compat import Final


@define
class C:
    a: Final[int]


def test_unstructure_final(genconverter: Converter) -> None:
    """Unstructuring should work, and unstructure hooks should work."""
    assert genconverter.unstructure(C(1)) == {"a": 1}

    genconverter.register_unstructure_hook(int, lambda i: str(i))
    assert genconverter.unstructure(C(1)) == {"a": "1"}


def test_structure_final(genconverter: Converter) -> None:
    """Structuring should work, and structure hooks should work."""
    assert genconverter.structure({"a": 1}, C) == C(1)

    genconverter.register_structure_hook(int, lambda i, _: int(i) + 1)
    assert genconverter.structure({"a": "1"}, C) == C(2)


@define
class D:
    a: Final[int]
    b: Final = 5
    c: Final = Factory(lambda: 3)


def test_unstructure_bare_final(genconverter: Converter) -> None:
    """Unstructuring bare Finals should work, and unstructure hooks should work."""
    assert genconverter.unstructure(D(1)) == {"a": 1, "b": 5, "c": 3}

    genconverter.register_unstructure_hook(int, lambda i: str(i))
    # Bare finals resolve to `Final[Any]`, so the custom hook works.
    assert genconverter.unstructure(D(1)) == {"a": "1", "b": "5", "c": "3"}


def test_structure_bare_final(genconverter: Converter) -> None:
    """Structuring should work, and structure hooks should work."""
    assert genconverter.structure({"a": 1, "b": 3}, D) == D(1, 3)

    genconverter.register_structure_hook(int, lambda i, _: int(i) + 1)
    assert genconverter.structure({"a": "1", "b": "3"}, D) == D(2, 4, 3)