diff --git a/CHANGELOG.rst b/CHANGELOG.rst index e494c4e..403df19 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,11 @@ Changelog ========= +0.6.2 (2023-06-10) +------------------ + +- piped union typehints support added. See https://github.com/dapper91/pydantic-xml/issues/56 + 0.6.1 (2023-04-15) ------------------ diff --git a/docs/source/pages/quickstart.rst b/docs/source/pages/quickstart.rst index e2e7c78..c1ea798 100644 --- a/docs/source/pages/quickstart.rst +++ b/docs/source/pages/quickstart.rst @@ -186,7 +186,7 @@ For more information see :ref:`wrapped entities bool: def is_union(type_: Any) -> bool: - return typing.get_origin(type_) is Union + return typing.get_origin(type_) in UnionTypes def is_optional(type_: Any) -> bool: diff --git a/pyproject.toml b/pyproject.toml index 9bbbdcd..e12a283 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "pydantic-xml" -version = "0.6.1" +version = "0.6.2" description = "pydantic xml extension" authors = ["Dmitry Pershin "] license = "Unlicense" diff --git a/tests/test_unions.py b/tests/test_unions.py index 9103f26..b6bea48 100644 --- a/tests/test_unions.py +++ b/tests/test_unions.py @@ -1,3 +1,4 @@ +import sys from typing import List, Tuple, Union import pytest @@ -156,3 +157,61 @@ class SubModel(BaseXmlModel): class TestModel(BaseXmlModel): field1: Union[int, SubModel] + + +@pytest.mark.skipif(sys.version_info < (3, 10), reason="requires python 3.10 and above") +def test_union_type(): + class TestModel(BaseXmlModel, tag='model'): + text: int | float | str + + xml = ''' + text + ''' + + actual_obj = TestModel.from_xml(xml) + expected_obj = TestModel(text='text') + + assert actual_obj == expected_obj + + actual_xml = actual_obj.to_xml() + assert_xml_equal(actual_xml, xml) + + +@pytest.mark.skipif(sys.version_info < (3, 10), reason="requires python 3.10 and above") +def test_model_union_type(): + class SubModel1(BaseXmlModel, tag='model1'): + attr1: int = attr() + + class SubModel2(BaseXmlModel, tag='model2'): + text: float + + class TestModel(BaseXmlModel, tag='model'): + field1: SubModel1 | SubModel2 = element() + + xml = ''' + + ''' + + actual_obj = TestModel.from_xml(xml) + expected_obj = TestModel( + field1=SubModel1(attr1=1), + ) + + assert actual_obj == expected_obj + + actual_xml = actual_obj.to_xml() + assert_xml_equal(actual_xml, xml) + + xml = ''' + inf + ''' + + actual_obj = TestModel.from_xml(xml) + expected_obj = TestModel( + field1=SubModel2(text=float('inf')), + ) + + assert actual_obj == expected_obj + + actual_xml = actual_obj.to_xml() + assert_xml_equal(actual_xml, xml)