Skip to content

Commit

Permalink
unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
arne.vanlondersele committed Jan 12, 2025
1 parent a89bc16 commit deb629e
Show file tree
Hide file tree
Showing 3 changed files with 117 additions and 0 deletions.
19 changes: 19 additions & 0 deletions tests/core/test_convert_key.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from dataclasses import dataclass
from dacite import Config, from_dict


def test_convert_key():
def to_camel_case(key: str) -> str:
first_part, *remaining_parts = key.split("_")
return first_part + "".join(part.title() for part in remaining_parts)

@dataclass
class Person:
first_name: str
last_name: str

data = {"firstName": "John", "lastName": "Doe"}

result = from_dict(Person, data, Config(convert_key=to_camel_case))

assert result == Person(first_name="John", last_name="Doe")
31 changes: 31 additions & 0 deletions tests/core/test_forward_reference.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from dataclasses import dataclass
from typing import List, Optional
from dacite import from_dict


@dataclass
class Person:
name: str
children: Optional[List["Person"]] = None


@dataclass
class Club:
name: str
members: list["Person"]


def test_self_reference():
data = {"name": "John Doe", "children": [{"name": "Jane Doe"}]}

result = from_dict(Person, data)

assert result == Person(name="John Doe", children=[Person(name="Jane Doe")])


def test_other_reference():
data = {"name": "FooBar", "members": [{"name": "John Doe", "children": [{"name": "Jane Doe"}]}]}

result = from_dict(Club, data)

assert result == Club(name="FooBar", members=[Person(name="John Doe", children=[Person(name="Jane Doe")])])
67 changes: 67 additions & 0 deletions tests/core/test_generics.py
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]))

0 comments on commit deb629e

Please sign in to comment.