Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions Lib/test/test_xml_etree.py
Original file line number Diff line number Diff line change
Expand Up @@ -3336,6 +3336,51 @@ def __iter__(self):
e.extend([ET.Element(f'c{i}') for i in range(10)])
e[:] = V()

def test_treebuilder_data(self):
# single data() call: pass the string object
b = ET.TreeBuilder()
b.start('root', {})
b.data('ABCD')
b.end('root')
elem = b.close()
self.assertEqual(elem.text, 'ABCD')

# two data() calls: join the two strings
b = ET.TreeBuilder()
b.start('root', {})
b.data('ABCD')
b.data('EFGH')
b.end('root')
elem = b.close()
self.assertEqual(elem.text, 'ABCDEFGH')

def test_treebuilder_data_wrong_types(self):
for obj in (b'bytes', 123, 1.0):
# single data() call
try:
b = ET.TreeBuilder()
b.start('tag', {})
b.data(obj)
b.end('tag')
except TypeError:
# Python implementation raises TypeError,
# C implementation doesn't.
pass
else:
elem = b.close()
self.assertEqual(elem.text, obj)

# two data() calls
errmsg = f'expected str instance, {type(obj).__name__} found'
with self.assertRaisesRegex(TypeError, errmsg):
b = ET.TreeBuilder()
b.start('tag', {})
b.data(obj)
b.data(obj)
b.end('tag')
elem = b.close()
_ = elem.text

def test_treebuilder_start(self):
# Issue #27863
def element_factory(x, y):
Expand Down
12 changes: 1 addition & 11 deletions Modules/_elementtree.c
Original file line number Diff line number Diff line change
Expand Up @@ -2935,17 +2935,7 @@ treebuilder_handle_data(TreeBuilderObject* self, PyObject* data)
self->data = Py_NewRef(data);
} else {
/* more than one item; use a list to collect items */
if (PyBytes_CheckExact(self->data)
&& _PyObject_IsUniquelyReferenced(self->data)
&& PyBytes_CheckExact(data) && PyBytes_GET_SIZE(data) == 1) {
/* XXX this code path unused in Python 3? */
/* expat often generates single character data sections; handle
the most common case by resizing the existing string... */
Py_ssize_t size = PyBytes_GET_SIZE(self->data);
if (_PyBytes_Resize(&self->data, size + 1) < 0)
return NULL;
PyBytes_AS_STRING(self->data)[size] = PyBytes_AS_STRING(data)[0];
} else if (PyList_CheckExact(self->data)) {
if (PyList_CheckExact(self->data)) {
if (PyList_Append(self->data, data) < 0)
return NULL;
} else {
Expand Down
Loading