-
Notifications
You must be signed in to change notification settings - Fork 107
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
arne.vanlondersele
committed
Jan 12, 2025
1 parent
a89bc16
commit 2499f24
Showing
1 changed file
with
67 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
from dataclasses import dataclass | ||
from typing import Generic, List, TypeVar | ||
from dacite import from_dict | ||
|
||
T = TypeVar("T") | ||
U = TypeVar("U") | ||
|
||
|
||
@dataclass | ||
class X: | ||
a: str | ||
|
||
|
||
@dataclass | ||
class A(Generic[T, U]): | ||
x: T | ||
y: List[U] | ||
|
||
|
||
def test_multi_generic(): | ||
data = { | ||
"x": { | ||
"a": "foo", | ||
}, | ||
"y": [1, 2, 3], | ||
} | ||
|
||
result = from_dict(data_class=A[X, int], data=data) | ||
|
||
assert result == A(x=X(a="foo"), y=[1, 2, 3]) | ||
|
||
|
||
def test_inherited_generic(): | ||
@dataclass | ||
class B(A[X, int]): | ||
z: str | ||
|
||
data = { | ||
"x": { | ||
"a": "foo", | ||
}, | ||
"y": [1, 2, 3], | ||
"z": "bar", | ||
} | ||
|
||
result = from_dict(data_class=B, data=data) | ||
|
||
assert result == B(x=X(a="foo"), y=[1, 2, 3], z="bar") | ||
|
||
|
||
def test_generic_field(): | ||
@dataclass | ||
class C: | ||
z: A[X, int] | ||
|
||
data = { | ||
"z": { | ||
"x": { | ||
"a": "foo", | ||
}, | ||
"y": [1, 2, 3], | ||
} | ||
} | ||
|
||
result = from_dict(data_class=C, data=data) | ||
|
||
assert result == C(z=A(x=X(a="foo"), y=[1, 2, 3])) |