Repository navigation
gh-161807: Fix ElementTree find*/iterfind with empty path - #161916
ramondomiingos wants to merge 2 commits into
Conversation
`ElementPath.iterfind()` used a bare `return` when the tokenizer produced no tokens (empty path string), which returned `None` instead of an iterator. This caused `find()`, `findall()`, `findtext()`, and `iterfind()` to raise `TypeError` when called with an empty path. Changed `return` to `return iter(())` so that an empty path yields an empty iterator, consistent with a path that simply matches nothing.
aozmekik
left a comment
There was a problem hiding this comment.
Checked both implementations. On main the C accelerator already returned None, [] and the default for find(""), findall("") and findtext("", "d") (only iterfind("") raised), while the pure-Python module raised TypeError for all four. With this branch both give None, [], 'd' and [], so the Python version now matches what C did and iterfind is fixed for both. test_xml_etree and test_xml_etree_c pass.
| ns = {"ns": "http://example.com"} | ||
| self.assertIsNone(e.find("", ns)) | ||
| self.assertEqual(e.findall("", ns), []) | ||
| self.assertIsNone(e.findtext("", namespaces=ns)) |
There was a problem hiding this comment.
Plese check that the namespace is never altered as well.
| tree = ET.ElementTree(e) | ||
| self.assertIsNone(tree.find("")) | ||
| self.assertEqual(tree.findall(""), []) | ||
| self.assertIsNone(tree.findtext("")) |
There was a problem hiding this comment.
Do we have a default to check? if so, please test the exact same interface by parametrizing over the object invoking the methods: create a do_test_find_empty_path(self, m) method which takes a compatible object exposing the methods you'll test and then do self.do_test_find_empty_path(e) followed by self.do_test_find_empty_path(ET.ElementTree(e)).
| @@ -0,0 +1,6 @@ | |||
| Fix :func:`xml.etree.ElementTree.Element.find`, | |||
There was a problem hiding this comment.
This is only for the pure Python implementation, so please say it or say that it aligns with the C implementation.
… helper Add do_test_find_empty_path(m) so both Element and ElementTree are exercised with the same assertions. Also verify that the namespace dict is not mutated by any of the find*/iterfind calls, and add a comment noting that the test covers the pure-Python implementation – after the fix it matches what the C accelerator already returned.
Summary
ElementPath.iterfind()uses a barereturnwhen the XPath tokenizer produces no tokens (empty path string), which returnsNoneinstead of an iterator. This causesfind(),findall(),findtext(), anditerfind()to raiseTypeErrorwhen called with an empty path.Reproducer:
Fix
Changed the bare
returniniterfind()toreturn iter(()), so an empty path yields an empty iterator — consistent with a path that simply matches nothing.Tests
Added
test_find_empty_pathcoveringfind(""),findall(""),findtext(""), anditerfind(""):ElementTree(not justElement)findtextwith default value