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
|