From eb2678e0c78381e5a0c1645ecfb7e296e26d7171 Mon Sep 17 00:00:00 2001 From: Daniel Mach Date: Wed, 17 Apr 2024 10:33:08 +0200 Subject: [PATCH] Fix XmlModel to load an empty string in an int field as None --- osc/util/models.py | 2 ++ tests/test_models_xmlmodel.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/osc/util/models.py b/osc/util/models.py index 0777b535..be41e5b9 100644 --- a/osc/util/models.py +++ b/osc/util/models.py @@ -594,6 +594,8 @@ class XmlModel(BaseModel): return value if field.origin_type is int: + if not value or not value.strip(): + return None value = int(value) return value diff --git a/tests/test_models_xmlmodel.py b/tests/test_models_xmlmodel.py index 665db5e2..4f63a0e4 100644 --- a/tests/test_models_xmlmodel.py +++ b/tests/test_models_xmlmodel.py @@ -185,6 +185,38 @@ class TestXmlModel(unittest.TestCase): self.assertEqual(m.child[1]._apiurl, apiurl) self.assertEqual(m.child[2]._apiurl, apiurl) + def test_empty_int_optional(self): + class TestModel(XmlModel): + XML_TAG = "model" + num_attr: Optional[int] = Field(xml_attribute=True) + num_elem: Optional[int] = Field() + + data = textwrap.dedent( + """ + + + + """ + ).strip() + m = TestModel.from_string(data) + self.assertEqual(m.num_attr, None) + self.assertEqual(m.num_elem, None) + + def test_empty_int(self): + class TestModel(XmlModel): + XML_TAG = "model" + num_attr: int = Field(xml_attribute=True) + num_elem: int = Field() + + data = textwrap.dedent( + """ + + + + """ + ).strip() + self.assertRaises(TypeError, TestModel.from_string, data) + if __name__ == "__main__": unittest.main()