Skip to content

Commit 764bfd4

Browse files
committed
Make sure inline list cannot be created for complex types.
1 parent bb807f7 commit 764bfd4

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

pydantic_xml/serializers.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,15 @@ class HomogeneousSerializerFactory:
559559
"""
560560

561561
class TextSerializer(Serializer):
562+
def __init__(
563+
self, model: Type['pxml.BaseXmlModel'], model_field: pd.fields.ModelField, ctx: Serializer.Context,
564+
):
565+
assert len(model_field.sub_fields) == 1
566+
if issubclass(model_field.type_, pxml.BaseXmlModel):
567+
raise errors.ModelFieldError(
568+
model.__name__, model_field.name, "Inline list value should be of scalar type",
569+
)
570+
562571
def serialize(
563572
self, element: etree.Element, value: Any, *, encoder: XmlEncoder, skip_empty: bool = False,
564573
) -> Optional[etree.Element]:
@@ -570,10 +579,7 @@ def serialize(
570579
return element
571580

572581
def deserialize(self, element: etree.Element) -> Optional[List[Any]]:
573-
return [
574-
value
575-
for value in element.text.split()
576-
]
582+
return [value for value in element.text.split()]
577583

578584
class ElementSerializer(Serializer):
579585
def __init__(
@@ -650,7 +656,7 @@ def build(
650656
if field_location is Location.ELEMENT:
651657
return cls.ElementSerializer(model, model_field, ctx)
652658
elif field_location is Location.MISSING:
653-
return cls.TextSerializer()
659+
return cls.TextSerializer(model, model_field, ctx)
654660
elif field_location is Location.ATTRIBUTE:
655661
raise errors.ModelFieldError(
656662
model.__name__, model_field.name, "attributes of collection type are not supported",

tests/test_homogeneous_collections.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,3 +175,10 @@ class TestSubModel(BaseXmlModel):
175175

176176
class TestModel(BaseXmlModel):
177177
__root__: List[TestSubModel]
178+
179+
with pytest.raises(errors.ModelFieldError):
180+
class TestSubModel(BaseXmlModel):
181+
attr: int
182+
183+
class TestModel(BaseXmlModel):
184+
text: List[TestSubModel]

0 commit comments

Comments
 (0)