Skip to content

Commit 1de8fc3

Browse files
[3.13] gh-135640: Adds more type checking to ElementTree (GH-135643) (GH-136226)
(cherry picked from commit e0245c7) Co-authored-by: Kira <[email protected]>
1 parent d80df8c commit 1de8fc3

File tree

3 files changed

+39
-2
lines changed

3 files changed

+39
-2
lines changed

Lib/test/test_xml_etree.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,33 @@ class ElementTreeTest(unittest.TestCase):
218218
def serialize_check(self, elem, expected):
219219
self.assertEqual(serialize(elem), expected)
220220

221+
def test_constructor(self):
222+
# Test constructor behavior.
223+
224+
with self.assertRaises(TypeError):
225+
tree = ET.ElementTree("")
226+
with self.assertRaises(TypeError):
227+
tree = ET.ElementTree(ET.ElementTree())
228+
229+
def test_setroot(self):
230+
# Test _setroot behavior.
231+
232+
tree = ET.ElementTree()
233+
element = ET.Element("tag")
234+
tree._setroot(element)
235+
self.assertEqual(tree.getroot().tag, "tag")
236+
self.assertEqual(tree.getroot(), element)
237+
238+
# Test behavior with an invalid root element
239+
240+
tree = ET.ElementTree()
241+
with self.assertRaises(TypeError):
242+
tree._setroot("")
243+
with self.assertRaises(TypeError):
244+
tree._setroot(ET.ElementTree())
245+
with self.assertRaises(TypeError):
246+
tree._setroot(None)
247+
221248
def test_interface(self):
222249
# Test element tree interface.
223250

Lib/xml/etree/ElementTree.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -523,7 +523,9 @@ class ElementTree:
523523
524524
"""
525525
def __init__(self, element=None, file=None):
526-
# assert element is None or iselement(element)
526+
if element is not None and not iselement(element):
527+
raise TypeError('expected an Element, not %s' %
528+
type(element).__name__)
527529
self._root = element # first node
528530
if file:
529531
self.parse(file)
@@ -539,7 +541,9 @@ def _setroot(self, element):
539541
with the given element. Use with care!
540542
541543
"""
542-
# assert iselement(element)
544+
if not iselement(element):
545+
raise TypeError('expected an Element, not %s'
546+
% type(element).__name__)
543547
self._root = element
544548

545549
def parse(self, source, parser=None):
@@ -705,6 +709,8 @@ def write(self, file_or_filename,
705709
of start/end tags
706710
707711
"""
712+
if self._root is None:
713+
raise TypeError('ElementTree not initialized')
708714
if not method:
709715
method = "xml"
710716
elif method not in _serialize:
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Address bug where it was possible to call
2+
:func:`xml.etree.ElementTree.ElementTree.write` on an ElementTree object with
3+
an invalid root element. This behavior blanked the file passed to ``write``
4+
if it already existed.

0 commit comments

Comments
 (0)