File: test_recursive_union.py

package info (click to toggle)
python-mashumaro 3.16-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,400 kB
  • sloc: python: 19,890; sh: 16; makefile: 5
file content (72 lines) | stat: -rw-r--r-- 2,036 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from dataclasses import dataclass

from mashumaro import DataClassDictMixin
from mashumaro.codecs import BasicDecoder, BasicEncoder

type JSON = str | int | float | bool | dict[str, JSON] | list[JSON] | None


@dataclass
class MyClass:
    x: str
    y: JSON


def test_encoder_with_recursive_union():
    encoder = BasicEncoder(JSON)
    assert encoder.encode(
        {"x": [{"x": {"x": [{"x": ["x", 1, 1.0, True, None]}]}}]}
    ) == {"x": [{"x": {"x": [{"x": ["x", 1, 1.0, True, None]}]}}]}


def test_encoder_with_recursive_union_in_dataclass():
    encoder = BasicEncoder(MyClass)
    assert encoder.encode(
        MyClass(
            x="x", y={"x": [{"x": {"x": [{"x": ["x", 1, 1.0, True, None]}]}}]}
        )
    ) == {
        "x": "x",
        "y": {"x": [{"x": {"x": [{"x": ["x", 1, 1.0, True, None]}]}}]},
    }


def test_decoder_with_recursive_union():
    decoder = BasicDecoder(JSON)
    assert decoder.decode(
        {"x": [{"x": {"x": [{"x": ["x", 1, 1.0, True, None]}]}}]}
    ) == {"x": [{"x": {"x": [{"x": ["x", 1, 1.0, True, None]}]}}]}


def test_decoder_with_recursive_union_in_dataclass():
    decoder = BasicDecoder(MyClass)
    assert decoder.decode(
        {
            "x": "x",
            "y": {"x": [{"x": {"x": [{"x": ["x", 1, 1.0, True, None]}]}}]},
        }
    ) == MyClass(
        x="x", y={"x": [{"x": {"x": [{"x": ["x", 1, 1.0, True, None]}]}}]}
    )


def test_dataclass_dict_mixin_with_recursive_union():
    @dataclass
    class MyClassWithMixin(DataClassDictMixin):
        x: str
        y: JSON

    assert MyClassWithMixin(
        x="x", y={"x": [{"x": {"x": [{"x": ["x", 1, 1.0, True, None]}]}}]}
    ).to_dict() == {
        "x": "x",
        "y": {"x": [{"x": {"x": [{"x": ["x", 1, 1.0, True, None]}]}}]},
    }
    assert MyClassWithMixin.from_dict(
        {
            "x": "x",
            "y": {"x": [{"x": {"x": [{"x": ["x", 1, 1.0, True, None]}]}}]},
        }
    ) == MyClassWithMixin(
        x="x", y={"x": [{"x": {"x": [{"x": ["x", 1, 1.0, True, None]}]}}]}
    )