Debian Codegraph @

Lib/test/test_xml_etree_c.py

raw
1 # xml.etree test for cElementTree
2 import io
3 import struct
4 from test import support
5 from test.support.import_helper import import_fresh_module
6 import types
7 import unittest
8
9 cET = import_fresh_module('xml.etree.ElementTree',
10 fresh=['_elementtree'])
11 cET_alias = import_fresh_module('xml.etree.cElementTree',
12 fresh=['_elementtree', 'xml.etree'],
13 deprecated=True)
14
15
16 @unittest.skipUnless(cET, 'requires _elementtree')
17 class MiscTests(unittest.TestCase):
18 # Issue #8651.
19 @support.bigmemtest(size=support._2G + 100, memuse=1, dry_run=False)
20 def test_length_overflow(self, size):
21 data = b'x' * size
22 parser = cET.XMLParser()
23 try:
24 self.assertRaises(OverflowError, parser.feed, data)
25 finally:
26 data = None
27
28 def test_del_attribute(self):
29 element = cET.Element('tag')
30
31 element.tag = 'TAG'
32 with self.assertRaises(AttributeError):
33 del element.tag
34 self.assertEqual(element.tag, 'TAG')
35
36 with self.assertRaises(AttributeError):
37 del element.text
38 self.assertIsNone(element.text)
39 element.text = 'TEXT'
40 with self.assertRaises(AttributeError):
41 del element.text
42 self.assertEqual(element.text, 'TEXT')
43
44 with self.assertRaises(AttributeError):
45 del element.tail
46 self.assertIsNone(element.tail)
47 element.tail = 'TAIL'
48 with self.assertRaises(AttributeError):
49 del element.tail
50 self.assertEqual(element.tail, 'TAIL')
51
52 with self.assertRaises(AttributeError):
53 del element.attrib
54 self.assertEqual(element.attrib, {})
55 element.attrib = {'A': 'B', 'C': 'D'}
56 with self.assertRaises(AttributeError):
57 del element.attrib
58 self.assertEqual(element.attrib, {'A': 'B', 'C': 'D'})
59
60 @support.skip_wasi_stack_overflow()
61 @support.skip_emscripten_stack_overflow()
62 def test_trashcan(self):
63 # If this test fails, it will most likely die via segfault.
64 e = root = cET.Element('root')
65 for i in range(200000):
66 e = cET.SubElement(e, 'x')
67 del e
68 del root
69 support.gc_collect()
70
71 def test_parser_ref_cycle(self):
72 # bpo-31499: xmlparser_dealloc() crashed with a segmentation fault when
73 # xmlparser_gc_clear() was called previously by the garbage collector,
74 # when the parser was part of a reference cycle.
75
76 def parser_ref_cycle():
77 parser = cET.XMLParser()
78 # Create a reference cycle using an exception to keep the frame
79 # alive, so the parser will be destroyed by the garbage collector
80 try:
81 raise ValueError
82 except ValueError as exc:
83 err = exc
84
85 # Create a parser part of reference cycle
86 parser_ref_cycle()
87 # Trigger an explicit garbage collection to break the reference cycle
88 # and so destroy the parser
89 support.gc_collect()
90
91 def test_bpo_31728(self):
92 # A crash or an assertion failure shouldn't happen, in case garbage
93 # collection triggers a call to clear() or a reading of text or tail,
94 # while a setter or clear() or __setstate__() is already running.
95 elem = cET.Element('elem')
96 class X:
97 def __del__(self):
98 elem.text
99 elem.tail
100 elem.clear()
101
102 elem.text = X()
103 elem.clear() # shouldn't crash
104
105 elem.tail = X()
106 elem.clear() # shouldn't crash
107
108 elem.text = X()
109 elem.text = X() # shouldn't crash
110 elem.clear()
111
112 elem.tail = X()
113 elem.tail = X() # shouldn't crash
114 elem.clear()
115
116 elem.text = X()
117 elem.__setstate__({'tag': 42}) # shouldn't cause an assertion failure
118 elem.clear()
119
120 elem.tail = X()
121 elem.__setstate__({'tag': 42}) # shouldn't cause an assertion failure
122
123 @support.cpython_only
124 def test_uninitialized_parser(self):
125 # The interpreter shouldn't crash in case of calling methods or
126 # accessing attributes of uninitialized XMLParser objects.
127 parser = cET.XMLParser.__new__(cET.XMLParser)
128 self.assertRaises(ValueError, parser.close)
129 self.assertRaises(ValueError, parser.feed, 'foo')
130 class MockFile:
131 def read(*args):
132 return ''
133 self.assertRaises(ValueError, parser._parse_whole, MockFile())
134 self.assertRaises(ValueError, parser._setevents, None)
135 self.assertIsNone(parser.entity)
136 self.assertIsNone(parser.target)
137
138 def test_setstate_leaks(self):
139 # Test reference leaks
140 elem = cET.Element.__new__(cET.Element)
141 for i in range(100):
142 elem.__setstate__({'tag': 'foo', 'attrib': {'bar': 42},
143 '_children': [cET.Element('child')],
144 'text': 'text goes here',
145 'tail': 'opposite of head'})
146
147 self.assertEqual(elem.tag, 'foo')
148 self.assertEqual(elem.text, 'text goes here')
149 self.assertEqual(elem.tail, 'opposite of head')
150 self.assertEqual(list(elem.attrib.items()), [('bar', 42)])
151 self.assertEqual(len(elem), 1)
152 self.assertEqual(elem[0].tag, 'child')
153
154 def test_iterparse_leaks(self):
155 # Test reference leaks in TreeBuilder (issue #35502).
156 # The test is written to be executed in the hunting reference leaks
157 # mode.
158 XML = '<a></a></b>'
159 parser = cET.iterparse(io.StringIO(XML))
160 next(parser)
161 del parser
162 support.gc_collect()
163
164 def test_xmlpullparser_leaks(self):
165 # Test reference leaks in TreeBuilder (issue #35502).
166 # The test is written to be executed in the hunting reference leaks
167 # mode.
168 XML = '<a></a></b>'
169 parser = cET.XMLPullParser()
170 parser.feed(XML)
171 del parser
172 support.gc_collect()
173
174 def test_dict_disappearing_during_get_item(self):
175 # test fix for seg fault reported in issue 27946
176 class X:
177 def __hash__(self):
178 e.attrib = {} # this frees e->extra->attrib
179 [{i: i} for i in range(1000)] # exhaust the dict keys cache
180 return 13
181
182 e = cET.Element("elem", {1: 2})
183 r = e.get(X())
184 self.assertIsNone(r)
185
186 @support.cpython_only
187 def test_immutable_types(self):
188 root = cET.fromstring('<a></a>')
189 dataset = (
190 cET.Element,
191 cET.TreeBuilder,
192 cET.XMLParser,
193 type(root.iter()),
194 )
195 for tp in dataset:
196 with self.subTest(tp=tp):
197 with self.assertRaisesRegex(TypeError, "immutable"):
198 tp.foo = 1
199
200 @support.cpython_only
201 def test_disallow_instantiation(self):
202 root = cET.fromstring('<a></a>')
203 iter_type = type(root.iter())
204 support.check_disallow_instantiation(self, iter_type)
205
206
207 @unittest.skipUnless(cET, 'requires _elementtree')
208 class TestAliasWorking(unittest.TestCase):
209 # Test that the cET alias module is alive
210 def test_alias_working(self):
211 e = cET_alias.Element('foo')
212 self.assertEqual(e.tag, 'foo')
213
214
215 @unittest.skipUnless(cET, 'requires _elementtree')
216 @support.cpython_only
217 class TestAcceleratorImported(unittest.TestCase):
218 # Test that the C accelerator was imported, as expected
219 def test_correct_import_cET(self):
220 # SubElement is a function so it retains _elementtree as its module.
221 self.assertEqual(cET.SubElement.__module__, '_elementtree')
222
223 def test_correct_import_cET_alias(self):
224 self.assertEqual(cET_alias.SubElement.__module__, '_elementtree')
225
226 def test_parser_comes_from_C(self):
227 # The type of methods defined in Python code is types.FunctionType,
228 # while the type of methods defined inside _elementtree is
229 # <class 'wrapper_descriptor'>
230 self.assertNotIsInstance(cET.Element.__init__, types.FunctionType)
231
232
233 @unittest.skipUnless(cET, 'requires _elementtree')
234 @support.cpython_only
235 class SizeofTest(unittest.TestCase):
236 def setUp(self):
237 self.elementsize = support.calcobjsize('5P')
238 # extra
239 self.extra = struct.calcsize('PnnP4P')
240
241 check_sizeof = support.check_sizeof
242
243 def test_element(self):
244 e = cET.Element('a')
245 self.check_sizeof(e, self.elementsize)
246
247 def test_element_with_attrib(self):
248 e = cET.Element('a', href='about:')
249 self.check_sizeof(e, self.elementsize + self.extra)
250
251 def test_element_with_children(self):
252 e = cET.Element('a')
253 for i in range(5):
254 cET.SubElement(e, 'span')
255 # should have space for 8 children now
256 self.check_sizeof(e, self.elementsize + self.extra +
257 struct.calcsize('8P'))
258
259
260 def install_tests():
261 # Test classes should have __module__ referring to this module.
262 from test import test_xml_etree
263 for name, base in vars(test_xml_etree).items():
264 if isinstance(base, type) and issubclass(base, unittest.TestCase):
265 class Temp(base):
266 pass
267 Temp.__name__ = Temp.__qualname__ = name
268 Temp.__module__ = __name__
269 assert name not in globals()
270 globals()[name] = Temp
271
272 install_tests()
273
274 def setUpModule():
275 from test import test_xml_etree
276 test_xml_etree.setUpModule(module=cET)
277
278
279 if __name__ == '__main__':
280 unittest.main()