Skip to content

Commit

Permalink
Fix NiklasRosenstein#66: dataclass from Generic now serializes
Browse files Browse the repository at this point in the history
  • Loading branch information
rhaps0dy committed May 10, 2024
1 parent 572c79c commit 71b136f
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changelog/_unreleased.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[[entries]]
id = "693674ea-b2b2-4733-bce6-4d5bae59b164"
type = "fix"
description = "Fix #66: dataclasses inheriting from uninstantiated Generic did not get all their fields serialized"
author = "@rhaps0dy"
2 changes: 1 addition & 1 deletion databind/src/databind/core/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ class A(Generic[T]):
pass

# Continue with the base classes.
for base in hint.bases or hint.type.__bases__:
for base in (*hint.bases, *hint.type.__bases__):
base_hint = TypeHint(base, source=hint.type).evaluate().parameterize(parameter_map)
assert isinstance(base_hint, ClassTypeHint), f"nani? {base_hint}"
if dataclasses.is_dataclass(base_hint.type):
Expand Down
22 changes: 22 additions & 0 deletions databind/src/databind/core/tests/schema_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,3 +456,25 @@ def test_parse_dataclass_with_forward_ref() -> None:
ClassWithForwardRef,
ClassWithForwardRef,
)

T = t.TypeVar("T")

@dataclasses.dataclass
class GenericClass(t.Generic[T]):
a_field: int


@dataclasses.dataclass
class InheritGeneric(GenericClass):
b_field: str


def test_schema_generic_dataclass() -> None:
"""Regression test for #66: dataclasses inheriting from Generic with an uninstantiated TypeVar don't get their
parents' fields.
"""
assert convert_dataclass_to_schema(InheritGeneric) == Schema(
{"a_field": Field(TypeHint(int), True), "b_field": Field(TypeHint(str), True)},
InheritGeneric,
InheritGeneric,
)
22 changes: 22 additions & 0 deletions databind/src/databind/json/tests/converters_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -713,3 +713,25 @@ def of(cls, v: str) -> "MyCls":
mapper = make_mapper([JsonConverterSupport()])
assert mapper.serialize(MyCls(), MyCls) == "MyCls"
assert mapper.deserialize("MyCls", MyCls) == MyCls()


T = t.TypeVar("T")


@dataclasses.dataclass
class GenericClass(t.Generic[T]):
a_field: int


@dataclasses.dataclass
class InheritGeneric(GenericClass):
b_field: str


def test_serialize_generic_dataclass() -> None:
"""Regression test for #66: dataclasses inheriting from Generic with an uninstantiated TypeVar don't get their
parents' fields.
"""
obj = InheritGeneric(2, "hi")
mapper = make_mapper([SchemaConverter(), PlainDatatypeConverter()])
assert mapper.serialize(obj, InheritGeneric) == {"a_field": obj.a_field, "b_field": obj.b_field}

0 comments on commit 71b136f

Please sign in to comment.