File: test_init_var.py

package info (click to toggle)
dacite 1.9.2-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 332 kB
  • sloc: python: 1,870; makefile: 8
file content (52 lines) | stat: -rw-r--r-- 1,086 bytes parent folder | download | duplicates (3)
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
from dataclasses import dataclass, InitVar, field

from dacite import from_dict, Config
from tests.common import init_var_type_support


def test_from_dict_with_init_var():
    @dataclass
    class X:
        a: InitVar[int]
        b: int = field(init=False)

        def __post_init__(self, a: int) -> None:
            self.b = 2 * a

    result = from_dict(X, {"a": 2})

    assert result.b == 4


@init_var_type_support
def test_from_dict_with_init_var_and_data_class():
    @dataclass
    class X:
        i: int

    @dataclass
    class Y:
        a: InitVar[X]
        b: X = field(init=False)

        def __post_init__(self, a: X) -> None:
            self.b = X(i=2 * a.i)

    result = from_dict(Y, {"a": {"i": 2}})

    assert result.b == X(i=4)


@init_var_type_support
def test_from_dict_with_init_var_and_cast():
    @dataclass
    class X:
        a: InitVar[int]
        b: int = field(init=False)

        def __post_init__(self, a: int) -> None:
            self.b = 2 * a

    result = from_dict(X, {"a": "2"}, config=Config(cast=[int]))

    assert result.b == 4