Skip to content

Commit

Permalink
fix: Derived element json serialization (tefra#1035)
Browse files Browse the repository at this point in the history
  • Loading branch information
tefra authored and skinkie committed Jun 18, 2024
1 parent bcbee9a commit 47fe6b4
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
21 changes: 21 additions & 0 deletions tests/formats/dataclass/serializers/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from tests.fixtures.books import BookForm, Books
from tests.fixtures.datatypes import Telephone
from tests.fixtures.wrapper import Wrapper
from xsdata.formats.dataclass.models.generics import AnyElement, DerivedElement
from xsdata.formats.dataclass.serializers import DictEncoder, DictFactory
from xsdata.models.datatype import XmlDate
from xsdata.models.xsd import Attribute
Expand Down Expand Up @@ -107,3 +108,23 @@ def test_next_value(self):
expected = expected[:-1]
actual = [name for name, value in self.encoder.next_value(book)]
self.assertEqual(expected, actual)

def test_generics(self):
self.obj = AnyElement(
children=[
AnyElement(qname="foo", text="bar"),
DerivedElement(qname="bar", value="1"),
DerivedElement(qname="bar", value=2),
]
)
result = self.encoder.encode(self.obj)
expected = {
"attributes": {},
"children": [
{"attributes": {}, "children": [], "qname": "foo", "text": "bar"},
{"qname": "bar", "value": "1"},
{"qname": "bar", "value": 2},
],
}

self.assertEqual(expected, result)
2 changes: 1 addition & 1 deletion xsdata/formats/dataclass/models/generics.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class AnyElement:
class DerivedElement(Generic[T]):
"""Generic model wrapper for type substituted elements.
Example: eg. <b xsi:type="a">...</b>
Example: e.g. <b xsi:type="a">...</b>
Args:
qname: The element's qualified name
Expand Down
6 changes: 6 additions & 0 deletions xsdata/formats/dataclass/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
Optional,
Tuple,
Type,
TypeVar,
Union,
)

Expand Down Expand Up @@ -152,6 +153,11 @@ def evaluate_attributes(annotation: Any, **_: Any) -> Result:

def evaluate_element(annotation: Any, tokens: bool = False) -> Result:
"""Validate annotations for a xml element."""

# Only the derived element value field is allowed a typevar
if isinstance(annotation, TypeVar) and annotation.__bound__ is object:
annotation = object

types = (annotation,)
origin = get_origin(annotation)
args = get_args(annotation)
Expand Down

0 comments on commit 47fe6b4

Please sign in to comment.