File: test_newtypes.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 (58 lines) | stat: -rw-r--r-- 2,004 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
50
51
52
53
54
55
56
57
58
"""Tests for NewTypes."""

from typing import NewType

import pytest

from cattrs import BaseConverter, Converter

PositiveIntNewType = NewType("PositiveIntNewType", int)
BigPositiveIntNewType = NewType("BigPositiveIntNewType", PositiveIntNewType)


def test_newtype_structure_hooks(converter: BaseConverter):
    """NewTypes should work with `register_structure_hook`."""

    assert converter.structure("0", int) == 0
    assert converter.structure("0", PositiveIntNewType) == 0
    assert converter.structure("0", BigPositiveIntNewType) == 0

    converter.register_structure_hook(
        PositiveIntNewType, lambda v, _: int(v) if int(v) > 0 else 1 / 0
    )

    with pytest.raises(ZeroDivisionError):
        converter.structure("0", PositiveIntNewType)

    assert converter.structure("1", PositiveIntNewType) == 1

    with pytest.raises(ZeroDivisionError):
        converter.structure("0", BigPositiveIntNewType)

    converter.register_structure_hook(
        BigPositiveIntNewType, lambda v, _: int(v) if int(v) > 50 else 1 / 0
    )

    with pytest.raises(ZeroDivisionError):
        converter.structure("1", BigPositiveIntNewType)

    assert converter.structure("1", PositiveIntNewType) == 1
    assert converter.structure("51", BigPositiveIntNewType) == 51


def test_newtype_unstructure_hooks(genconverter: Converter):
    """NewTypes should work with `register_unstructure_hook`."""

    assert genconverter.unstructure(0, int) == 0
    assert genconverter.unstructure(0, PositiveIntNewType) == 0
    assert genconverter.unstructure(0, BigPositiveIntNewType) == 0

    genconverter.register_unstructure_hook(PositiveIntNewType, oct)

    assert genconverter.unstructure(0, PositiveIntNewType) == "0o0"
    assert genconverter.unstructure(0, BigPositiveIntNewType) == "0o0"

    genconverter.register_unstructure_hook(BigPositiveIntNewType, hex)

    assert genconverter.unstructure(0, PositiveIntNewType) == "0o0"
    assert genconverter.unstructure(0, BigPositiveIntNewType) == "0x0"