1 | n/a | # IMPORTANT: the same tests are run from "test_xml_etree_c" in order |
---|
2 | n/a | # to ensure consistency between the C implementation and the Python |
---|
3 | n/a | # implementation. |
---|
4 | n/a | # |
---|
5 | n/a | # For this purpose, the module-level "ET" symbol is temporarily |
---|
6 | n/a | # monkey-patched when running the "test_xml_etree_c" test suite. |
---|
7 | n/a | |
---|
8 | n/a | import copy |
---|
9 | n/a | import html |
---|
10 | n/a | import io |
---|
11 | n/a | import operator |
---|
12 | n/a | import pickle |
---|
13 | n/a | import sys |
---|
14 | n/a | import types |
---|
15 | n/a | import unittest |
---|
16 | n/a | import warnings |
---|
17 | n/a | import weakref |
---|
18 | n/a | |
---|
19 | n/a | from itertools import product |
---|
20 | n/a | from test import support |
---|
21 | n/a | from test.support import TESTFN, findfile, import_fresh_module, gc_collect, swap_attr |
---|
22 | n/a | |
---|
23 | n/a | # pyET is the pure-Python implementation. |
---|
24 | n/a | # |
---|
25 | n/a | # ET is pyET in test_xml_etree and is the C accelerated version in |
---|
26 | n/a | # test_xml_etree_c. |
---|
27 | n/a | pyET = None |
---|
28 | n/a | ET = None |
---|
29 | n/a | |
---|
30 | n/a | SIMPLE_XMLFILE = findfile("simple.xml", subdir="xmltestdata") |
---|
31 | n/a | try: |
---|
32 | n/a | SIMPLE_XMLFILE.encode("utf-8") |
---|
33 | n/a | except UnicodeEncodeError: |
---|
34 | n/a | raise unittest.SkipTest("filename is not encodable to utf8") |
---|
35 | n/a | SIMPLE_NS_XMLFILE = findfile("simple-ns.xml", subdir="xmltestdata") |
---|
36 | n/a | |
---|
37 | n/a | SAMPLE_XML = """\ |
---|
38 | n/a | <body> |
---|
39 | n/a | <tag class='a'>text</tag> |
---|
40 | n/a | <tag class='b' /> |
---|
41 | n/a | <section> |
---|
42 | n/a | <tag class='b' id='inner'>subtext</tag> |
---|
43 | n/a | </section> |
---|
44 | n/a | </body> |
---|
45 | n/a | """ |
---|
46 | n/a | |
---|
47 | n/a | SAMPLE_SECTION = """\ |
---|
48 | n/a | <section> |
---|
49 | n/a | <tag class='b' id='inner'>subtext</tag> |
---|
50 | n/a | <nexttag /> |
---|
51 | n/a | <nextsection> |
---|
52 | n/a | <tag /> |
---|
53 | n/a | </nextsection> |
---|
54 | n/a | </section> |
---|
55 | n/a | """ |
---|
56 | n/a | |
---|
57 | n/a | SAMPLE_XML_NS = """ |
---|
58 | n/a | <body xmlns="http://effbot.org/ns"> |
---|
59 | n/a | <tag>text</tag> |
---|
60 | n/a | <tag /> |
---|
61 | n/a | <section> |
---|
62 | n/a | <tag>subtext</tag> |
---|
63 | n/a | </section> |
---|
64 | n/a | </body> |
---|
65 | n/a | """ |
---|
66 | n/a | |
---|
67 | n/a | SAMPLE_XML_NS_ELEMS = """ |
---|
68 | n/a | <root> |
---|
69 | n/a | <h:table xmlns:h="hello"> |
---|
70 | n/a | <h:tr> |
---|
71 | n/a | <h:td>Apples</h:td> |
---|
72 | n/a | <h:td>Bananas</h:td> |
---|
73 | n/a | </h:tr> |
---|
74 | n/a | </h:table> |
---|
75 | n/a | |
---|
76 | n/a | <f:table xmlns:f="foo"> |
---|
77 | n/a | <f:name>African Coffee Table</f:name> |
---|
78 | n/a | <f:width>80</f:width> |
---|
79 | n/a | <f:length>120</f:length> |
---|
80 | n/a | </f:table> |
---|
81 | n/a | </root> |
---|
82 | n/a | """ |
---|
83 | n/a | |
---|
84 | n/a | ENTITY_XML = """\ |
---|
85 | n/a | <!DOCTYPE points [ |
---|
86 | n/a | <!ENTITY % user-entities SYSTEM 'user-entities.xml'> |
---|
87 | n/a | %user-entities; |
---|
88 | n/a | ]> |
---|
89 | n/a | <document>&entity;</document> |
---|
90 | n/a | """ |
---|
91 | n/a | |
---|
92 | n/a | |
---|
93 | n/a | class ModuleTest(unittest.TestCase): |
---|
94 | n/a | def test_sanity(self): |
---|
95 | n/a | # Import sanity. |
---|
96 | n/a | |
---|
97 | n/a | from xml.etree import ElementTree |
---|
98 | n/a | from xml.etree import ElementInclude |
---|
99 | n/a | from xml.etree import ElementPath |
---|
100 | n/a | |
---|
101 | n/a | def test_all(self): |
---|
102 | n/a | names = ("xml.etree.ElementTree", "_elementtree") |
---|
103 | n/a | support.check__all__(self, ET, names, blacklist=("HTML_EMPTY",)) |
---|
104 | n/a | |
---|
105 | n/a | |
---|
106 | n/a | def serialize(elem, to_string=True, encoding='unicode', **options): |
---|
107 | n/a | if encoding != 'unicode': |
---|
108 | n/a | file = io.BytesIO() |
---|
109 | n/a | else: |
---|
110 | n/a | file = io.StringIO() |
---|
111 | n/a | tree = ET.ElementTree(elem) |
---|
112 | n/a | tree.write(file, encoding=encoding, **options) |
---|
113 | n/a | if to_string: |
---|
114 | n/a | return file.getvalue() |
---|
115 | n/a | else: |
---|
116 | n/a | file.seek(0) |
---|
117 | n/a | return file |
---|
118 | n/a | |
---|
119 | n/a | def summarize_list(seq): |
---|
120 | n/a | return [elem.tag for elem in seq] |
---|
121 | n/a | |
---|
122 | n/a | |
---|
123 | n/a | class ElementTestCase: |
---|
124 | n/a | @classmethod |
---|
125 | n/a | def setUpClass(cls): |
---|
126 | n/a | cls.modules = {pyET, ET} |
---|
127 | n/a | |
---|
128 | n/a | def pickleRoundTrip(self, obj, name, dumper, loader, proto): |
---|
129 | n/a | save_m = sys.modules[name] |
---|
130 | n/a | try: |
---|
131 | n/a | sys.modules[name] = dumper |
---|
132 | n/a | temp = pickle.dumps(obj, proto) |
---|
133 | n/a | sys.modules[name] = loader |
---|
134 | n/a | result = pickle.loads(temp) |
---|
135 | n/a | except pickle.PicklingError as pe: |
---|
136 | n/a | # pyET must be second, because pyET may be (equal to) ET. |
---|
137 | n/a | human = dict([(ET, "cET"), (pyET, "pyET")]) |
---|
138 | n/a | raise support.TestFailed("Failed to round-trip %r from %r to %r" |
---|
139 | n/a | % (obj, |
---|
140 | n/a | human.get(dumper, dumper), |
---|
141 | n/a | human.get(loader, loader))) from pe |
---|
142 | n/a | finally: |
---|
143 | n/a | sys.modules[name] = save_m |
---|
144 | n/a | return result |
---|
145 | n/a | |
---|
146 | n/a | def assertEqualElements(self, alice, bob): |
---|
147 | n/a | self.assertIsInstance(alice, (ET.Element, pyET.Element)) |
---|
148 | n/a | self.assertIsInstance(bob, (ET.Element, pyET.Element)) |
---|
149 | n/a | self.assertEqual(len(list(alice)), len(list(bob))) |
---|
150 | n/a | for x, y in zip(alice, bob): |
---|
151 | n/a | self.assertEqualElements(x, y) |
---|
152 | n/a | properties = operator.attrgetter('tag', 'tail', 'text', 'attrib') |
---|
153 | n/a | self.assertEqual(properties(alice), properties(bob)) |
---|
154 | n/a | |
---|
155 | n/a | # -------------------------------------------------------------------- |
---|
156 | n/a | # element tree tests |
---|
157 | n/a | |
---|
158 | n/a | class ElementTreeTest(unittest.TestCase): |
---|
159 | n/a | |
---|
160 | n/a | def serialize_check(self, elem, expected): |
---|
161 | n/a | self.assertEqual(serialize(elem), expected) |
---|
162 | n/a | |
---|
163 | n/a | def test_interface(self): |
---|
164 | n/a | # Test element tree interface. |
---|
165 | n/a | |
---|
166 | n/a | def check_string(string): |
---|
167 | n/a | len(string) |
---|
168 | n/a | for char in string: |
---|
169 | n/a | self.assertEqual(len(char), 1, |
---|
170 | n/a | msg="expected one-character string, got %r" % char) |
---|
171 | n/a | new_string = string + "" |
---|
172 | n/a | new_string = string + " " |
---|
173 | n/a | string[:0] |
---|
174 | n/a | |
---|
175 | n/a | def check_mapping(mapping): |
---|
176 | n/a | len(mapping) |
---|
177 | n/a | keys = mapping.keys() |
---|
178 | n/a | items = mapping.items() |
---|
179 | n/a | for key in keys: |
---|
180 | n/a | item = mapping[key] |
---|
181 | n/a | mapping["key"] = "value" |
---|
182 | n/a | self.assertEqual(mapping["key"], "value", |
---|
183 | n/a | msg="expected value string, got %r" % mapping["key"]) |
---|
184 | n/a | |
---|
185 | n/a | def check_element(element): |
---|
186 | n/a | self.assertTrue(ET.iselement(element), msg="not an element") |
---|
187 | n/a | direlem = dir(element) |
---|
188 | n/a | for attr in 'tag', 'attrib', 'text', 'tail': |
---|
189 | n/a | self.assertTrue(hasattr(element, attr), |
---|
190 | n/a | msg='no %s member' % attr) |
---|
191 | n/a | self.assertIn(attr, direlem, |
---|
192 | n/a | msg='no %s visible by dir' % attr) |
---|
193 | n/a | |
---|
194 | n/a | check_string(element.tag) |
---|
195 | n/a | check_mapping(element.attrib) |
---|
196 | n/a | if element.text is not None: |
---|
197 | n/a | check_string(element.text) |
---|
198 | n/a | if element.tail is not None: |
---|
199 | n/a | check_string(element.tail) |
---|
200 | n/a | for elem in element: |
---|
201 | n/a | check_element(elem) |
---|
202 | n/a | |
---|
203 | n/a | element = ET.Element("tag") |
---|
204 | n/a | check_element(element) |
---|
205 | n/a | tree = ET.ElementTree(element) |
---|
206 | n/a | check_element(tree.getroot()) |
---|
207 | n/a | element = ET.Element("t\xe4g", key="value") |
---|
208 | n/a | tree = ET.ElementTree(element) |
---|
209 | n/a | self.assertRegex(repr(element), r"^<Element 't\xe4g' at 0x.*>$") |
---|
210 | n/a | element = ET.Element("tag", key="value") |
---|
211 | n/a | |
---|
212 | n/a | # Make sure all standard element methods exist. |
---|
213 | n/a | |
---|
214 | n/a | def check_method(method): |
---|
215 | n/a | self.assertTrue(hasattr(method, '__call__'), |
---|
216 | n/a | msg="%s not callable" % method) |
---|
217 | n/a | |
---|
218 | n/a | check_method(element.append) |
---|
219 | n/a | check_method(element.extend) |
---|
220 | n/a | check_method(element.insert) |
---|
221 | n/a | check_method(element.remove) |
---|
222 | n/a | check_method(element.getchildren) |
---|
223 | n/a | check_method(element.find) |
---|
224 | n/a | check_method(element.iterfind) |
---|
225 | n/a | check_method(element.findall) |
---|
226 | n/a | check_method(element.findtext) |
---|
227 | n/a | check_method(element.clear) |
---|
228 | n/a | check_method(element.get) |
---|
229 | n/a | check_method(element.set) |
---|
230 | n/a | check_method(element.keys) |
---|
231 | n/a | check_method(element.items) |
---|
232 | n/a | check_method(element.iter) |
---|
233 | n/a | check_method(element.itertext) |
---|
234 | n/a | check_method(element.getiterator) |
---|
235 | n/a | |
---|
236 | n/a | # These methods return an iterable. See bug 6472. |
---|
237 | n/a | |
---|
238 | n/a | def check_iter(it): |
---|
239 | n/a | check_method(it.__next__) |
---|
240 | n/a | |
---|
241 | n/a | check_iter(element.iterfind("tag")) |
---|
242 | n/a | check_iter(element.iterfind("*")) |
---|
243 | n/a | check_iter(tree.iterfind("tag")) |
---|
244 | n/a | check_iter(tree.iterfind("*")) |
---|
245 | n/a | |
---|
246 | n/a | # These aliases are provided: |
---|
247 | n/a | |
---|
248 | n/a | self.assertEqual(ET.XML, ET.fromstring) |
---|
249 | n/a | self.assertEqual(ET.PI, ET.ProcessingInstruction) |
---|
250 | n/a | |
---|
251 | n/a | def test_set_attribute(self): |
---|
252 | n/a | element = ET.Element('tag') |
---|
253 | n/a | |
---|
254 | n/a | self.assertEqual(element.tag, 'tag') |
---|
255 | n/a | element.tag = 'Tag' |
---|
256 | n/a | self.assertEqual(element.tag, 'Tag') |
---|
257 | n/a | element.tag = 'TAG' |
---|
258 | n/a | self.assertEqual(element.tag, 'TAG') |
---|
259 | n/a | |
---|
260 | n/a | self.assertIsNone(element.text) |
---|
261 | n/a | element.text = 'Text' |
---|
262 | n/a | self.assertEqual(element.text, 'Text') |
---|
263 | n/a | element.text = 'TEXT' |
---|
264 | n/a | self.assertEqual(element.text, 'TEXT') |
---|
265 | n/a | |
---|
266 | n/a | self.assertIsNone(element.tail) |
---|
267 | n/a | element.tail = 'Tail' |
---|
268 | n/a | self.assertEqual(element.tail, 'Tail') |
---|
269 | n/a | element.tail = 'TAIL' |
---|
270 | n/a | self.assertEqual(element.tail, 'TAIL') |
---|
271 | n/a | |
---|
272 | n/a | self.assertEqual(element.attrib, {}) |
---|
273 | n/a | element.attrib = {'a': 'b', 'c': 'd'} |
---|
274 | n/a | self.assertEqual(element.attrib, {'a': 'b', 'c': 'd'}) |
---|
275 | n/a | element.attrib = {'A': 'B', 'C': 'D'} |
---|
276 | n/a | self.assertEqual(element.attrib, {'A': 'B', 'C': 'D'}) |
---|
277 | n/a | |
---|
278 | n/a | def test_simpleops(self): |
---|
279 | n/a | # Basic method sanity checks. |
---|
280 | n/a | |
---|
281 | n/a | elem = ET.XML("<body><tag/></body>") |
---|
282 | n/a | self.serialize_check(elem, '<body><tag /></body>') |
---|
283 | n/a | e = ET.Element("tag2") |
---|
284 | n/a | elem.append(e) |
---|
285 | n/a | self.serialize_check(elem, '<body><tag /><tag2 /></body>') |
---|
286 | n/a | elem.remove(e) |
---|
287 | n/a | self.serialize_check(elem, '<body><tag /></body>') |
---|
288 | n/a | elem.insert(0, e) |
---|
289 | n/a | self.serialize_check(elem, '<body><tag2 /><tag /></body>') |
---|
290 | n/a | elem.remove(e) |
---|
291 | n/a | elem.extend([e]) |
---|
292 | n/a | self.serialize_check(elem, '<body><tag /><tag2 /></body>') |
---|
293 | n/a | elem.remove(e) |
---|
294 | n/a | |
---|
295 | n/a | element = ET.Element("tag", key="value") |
---|
296 | n/a | self.serialize_check(element, '<tag key="value" />') # 1 |
---|
297 | n/a | subelement = ET.Element("subtag") |
---|
298 | n/a | element.append(subelement) |
---|
299 | n/a | self.serialize_check(element, '<tag key="value"><subtag /></tag>') # 2 |
---|
300 | n/a | element.insert(0, subelement) |
---|
301 | n/a | self.serialize_check(element, |
---|
302 | n/a | '<tag key="value"><subtag /><subtag /></tag>') # 3 |
---|
303 | n/a | element.remove(subelement) |
---|
304 | n/a | self.serialize_check(element, '<tag key="value"><subtag /></tag>') # 4 |
---|
305 | n/a | element.remove(subelement) |
---|
306 | n/a | self.serialize_check(element, '<tag key="value" />') # 5 |
---|
307 | n/a | with self.assertRaises(ValueError) as cm: |
---|
308 | n/a | element.remove(subelement) |
---|
309 | n/a | self.assertEqual(str(cm.exception), 'list.remove(x): x not in list') |
---|
310 | n/a | self.serialize_check(element, '<tag key="value" />') # 6 |
---|
311 | n/a | element[0:0] = [subelement, subelement, subelement] |
---|
312 | n/a | self.serialize_check(element[1], '<subtag />') |
---|
313 | n/a | self.assertEqual(element[1:9], [element[1], element[2]]) |
---|
314 | n/a | self.assertEqual(element[:9:2], [element[0], element[2]]) |
---|
315 | n/a | del element[1:2] |
---|
316 | n/a | self.serialize_check(element, |
---|
317 | n/a | '<tag key="value"><subtag /><subtag /></tag>') |
---|
318 | n/a | |
---|
319 | n/a | def test_cdata(self): |
---|
320 | n/a | # Test CDATA handling (etc). |
---|
321 | n/a | |
---|
322 | n/a | self.serialize_check(ET.XML("<tag>hello</tag>"), |
---|
323 | n/a | '<tag>hello</tag>') |
---|
324 | n/a | self.serialize_check(ET.XML("<tag>hello</tag>"), |
---|
325 | n/a | '<tag>hello</tag>') |
---|
326 | n/a | self.serialize_check(ET.XML("<tag><![CDATA[hello]]></tag>"), |
---|
327 | n/a | '<tag>hello</tag>') |
---|
328 | n/a | |
---|
329 | n/a | def test_file_init(self): |
---|
330 | n/a | stringfile = io.BytesIO(SAMPLE_XML.encode("utf-8")) |
---|
331 | n/a | tree = ET.ElementTree(file=stringfile) |
---|
332 | n/a | self.assertEqual(tree.find("tag").tag, 'tag') |
---|
333 | n/a | self.assertEqual(tree.find("section/tag").tag, 'tag') |
---|
334 | n/a | |
---|
335 | n/a | tree = ET.ElementTree(file=SIMPLE_XMLFILE) |
---|
336 | n/a | self.assertEqual(tree.find("element").tag, 'element') |
---|
337 | n/a | self.assertEqual(tree.find("element/../empty-element").tag, |
---|
338 | n/a | 'empty-element') |
---|
339 | n/a | |
---|
340 | n/a | def test_path_cache(self): |
---|
341 | n/a | # Check that the path cache behaves sanely. |
---|
342 | n/a | |
---|
343 | n/a | from xml.etree import ElementPath |
---|
344 | n/a | |
---|
345 | n/a | elem = ET.XML(SAMPLE_XML) |
---|
346 | n/a | for i in range(10): ET.ElementTree(elem).find('./'+str(i)) |
---|
347 | n/a | cache_len_10 = len(ElementPath._cache) |
---|
348 | n/a | for i in range(10): ET.ElementTree(elem).find('./'+str(i)) |
---|
349 | n/a | self.assertEqual(len(ElementPath._cache), cache_len_10) |
---|
350 | n/a | for i in range(20): ET.ElementTree(elem).find('./'+str(i)) |
---|
351 | n/a | self.assertGreater(len(ElementPath._cache), cache_len_10) |
---|
352 | n/a | for i in range(600): ET.ElementTree(elem).find('./'+str(i)) |
---|
353 | n/a | self.assertLess(len(ElementPath._cache), 500) |
---|
354 | n/a | |
---|
355 | n/a | def test_copy(self): |
---|
356 | n/a | # Test copy handling (etc). |
---|
357 | n/a | |
---|
358 | n/a | import copy |
---|
359 | n/a | e1 = ET.XML("<tag>hello<foo/></tag>") |
---|
360 | n/a | e2 = copy.copy(e1) |
---|
361 | n/a | e3 = copy.deepcopy(e1) |
---|
362 | n/a | e1.find("foo").tag = "bar" |
---|
363 | n/a | self.serialize_check(e1, '<tag>hello<bar /></tag>') |
---|
364 | n/a | self.serialize_check(e2, '<tag>hello<bar /></tag>') |
---|
365 | n/a | self.serialize_check(e3, '<tag>hello<foo /></tag>') |
---|
366 | n/a | |
---|
367 | n/a | def test_attrib(self): |
---|
368 | n/a | # Test attribute handling. |
---|
369 | n/a | |
---|
370 | n/a | elem = ET.Element("tag") |
---|
371 | n/a | elem.get("key") # 1.1 |
---|
372 | n/a | self.assertEqual(elem.get("key", "default"), 'default') # 1.2 |
---|
373 | n/a | |
---|
374 | n/a | elem.set("key", "value") |
---|
375 | n/a | self.assertEqual(elem.get("key"), 'value') # 1.3 |
---|
376 | n/a | |
---|
377 | n/a | elem = ET.Element("tag", key="value") |
---|
378 | n/a | self.assertEqual(elem.get("key"), 'value') # 2.1 |
---|
379 | n/a | self.assertEqual(elem.attrib, {'key': 'value'}) # 2.2 |
---|
380 | n/a | |
---|
381 | n/a | attrib = {"key": "value"} |
---|
382 | n/a | elem = ET.Element("tag", attrib) |
---|
383 | n/a | attrib.clear() # check for aliasing issues |
---|
384 | n/a | self.assertEqual(elem.get("key"), 'value') # 3.1 |
---|
385 | n/a | self.assertEqual(elem.attrib, {'key': 'value'}) # 3.2 |
---|
386 | n/a | |
---|
387 | n/a | attrib = {"key": "value"} |
---|
388 | n/a | elem = ET.Element("tag", **attrib) |
---|
389 | n/a | attrib.clear() # check for aliasing issues |
---|
390 | n/a | self.assertEqual(elem.get("key"), 'value') # 4.1 |
---|
391 | n/a | self.assertEqual(elem.attrib, {'key': 'value'}) # 4.2 |
---|
392 | n/a | |
---|
393 | n/a | elem = ET.Element("tag", {"key": "other"}, key="value") |
---|
394 | n/a | self.assertEqual(elem.get("key"), 'value') # 5.1 |
---|
395 | n/a | self.assertEqual(elem.attrib, {'key': 'value'}) # 5.2 |
---|
396 | n/a | |
---|
397 | n/a | elem = ET.Element('test') |
---|
398 | n/a | elem.text = "aa" |
---|
399 | n/a | elem.set('testa', 'testval') |
---|
400 | n/a | elem.set('testb', 'test2') |
---|
401 | n/a | self.assertEqual(ET.tostring(elem), |
---|
402 | n/a | b'<test testa="testval" testb="test2">aa</test>') |
---|
403 | n/a | self.assertEqual(sorted(elem.keys()), ['testa', 'testb']) |
---|
404 | n/a | self.assertEqual(sorted(elem.items()), |
---|
405 | n/a | [('testa', 'testval'), ('testb', 'test2')]) |
---|
406 | n/a | self.assertEqual(elem.attrib['testb'], 'test2') |
---|
407 | n/a | elem.attrib['testb'] = 'test1' |
---|
408 | n/a | elem.attrib['testc'] = 'test2' |
---|
409 | n/a | self.assertEqual(ET.tostring(elem), |
---|
410 | n/a | b'<test testa="testval" testb="test1" testc="test2">aa</test>') |
---|
411 | n/a | |
---|
412 | n/a | elem = ET.Element('test') |
---|
413 | n/a | elem.set('a', '\r') |
---|
414 | n/a | elem.set('b', '\r\n') |
---|
415 | n/a | elem.set('c', '\t\n\r ') |
---|
416 | n/a | elem.set('d', '\n\n') |
---|
417 | n/a | self.assertEqual(ET.tostring(elem), |
---|
418 | n/a | b'<test a=" " b=" " c="	 " d=" " />') |
---|
419 | n/a | |
---|
420 | n/a | def test_makeelement(self): |
---|
421 | n/a | # Test makeelement handling. |
---|
422 | n/a | |
---|
423 | n/a | elem = ET.Element("tag") |
---|
424 | n/a | attrib = {"key": "value"} |
---|
425 | n/a | subelem = elem.makeelement("subtag", attrib) |
---|
426 | n/a | self.assertIsNot(subelem.attrib, attrib, msg="attrib aliasing") |
---|
427 | n/a | elem.append(subelem) |
---|
428 | n/a | self.serialize_check(elem, '<tag><subtag key="value" /></tag>') |
---|
429 | n/a | |
---|
430 | n/a | elem.clear() |
---|
431 | n/a | self.serialize_check(elem, '<tag />') |
---|
432 | n/a | elem.append(subelem) |
---|
433 | n/a | self.serialize_check(elem, '<tag><subtag key="value" /></tag>') |
---|
434 | n/a | elem.extend([subelem, subelem]) |
---|
435 | n/a | self.serialize_check(elem, |
---|
436 | n/a | '<tag><subtag key="value" /><subtag key="value" /><subtag key="value" /></tag>') |
---|
437 | n/a | elem[:] = [subelem] |
---|
438 | n/a | self.serialize_check(elem, '<tag><subtag key="value" /></tag>') |
---|
439 | n/a | elem[:] = tuple([subelem]) |
---|
440 | n/a | self.serialize_check(elem, '<tag><subtag key="value" /></tag>') |
---|
441 | n/a | |
---|
442 | n/a | def test_parsefile(self): |
---|
443 | n/a | # Test parsing from file. |
---|
444 | n/a | |
---|
445 | n/a | tree = ET.parse(SIMPLE_XMLFILE) |
---|
446 | n/a | stream = io.StringIO() |
---|
447 | n/a | tree.write(stream, encoding='unicode') |
---|
448 | n/a | self.assertEqual(stream.getvalue(), |
---|
449 | n/a | '<root>\n' |
---|
450 | n/a | ' <element key="value">text</element>\n' |
---|
451 | n/a | ' <element>text</element>tail\n' |
---|
452 | n/a | ' <empty-element />\n' |
---|
453 | n/a | '</root>') |
---|
454 | n/a | tree = ET.parse(SIMPLE_NS_XMLFILE) |
---|
455 | n/a | stream = io.StringIO() |
---|
456 | n/a | tree.write(stream, encoding='unicode') |
---|
457 | n/a | self.assertEqual(stream.getvalue(), |
---|
458 | n/a | '<ns0:root xmlns:ns0="namespace">\n' |
---|
459 | n/a | ' <ns0:element key="value">text</ns0:element>\n' |
---|
460 | n/a | ' <ns0:element>text</ns0:element>tail\n' |
---|
461 | n/a | ' <ns0:empty-element />\n' |
---|
462 | n/a | '</ns0:root>') |
---|
463 | n/a | |
---|
464 | n/a | with open(SIMPLE_XMLFILE) as f: |
---|
465 | n/a | data = f.read() |
---|
466 | n/a | |
---|
467 | n/a | parser = ET.XMLParser() |
---|
468 | n/a | self.assertRegex(parser.version, r'^Expat ') |
---|
469 | n/a | parser.feed(data) |
---|
470 | n/a | self.serialize_check(parser.close(), |
---|
471 | n/a | '<root>\n' |
---|
472 | n/a | ' <element key="value">text</element>\n' |
---|
473 | n/a | ' <element>text</element>tail\n' |
---|
474 | n/a | ' <empty-element />\n' |
---|
475 | n/a | '</root>') |
---|
476 | n/a | |
---|
477 | n/a | target = ET.TreeBuilder() |
---|
478 | n/a | parser = ET.XMLParser(target=target) |
---|
479 | n/a | parser.feed(data) |
---|
480 | n/a | self.serialize_check(parser.close(), |
---|
481 | n/a | '<root>\n' |
---|
482 | n/a | ' <element key="value">text</element>\n' |
---|
483 | n/a | ' <element>text</element>tail\n' |
---|
484 | n/a | ' <empty-element />\n' |
---|
485 | n/a | '</root>') |
---|
486 | n/a | |
---|
487 | n/a | def test_parseliteral(self): |
---|
488 | n/a | element = ET.XML("<html><body>text</body></html>") |
---|
489 | n/a | self.assertEqual(ET.tostring(element, encoding='unicode'), |
---|
490 | n/a | '<html><body>text</body></html>') |
---|
491 | n/a | element = ET.fromstring("<html><body>text</body></html>") |
---|
492 | n/a | self.assertEqual(ET.tostring(element, encoding='unicode'), |
---|
493 | n/a | '<html><body>text</body></html>') |
---|
494 | n/a | sequence = ["<html><body>", "text</bo", "dy></html>"] |
---|
495 | n/a | element = ET.fromstringlist(sequence) |
---|
496 | n/a | self.assertEqual(ET.tostring(element), |
---|
497 | n/a | b'<html><body>text</body></html>') |
---|
498 | n/a | self.assertEqual(b"".join(ET.tostringlist(element)), |
---|
499 | n/a | b'<html><body>text</body></html>') |
---|
500 | n/a | self.assertEqual(ET.tostring(element, "ascii"), |
---|
501 | n/a | b"<?xml version='1.0' encoding='ascii'?>\n" |
---|
502 | n/a | b"<html><body>text</body></html>") |
---|
503 | n/a | _, ids = ET.XMLID("<html><body>text</body></html>") |
---|
504 | n/a | self.assertEqual(len(ids), 0) |
---|
505 | n/a | _, ids = ET.XMLID("<html><body id='body'>text</body></html>") |
---|
506 | n/a | self.assertEqual(len(ids), 1) |
---|
507 | n/a | self.assertEqual(ids["body"].tag, 'body') |
---|
508 | n/a | |
---|
509 | n/a | def test_iterparse(self): |
---|
510 | n/a | # Test iterparse interface. |
---|
511 | n/a | |
---|
512 | n/a | iterparse = ET.iterparse |
---|
513 | n/a | |
---|
514 | n/a | context = iterparse(SIMPLE_XMLFILE) |
---|
515 | n/a | action, elem = next(context) |
---|
516 | n/a | self.assertEqual((action, elem.tag), ('end', 'element')) |
---|
517 | n/a | self.assertEqual([(action, elem.tag) for action, elem in context], [ |
---|
518 | n/a | ('end', 'element'), |
---|
519 | n/a | ('end', 'empty-element'), |
---|
520 | n/a | ('end', 'root'), |
---|
521 | n/a | ]) |
---|
522 | n/a | self.assertEqual(context.root.tag, 'root') |
---|
523 | n/a | |
---|
524 | n/a | context = iterparse(SIMPLE_NS_XMLFILE) |
---|
525 | n/a | self.assertEqual([(action, elem.tag) for action, elem in context], [ |
---|
526 | n/a | ('end', '{namespace}element'), |
---|
527 | n/a | ('end', '{namespace}element'), |
---|
528 | n/a | ('end', '{namespace}empty-element'), |
---|
529 | n/a | ('end', '{namespace}root'), |
---|
530 | n/a | ]) |
---|
531 | n/a | |
---|
532 | n/a | events = () |
---|
533 | n/a | context = iterparse(SIMPLE_XMLFILE, events) |
---|
534 | n/a | self.assertEqual([(action, elem.tag) for action, elem in context], []) |
---|
535 | n/a | |
---|
536 | n/a | events = () |
---|
537 | n/a | context = iterparse(SIMPLE_XMLFILE, events=events) |
---|
538 | n/a | self.assertEqual([(action, elem.tag) for action, elem in context], []) |
---|
539 | n/a | |
---|
540 | n/a | events = ("start", "end") |
---|
541 | n/a | context = iterparse(SIMPLE_XMLFILE, events) |
---|
542 | n/a | self.assertEqual([(action, elem.tag) for action, elem in context], [ |
---|
543 | n/a | ('start', 'root'), |
---|
544 | n/a | ('start', 'element'), |
---|
545 | n/a | ('end', 'element'), |
---|
546 | n/a | ('start', 'element'), |
---|
547 | n/a | ('end', 'element'), |
---|
548 | n/a | ('start', 'empty-element'), |
---|
549 | n/a | ('end', 'empty-element'), |
---|
550 | n/a | ('end', 'root'), |
---|
551 | n/a | ]) |
---|
552 | n/a | |
---|
553 | n/a | events = ("start", "end", "start-ns", "end-ns") |
---|
554 | n/a | context = iterparse(SIMPLE_NS_XMLFILE, events) |
---|
555 | n/a | self.assertEqual([(action, elem.tag) if action in ("start", "end") |
---|
556 | n/a | else (action, elem) |
---|
557 | n/a | for action, elem in context], [ |
---|
558 | n/a | ('start-ns', ('', 'namespace')), |
---|
559 | n/a | ('start', '{namespace}root'), |
---|
560 | n/a | ('start', '{namespace}element'), |
---|
561 | n/a | ('end', '{namespace}element'), |
---|
562 | n/a | ('start', '{namespace}element'), |
---|
563 | n/a | ('end', '{namespace}element'), |
---|
564 | n/a | ('start', '{namespace}empty-element'), |
---|
565 | n/a | ('end', '{namespace}empty-element'), |
---|
566 | n/a | ('end', '{namespace}root'), |
---|
567 | n/a | ('end-ns', None), |
---|
568 | n/a | ]) |
---|
569 | n/a | |
---|
570 | n/a | events = ('start-ns', 'end-ns') |
---|
571 | n/a | context = iterparse(io.StringIO(r"<root xmlns=''/>"), events) |
---|
572 | n/a | res = [action for action, elem in context] |
---|
573 | n/a | self.assertEqual(res, ['start-ns', 'end-ns']) |
---|
574 | n/a | |
---|
575 | n/a | events = ("start", "end", "bogus") |
---|
576 | n/a | with open(SIMPLE_XMLFILE, "rb") as f: |
---|
577 | n/a | with self.assertRaises(ValueError) as cm: |
---|
578 | n/a | iterparse(f, events) |
---|
579 | n/a | self.assertFalse(f.closed) |
---|
580 | n/a | self.assertEqual(str(cm.exception), "unknown event 'bogus'") |
---|
581 | n/a | |
---|
582 | n/a | with support.check_no_resource_warning(self): |
---|
583 | n/a | with self.assertRaises(ValueError) as cm: |
---|
584 | n/a | iterparse(SIMPLE_XMLFILE, events) |
---|
585 | n/a | self.assertEqual(str(cm.exception), "unknown event 'bogus'") |
---|
586 | n/a | del cm |
---|
587 | n/a | |
---|
588 | n/a | source = io.BytesIO( |
---|
589 | n/a | b"<?xml version='1.0' encoding='iso-8859-1'?>\n" |
---|
590 | n/a | b"<body xmlns='http://éffbot.org/ns'\n" |
---|
591 | n/a | b" xmlns:cl\xe9='http://effbot.org/ns'>text</body>\n") |
---|
592 | n/a | events = ("start-ns",) |
---|
593 | n/a | context = iterparse(source, events) |
---|
594 | n/a | self.assertEqual([(action, elem) for action, elem in context], [ |
---|
595 | n/a | ('start-ns', ('', 'http://\xe9ffbot.org/ns')), |
---|
596 | n/a | ('start-ns', ('cl\xe9', 'http://effbot.org/ns')), |
---|
597 | n/a | ]) |
---|
598 | n/a | |
---|
599 | n/a | source = io.StringIO("<document />junk") |
---|
600 | n/a | it = iterparse(source) |
---|
601 | n/a | action, elem = next(it) |
---|
602 | n/a | self.assertEqual((action, elem.tag), ('end', 'document')) |
---|
603 | n/a | with self.assertRaises(ET.ParseError) as cm: |
---|
604 | n/a | next(it) |
---|
605 | n/a | self.assertEqual(str(cm.exception), |
---|
606 | n/a | 'junk after document element: line 1, column 12') |
---|
607 | n/a | |
---|
608 | n/a | with open(TESTFN, "wb") as f: |
---|
609 | n/a | f.write(b"<document />junk") |
---|
610 | n/a | it = iterparse(TESTFN) |
---|
611 | n/a | action, elem = next(it) |
---|
612 | n/a | self.assertEqual((action, elem.tag), ('end', 'document')) |
---|
613 | n/a | with support.check_no_resource_warning(self): |
---|
614 | n/a | with self.assertRaises(ET.ParseError) as cm: |
---|
615 | n/a | next(it) |
---|
616 | n/a | self.assertEqual(str(cm.exception), |
---|
617 | n/a | 'junk after document element: line 1, column 12') |
---|
618 | n/a | del cm, it |
---|
619 | n/a | |
---|
620 | n/a | def test_writefile(self): |
---|
621 | n/a | elem = ET.Element("tag") |
---|
622 | n/a | elem.text = "text" |
---|
623 | n/a | self.serialize_check(elem, '<tag>text</tag>') |
---|
624 | n/a | ET.SubElement(elem, "subtag").text = "subtext" |
---|
625 | n/a | self.serialize_check(elem, '<tag>text<subtag>subtext</subtag></tag>') |
---|
626 | n/a | |
---|
627 | n/a | # Test tag suppression |
---|
628 | n/a | elem.tag = None |
---|
629 | n/a | self.serialize_check(elem, 'text<subtag>subtext</subtag>') |
---|
630 | n/a | elem.insert(0, ET.Comment("comment")) |
---|
631 | n/a | self.serialize_check(elem, |
---|
632 | n/a | 'text<!--comment--><subtag>subtext</subtag>') # assumes 1.3 |
---|
633 | n/a | |
---|
634 | n/a | elem[0] = ET.PI("key", "value") |
---|
635 | n/a | self.serialize_check(elem, 'text<?key value?><subtag>subtext</subtag>') |
---|
636 | n/a | |
---|
637 | n/a | def test_custom_builder(self): |
---|
638 | n/a | # Test parser w. custom builder. |
---|
639 | n/a | |
---|
640 | n/a | with open(SIMPLE_XMLFILE) as f: |
---|
641 | n/a | data = f.read() |
---|
642 | n/a | class Builder(list): |
---|
643 | n/a | def start(self, tag, attrib): |
---|
644 | n/a | self.append(("start", tag)) |
---|
645 | n/a | def end(self, tag): |
---|
646 | n/a | self.append(("end", tag)) |
---|
647 | n/a | def data(self, text): |
---|
648 | n/a | pass |
---|
649 | n/a | builder = Builder() |
---|
650 | n/a | parser = ET.XMLParser(target=builder) |
---|
651 | n/a | parser.feed(data) |
---|
652 | n/a | self.assertEqual(builder, [ |
---|
653 | n/a | ('start', 'root'), |
---|
654 | n/a | ('start', 'element'), |
---|
655 | n/a | ('end', 'element'), |
---|
656 | n/a | ('start', 'element'), |
---|
657 | n/a | ('end', 'element'), |
---|
658 | n/a | ('start', 'empty-element'), |
---|
659 | n/a | ('end', 'empty-element'), |
---|
660 | n/a | ('end', 'root'), |
---|
661 | n/a | ]) |
---|
662 | n/a | |
---|
663 | n/a | with open(SIMPLE_NS_XMLFILE) as f: |
---|
664 | n/a | data = f.read() |
---|
665 | n/a | class Builder(list): |
---|
666 | n/a | def start(self, tag, attrib): |
---|
667 | n/a | self.append(("start", tag)) |
---|
668 | n/a | def end(self, tag): |
---|
669 | n/a | self.append(("end", tag)) |
---|
670 | n/a | def data(self, text): |
---|
671 | n/a | pass |
---|
672 | n/a | def pi(self, target, data): |
---|
673 | n/a | self.append(("pi", target, data)) |
---|
674 | n/a | def comment(self, data): |
---|
675 | n/a | self.append(("comment", data)) |
---|
676 | n/a | builder = Builder() |
---|
677 | n/a | parser = ET.XMLParser(target=builder) |
---|
678 | n/a | parser.feed(data) |
---|
679 | n/a | self.assertEqual(builder, [ |
---|
680 | n/a | ('pi', 'pi', 'data'), |
---|
681 | n/a | ('comment', ' comment '), |
---|
682 | n/a | ('start', '{namespace}root'), |
---|
683 | n/a | ('start', '{namespace}element'), |
---|
684 | n/a | ('end', '{namespace}element'), |
---|
685 | n/a | ('start', '{namespace}element'), |
---|
686 | n/a | ('end', '{namespace}element'), |
---|
687 | n/a | ('start', '{namespace}empty-element'), |
---|
688 | n/a | ('end', '{namespace}empty-element'), |
---|
689 | n/a | ('end', '{namespace}root'), |
---|
690 | n/a | ]) |
---|
691 | n/a | |
---|
692 | n/a | |
---|
693 | n/a | def test_getchildren(self): |
---|
694 | n/a | # Test Element.getchildren() |
---|
695 | n/a | |
---|
696 | n/a | with open(SIMPLE_XMLFILE, "rb") as f: |
---|
697 | n/a | tree = ET.parse(f) |
---|
698 | n/a | self.assertEqual([summarize_list(elem.getchildren()) |
---|
699 | n/a | for elem in tree.getroot().iter()], [ |
---|
700 | n/a | ['element', 'element', 'empty-element'], |
---|
701 | n/a | [], |
---|
702 | n/a | [], |
---|
703 | n/a | [], |
---|
704 | n/a | ]) |
---|
705 | n/a | self.assertEqual([summarize_list(elem.getchildren()) |
---|
706 | n/a | for elem in tree.getiterator()], [ |
---|
707 | n/a | ['element', 'element', 'empty-element'], |
---|
708 | n/a | [], |
---|
709 | n/a | [], |
---|
710 | n/a | [], |
---|
711 | n/a | ]) |
---|
712 | n/a | |
---|
713 | n/a | elem = ET.XML(SAMPLE_XML) |
---|
714 | n/a | self.assertEqual(len(elem.getchildren()), 3) |
---|
715 | n/a | self.assertEqual(len(elem[2].getchildren()), 1) |
---|
716 | n/a | self.assertEqual(elem[:], elem.getchildren()) |
---|
717 | n/a | child1 = elem[0] |
---|
718 | n/a | child2 = elem[2] |
---|
719 | n/a | del elem[1:2] |
---|
720 | n/a | self.assertEqual(len(elem.getchildren()), 2) |
---|
721 | n/a | self.assertEqual(child1, elem[0]) |
---|
722 | n/a | self.assertEqual(child2, elem[1]) |
---|
723 | n/a | elem[0:2] = [child2, child1] |
---|
724 | n/a | self.assertEqual(child2, elem[0]) |
---|
725 | n/a | self.assertEqual(child1, elem[1]) |
---|
726 | n/a | self.assertNotEqual(child1, elem[0]) |
---|
727 | n/a | elem.clear() |
---|
728 | n/a | self.assertEqual(elem.getchildren(), []) |
---|
729 | n/a | |
---|
730 | n/a | def test_writestring(self): |
---|
731 | n/a | elem = ET.XML("<html><body>text</body></html>") |
---|
732 | n/a | self.assertEqual(ET.tostring(elem), b'<html><body>text</body></html>') |
---|
733 | n/a | elem = ET.fromstring("<html><body>text</body></html>") |
---|
734 | n/a | self.assertEqual(ET.tostring(elem), b'<html><body>text</body></html>') |
---|
735 | n/a | |
---|
736 | n/a | def test_encoding(self): |
---|
737 | n/a | def check(encoding, body=''): |
---|
738 | n/a | xml = ("<?xml version='1.0' encoding='%s'?><xml>%s</xml>" % |
---|
739 | n/a | (encoding, body)) |
---|
740 | n/a | self.assertEqual(ET.XML(xml.encode(encoding)).text, body) |
---|
741 | n/a | self.assertEqual(ET.XML(xml).text, body) |
---|
742 | n/a | check("ascii", 'a') |
---|
743 | n/a | check("us-ascii", 'a') |
---|
744 | n/a | check("iso-8859-1", '\xbd') |
---|
745 | n/a | check("iso-8859-15", '\u20ac') |
---|
746 | n/a | check("cp437", '\u221a') |
---|
747 | n/a | check("mac-roman", '\u02da') |
---|
748 | n/a | |
---|
749 | n/a | def xml(encoding): |
---|
750 | n/a | return "<?xml version='1.0' encoding='%s'?><xml />" % encoding |
---|
751 | n/a | def bxml(encoding): |
---|
752 | n/a | return xml(encoding).encode(encoding) |
---|
753 | n/a | supported_encodings = [ |
---|
754 | n/a | 'ascii', 'utf-8', 'utf-8-sig', 'utf-16', 'utf-16be', 'utf-16le', |
---|
755 | n/a | 'iso8859-1', 'iso8859-2', 'iso8859-3', 'iso8859-4', 'iso8859-5', |
---|
756 | n/a | 'iso8859-6', 'iso8859-7', 'iso8859-8', 'iso8859-9', 'iso8859-10', |
---|
757 | n/a | 'iso8859-13', 'iso8859-14', 'iso8859-15', 'iso8859-16', |
---|
758 | n/a | 'cp437', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', |
---|
759 | n/a | 'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861', 'cp862', |
---|
760 | n/a | 'cp863', 'cp865', 'cp866', 'cp869', 'cp874', 'cp1006', 'cp1125', |
---|
761 | n/a | 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', |
---|
762 | n/a | 'cp1256', 'cp1257', 'cp1258', |
---|
763 | n/a | 'mac-cyrillic', 'mac-greek', 'mac-iceland', 'mac-latin2', |
---|
764 | n/a | 'mac-roman', 'mac-turkish', |
---|
765 | n/a | 'iso2022-jp', 'iso2022-jp-1', 'iso2022-jp-2', 'iso2022-jp-2004', |
---|
766 | n/a | 'iso2022-jp-3', 'iso2022-jp-ext', |
---|
767 | n/a | 'koi8-r', 'koi8-t', 'koi8-u', 'kz1048', |
---|
768 | n/a | 'hz', 'ptcp154', |
---|
769 | n/a | ] |
---|
770 | n/a | for encoding in supported_encodings: |
---|
771 | n/a | self.assertEqual(ET.tostring(ET.XML(bxml(encoding))), b'<xml />') |
---|
772 | n/a | |
---|
773 | n/a | unsupported_ascii_compatible_encodings = [ |
---|
774 | n/a | 'big5', 'big5hkscs', |
---|
775 | n/a | 'cp932', 'cp949', 'cp950', |
---|
776 | n/a | 'euc-jp', 'euc-jis-2004', 'euc-jisx0213', 'euc-kr', |
---|
777 | n/a | 'gb2312', 'gbk', 'gb18030', |
---|
778 | n/a | 'iso2022-kr', 'johab', |
---|
779 | n/a | 'shift-jis', 'shift-jis-2004', 'shift-jisx0213', |
---|
780 | n/a | 'utf-7', |
---|
781 | n/a | ] |
---|
782 | n/a | for encoding in unsupported_ascii_compatible_encodings: |
---|
783 | n/a | self.assertRaises(ValueError, ET.XML, bxml(encoding)) |
---|
784 | n/a | |
---|
785 | n/a | unsupported_ascii_incompatible_encodings = [ |
---|
786 | n/a | 'cp037', 'cp424', 'cp500', 'cp864', 'cp875', 'cp1026', 'cp1140', |
---|
787 | n/a | 'utf_32', 'utf_32_be', 'utf_32_le', |
---|
788 | n/a | ] |
---|
789 | n/a | for encoding in unsupported_ascii_incompatible_encodings: |
---|
790 | n/a | self.assertRaises(ET.ParseError, ET.XML, bxml(encoding)) |
---|
791 | n/a | |
---|
792 | n/a | self.assertRaises(ValueError, ET.XML, xml('undefined').encode('ascii')) |
---|
793 | n/a | self.assertRaises(LookupError, ET.XML, xml('xxx').encode('ascii')) |
---|
794 | n/a | |
---|
795 | n/a | def test_methods(self): |
---|
796 | n/a | # Test serialization methods. |
---|
797 | n/a | |
---|
798 | n/a | e = ET.XML("<html><link/><script>1 < 2</script></html>") |
---|
799 | n/a | e.tail = "\n" |
---|
800 | n/a | self.assertEqual(serialize(e), |
---|
801 | n/a | '<html><link /><script>1 < 2</script></html>\n') |
---|
802 | n/a | self.assertEqual(serialize(e, method=None), |
---|
803 | n/a | '<html><link /><script>1 < 2</script></html>\n') |
---|
804 | n/a | self.assertEqual(serialize(e, method="xml"), |
---|
805 | n/a | '<html><link /><script>1 < 2</script></html>\n') |
---|
806 | n/a | self.assertEqual(serialize(e, method="html"), |
---|
807 | n/a | '<html><link><script>1 < 2</script></html>\n') |
---|
808 | n/a | self.assertEqual(serialize(e, method="text"), '1 < 2\n') |
---|
809 | n/a | |
---|
810 | n/a | def test_issue18347(self): |
---|
811 | n/a | e = ET.XML('<html><CamelCase>text</CamelCase></html>') |
---|
812 | n/a | self.assertEqual(serialize(e), |
---|
813 | n/a | '<html><CamelCase>text</CamelCase></html>') |
---|
814 | n/a | self.assertEqual(serialize(e, method="html"), |
---|
815 | n/a | '<html><CamelCase>text</CamelCase></html>') |
---|
816 | n/a | |
---|
817 | n/a | def test_entity(self): |
---|
818 | n/a | # Test entity handling. |
---|
819 | n/a | |
---|
820 | n/a | # 1) good entities |
---|
821 | n/a | |
---|
822 | n/a | e = ET.XML("<document title='舰'>test</document>") |
---|
823 | n/a | self.assertEqual(serialize(e, encoding="us-ascii"), |
---|
824 | n/a | b'<document title="舰">test</document>') |
---|
825 | n/a | self.serialize_check(e, '<document title="\u8230">test</document>') |
---|
826 | n/a | |
---|
827 | n/a | # 2) bad entities |
---|
828 | n/a | |
---|
829 | n/a | with self.assertRaises(ET.ParseError) as cm: |
---|
830 | n/a | ET.XML("<document>&entity;</document>") |
---|
831 | n/a | self.assertEqual(str(cm.exception), |
---|
832 | n/a | 'undefined entity: line 1, column 10') |
---|
833 | n/a | |
---|
834 | n/a | with self.assertRaises(ET.ParseError) as cm: |
---|
835 | n/a | ET.XML(ENTITY_XML) |
---|
836 | n/a | self.assertEqual(str(cm.exception), |
---|
837 | n/a | 'undefined entity &entity;: line 5, column 10') |
---|
838 | n/a | |
---|
839 | n/a | # 3) custom entity |
---|
840 | n/a | |
---|
841 | n/a | parser = ET.XMLParser() |
---|
842 | n/a | parser.entity["entity"] = "text" |
---|
843 | n/a | parser.feed(ENTITY_XML) |
---|
844 | n/a | root = parser.close() |
---|
845 | n/a | self.serialize_check(root, '<document>text</document>') |
---|
846 | n/a | |
---|
847 | n/a | def test_namespace(self): |
---|
848 | n/a | # Test namespace issues. |
---|
849 | n/a | |
---|
850 | n/a | # 1) xml namespace |
---|
851 | n/a | |
---|
852 | n/a | elem = ET.XML("<tag xml:lang='en' />") |
---|
853 | n/a | self.serialize_check(elem, '<tag xml:lang="en" />') # 1.1 |
---|
854 | n/a | |
---|
855 | n/a | # 2) other "well-known" namespaces |
---|
856 | n/a | |
---|
857 | n/a | elem = ET.XML("<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' />") |
---|
858 | n/a | self.serialize_check(elem, |
---|
859 | n/a | '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" />') # 2.1 |
---|
860 | n/a | |
---|
861 | n/a | elem = ET.XML("<html:html xmlns:html='http://www.w3.org/1999/xhtml' />") |
---|
862 | n/a | self.serialize_check(elem, |
---|
863 | n/a | '<html:html xmlns:html="http://www.w3.org/1999/xhtml" />') # 2.2 |
---|
864 | n/a | |
---|
865 | n/a | elem = ET.XML("<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope' />") |
---|
866 | n/a | self.serialize_check(elem, |
---|
867 | n/a | '<ns0:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope" />') # 2.3 |
---|
868 | n/a | |
---|
869 | n/a | # 3) unknown namespaces |
---|
870 | n/a | elem = ET.XML(SAMPLE_XML_NS) |
---|
871 | n/a | self.serialize_check(elem, |
---|
872 | n/a | '<ns0:body xmlns:ns0="http://effbot.org/ns">\n' |
---|
873 | n/a | ' <ns0:tag>text</ns0:tag>\n' |
---|
874 | n/a | ' <ns0:tag />\n' |
---|
875 | n/a | ' <ns0:section>\n' |
---|
876 | n/a | ' <ns0:tag>subtext</ns0:tag>\n' |
---|
877 | n/a | ' </ns0:section>\n' |
---|
878 | n/a | '</ns0:body>') |
---|
879 | n/a | |
---|
880 | n/a | def test_qname(self): |
---|
881 | n/a | # Test QName handling. |
---|
882 | n/a | |
---|
883 | n/a | # 1) decorated tags |
---|
884 | n/a | |
---|
885 | n/a | elem = ET.Element("{uri}tag") |
---|
886 | n/a | self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" />') # 1.1 |
---|
887 | n/a | elem = ET.Element(ET.QName("{uri}tag")) |
---|
888 | n/a | self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" />') # 1.2 |
---|
889 | n/a | elem = ET.Element(ET.QName("uri", "tag")) |
---|
890 | n/a | self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" />') # 1.3 |
---|
891 | n/a | elem = ET.Element(ET.QName("uri", "tag")) |
---|
892 | n/a | subelem = ET.SubElement(elem, ET.QName("uri", "tag1")) |
---|
893 | n/a | subelem = ET.SubElement(elem, ET.QName("uri", "tag2")) |
---|
894 | n/a | self.serialize_check(elem, |
---|
895 | n/a | '<ns0:tag xmlns:ns0="uri"><ns0:tag1 /><ns0:tag2 /></ns0:tag>') # 1.4 |
---|
896 | n/a | |
---|
897 | n/a | # 2) decorated attributes |
---|
898 | n/a | |
---|
899 | n/a | elem.clear() |
---|
900 | n/a | elem.attrib["{uri}key"] = "value" |
---|
901 | n/a | self.serialize_check(elem, |
---|
902 | n/a | '<ns0:tag xmlns:ns0="uri" ns0:key="value" />') # 2.1 |
---|
903 | n/a | |
---|
904 | n/a | elem.clear() |
---|
905 | n/a | elem.attrib[ET.QName("{uri}key")] = "value" |
---|
906 | n/a | self.serialize_check(elem, |
---|
907 | n/a | '<ns0:tag xmlns:ns0="uri" ns0:key="value" />') # 2.2 |
---|
908 | n/a | |
---|
909 | n/a | # 3) decorated values are not converted by default, but the |
---|
910 | n/a | # QName wrapper can be used for values |
---|
911 | n/a | |
---|
912 | n/a | elem.clear() |
---|
913 | n/a | elem.attrib["{uri}key"] = "{uri}value" |
---|
914 | n/a | self.serialize_check(elem, |
---|
915 | n/a | '<ns0:tag xmlns:ns0="uri" ns0:key="{uri}value" />') # 3.1 |
---|
916 | n/a | |
---|
917 | n/a | elem.clear() |
---|
918 | n/a | elem.attrib["{uri}key"] = ET.QName("{uri}value") |
---|
919 | n/a | self.serialize_check(elem, |
---|
920 | n/a | '<ns0:tag xmlns:ns0="uri" ns0:key="ns0:value" />') # 3.2 |
---|
921 | n/a | |
---|
922 | n/a | elem.clear() |
---|
923 | n/a | subelem = ET.Element("tag") |
---|
924 | n/a | subelem.attrib["{uri1}key"] = ET.QName("{uri2}value") |
---|
925 | n/a | elem.append(subelem) |
---|
926 | n/a | elem.append(subelem) |
---|
927 | n/a | self.serialize_check(elem, |
---|
928 | n/a | '<ns0:tag xmlns:ns0="uri" xmlns:ns1="uri1" xmlns:ns2="uri2">' |
---|
929 | n/a | '<tag ns1:key="ns2:value" />' |
---|
930 | n/a | '<tag ns1:key="ns2:value" />' |
---|
931 | n/a | '</ns0:tag>') # 3.3 |
---|
932 | n/a | |
---|
933 | n/a | # 4) Direct QName tests |
---|
934 | n/a | |
---|
935 | n/a | self.assertEqual(str(ET.QName('ns', 'tag')), '{ns}tag') |
---|
936 | n/a | self.assertEqual(str(ET.QName('{ns}tag')), '{ns}tag') |
---|
937 | n/a | q1 = ET.QName('ns', 'tag') |
---|
938 | n/a | q2 = ET.QName('ns', 'tag') |
---|
939 | n/a | self.assertEqual(q1, q2) |
---|
940 | n/a | q2 = ET.QName('ns', 'other-tag') |
---|
941 | n/a | self.assertNotEqual(q1, q2) |
---|
942 | n/a | self.assertNotEqual(q1, 'ns:tag') |
---|
943 | n/a | self.assertEqual(q1, '{ns}tag') |
---|
944 | n/a | |
---|
945 | n/a | def test_doctype_public(self): |
---|
946 | n/a | # Test PUBLIC doctype. |
---|
947 | n/a | |
---|
948 | n/a | elem = ET.XML('<!DOCTYPE html PUBLIC' |
---|
949 | n/a | ' "-//W3C//DTD XHTML 1.0 Transitional//EN"' |
---|
950 | n/a | ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' |
---|
951 | n/a | '<html>text</html>') |
---|
952 | n/a | |
---|
953 | n/a | def test_xpath_tokenizer(self): |
---|
954 | n/a | # Test the XPath tokenizer. |
---|
955 | n/a | from xml.etree import ElementPath |
---|
956 | n/a | def check(p, expected): |
---|
957 | n/a | self.assertEqual([op or tag |
---|
958 | n/a | for op, tag in ElementPath.xpath_tokenizer(p)], |
---|
959 | n/a | expected) |
---|
960 | n/a | |
---|
961 | n/a | # tests from the xml specification |
---|
962 | n/a | check("*", ['*']) |
---|
963 | n/a | check("text()", ['text', '()']) |
---|
964 | n/a | check("@name", ['@', 'name']) |
---|
965 | n/a | check("@*", ['@', '*']) |
---|
966 | n/a | check("para[1]", ['para', '[', '1', ']']) |
---|
967 | n/a | check("para[last()]", ['para', '[', 'last', '()', ']']) |
---|
968 | n/a | check("*/para", ['*', '/', 'para']) |
---|
969 | n/a | check("/doc/chapter[5]/section[2]", |
---|
970 | n/a | ['/', 'doc', '/', 'chapter', '[', '5', ']', |
---|
971 | n/a | '/', 'section', '[', '2', ']']) |
---|
972 | n/a | check("chapter//para", ['chapter', '//', 'para']) |
---|
973 | n/a | check("//para", ['//', 'para']) |
---|
974 | n/a | check("//olist/item", ['//', 'olist', '/', 'item']) |
---|
975 | n/a | check(".", ['.']) |
---|
976 | n/a | check(".//para", ['.', '//', 'para']) |
---|
977 | n/a | check("..", ['..']) |
---|
978 | n/a | check("../@lang", ['..', '/', '@', 'lang']) |
---|
979 | n/a | check("chapter[title]", ['chapter', '[', 'title', ']']) |
---|
980 | n/a | check("employee[@secretary and @assistant]", ['employee', |
---|
981 | n/a | '[', '@', 'secretary', '', 'and', '', '@', 'assistant', ']']) |
---|
982 | n/a | |
---|
983 | n/a | # additional tests |
---|
984 | n/a | check("{http://spam}egg", ['{http://spam}egg']) |
---|
985 | n/a | check("./spam.egg", ['.', '/', 'spam.egg']) |
---|
986 | n/a | check(".//{http://spam}egg", ['.', '//', '{http://spam}egg']) |
---|
987 | n/a | |
---|
988 | n/a | def test_processinginstruction(self): |
---|
989 | n/a | # Test ProcessingInstruction directly |
---|
990 | n/a | |
---|
991 | n/a | self.assertEqual(ET.tostring(ET.ProcessingInstruction('test', 'instruction')), |
---|
992 | n/a | b'<?test instruction?>') |
---|
993 | n/a | self.assertEqual(ET.tostring(ET.PI('test', 'instruction')), |
---|
994 | n/a | b'<?test instruction?>') |
---|
995 | n/a | |
---|
996 | n/a | # Issue #2746 |
---|
997 | n/a | |
---|
998 | n/a | self.assertEqual(ET.tostring(ET.PI('test', '<testing&>')), |
---|
999 | n/a | b'<?test <testing&>?>') |
---|
1000 | n/a | self.assertEqual(ET.tostring(ET.PI('test', '<testing&>\xe3'), 'latin-1'), |
---|
1001 | n/a | b"<?xml version='1.0' encoding='latin-1'?>\n" |
---|
1002 | n/a | b"<?test <testing&>\xe3?>") |
---|
1003 | n/a | |
---|
1004 | n/a | def test_html_empty_elems_serialization(self): |
---|
1005 | n/a | # issue 15970 |
---|
1006 | n/a | # from http://www.w3.org/TR/html401/index/elements.html |
---|
1007 | n/a | for element in ['AREA', 'BASE', 'BASEFONT', 'BR', 'COL', 'FRAME', 'HR', |
---|
1008 | n/a | 'IMG', 'INPUT', 'ISINDEX', 'LINK', 'META', 'PARAM']: |
---|
1009 | n/a | for elem in [element, element.lower()]: |
---|
1010 | n/a | expected = '<%s>' % elem |
---|
1011 | n/a | serialized = serialize(ET.XML('<%s />' % elem), method='html') |
---|
1012 | n/a | self.assertEqual(serialized, expected) |
---|
1013 | n/a | serialized = serialize(ET.XML('<%s></%s>' % (elem,elem)), |
---|
1014 | n/a | method='html') |
---|
1015 | n/a | self.assertEqual(serialized, expected) |
---|
1016 | n/a | |
---|
1017 | n/a | |
---|
1018 | n/a | class XMLPullParserTest(unittest.TestCase): |
---|
1019 | n/a | |
---|
1020 | n/a | def _feed(self, parser, data, chunk_size=None): |
---|
1021 | n/a | if chunk_size is None: |
---|
1022 | n/a | parser.feed(data) |
---|
1023 | n/a | else: |
---|
1024 | n/a | for i in range(0, len(data), chunk_size): |
---|
1025 | n/a | parser.feed(data[i:i+chunk_size]) |
---|
1026 | n/a | |
---|
1027 | n/a | def assert_event_tags(self, parser, expected): |
---|
1028 | n/a | events = parser.read_events() |
---|
1029 | n/a | self.assertEqual([(action, elem.tag) for action, elem in events], |
---|
1030 | n/a | expected) |
---|
1031 | n/a | |
---|
1032 | n/a | def test_simple_xml(self): |
---|
1033 | n/a | for chunk_size in (None, 1, 5): |
---|
1034 | n/a | with self.subTest(chunk_size=chunk_size): |
---|
1035 | n/a | parser = ET.XMLPullParser() |
---|
1036 | n/a | self.assert_event_tags(parser, []) |
---|
1037 | n/a | self._feed(parser, "<!-- comment -->\n", chunk_size) |
---|
1038 | n/a | self.assert_event_tags(parser, []) |
---|
1039 | n/a | self._feed(parser, |
---|
1040 | n/a | "<root>\n <element key='value'>text</element", |
---|
1041 | n/a | chunk_size) |
---|
1042 | n/a | self.assert_event_tags(parser, []) |
---|
1043 | n/a | self._feed(parser, ">\n", chunk_size) |
---|
1044 | n/a | self.assert_event_tags(parser, [('end', 'element')]) |
---|
1045 | n/a | self._feed(parser, "<element>text</element>tail\n", chunk_size) |
---|
1046 | n/a | self._feed(parser, "<empty-element/>\n", chunk_size) |
---|
1047 | n/a | self.assert_event_tags(parser, [ |
---|
1048 | n/a | ('end', 'element'), |
---|
1049 | n/a | ('end', 'empty-element'), |
---|
1050 | n/a | ]) |
---|
1051 | n/a | self._feed(parser, "</root>\n", chunk_size) |
---|
1052 | n/a | self.assert_event_tags(parser, [('end', 'root')]) |
---|
1053 | n/a | self.assertIsNone(parser.close()) |
---|
1054 | n/a | |
---|
1055 | n/a | def test_feed_while_iterating(self): |
---|
1056 | n/a | parser = ET.XMLPullParser() |
---|
1057 | n/a | it = parser.read_events() |
---|
1058 | n/a | self._feed(parser, "<root>\n <element key='value'>text</element>\n") |
---|
1059 | n/a | action, elem = next(it) |
---|
1060 | n/a | self.assertEqual((action, elem.tag), ('end', 'element')) |
---|
1061 | n/a | self._feed(parser, "</root>\n") |
---|
1062 | n/a | action, elem = next(it) |
---|
1063 | n/a | self.assertEqual((action, elem.tag), ('end', 'root')) |
---|
1064 | n/a | with self.assertRaises(StopIteration): |
---|
1065 | n/a | next(it) |
---|
1066 | n/a | |
---|
1067 | n/a | def test_simple_xml_with_ns(self): |
---|
1068 | n/a | parser = ET.XMLPullParser() |
---|
1069 | n/a | self.assert_event_tags(parser, []) |
---|
1070 | n/a | self._feed(parser, "<!-- comment -->\n") |
---|
1071 | n/a | self.assert_event_tags(parser, []) |
---|
1072 | n/a | self._feed(parser, "<root xmlns='namespace'>\n") |
---|
1073 | n/a | self.assert_event_tags(parser, []) |
---|
1074 | n/a | self._feed(parser, "<element key='value'>text</element") |
---|
1075 | n/a | self.assert_event_tags(parser, []) |
---|
1076 | n/a | self._feed(parser, ">\n") |
---|
1077 | n/a | self.assert_event_tags(parser, [('end', '{namespace}element')]) |
---|
1078 | n/a | self._feed(parser, "<element>text</element>tail\n") |
---|
1079 | n/a | self._feed(parser, "<empty-element/>\n") |
---|
1080 | n/a | self.assert_event_tags(parser, [ |
---|
1081 | n/a | ('end', '{namespace}element'), |
---|
1082 | n/a | ('end', '{namespace}empty-element'), |
---|
1083 | n/a | ]) |
---|
1084 | n/a | self._feed(parser, "</root>\n") |
---|
1085 | n/a | self.assert_event_tags(parser, [('end', '{namespace}root')]) |
---|
1086 | n/a | self.assertIsNone(parser.close()) |
---|
1087 | n/a | |
---|
1088 | n/a | def test_ns_events(self): |
---|
1089 | n/a | parser = ET.XMLPullParser(events=('start-ns', 'end-ns')) |
---|
1090 | n/a | self._feed(parser, "<!-- comment -->\n") |
---|
1091 | n/a | self._feed(parser, "<root xmlns='namespace'>\n") |
---|
1092 | n/a | self.assertEqual( |
---|
1093 | n/a | list(parser.read_events()), |
---|
1094 | n/a | [('start-ns', ('', 'namespace'))]) |
---|
1095 | n/a | self._feed(parser, "<element key='value'>text</element") |
---|
1096 | n/a | self._feed(parser, ">\n") |
---|
1097 | n/a | self._feed(parser, "<element>text</element>tail\n") |
---|
1098 | n/a | self._feed(parser, "<empty-element/>\n") |
---|
1099 | n/a | self._feed(parser, "</root>\n") |
---|
1100 | n/a | self.assertEqual(list(parser.read_events()), [('end-ns', None)]) |
---|
1101 | n/a | self.assertIsNone(parser.close()) |
---|
1102 | n/a | |
---|
1103 | n/a | def test_events(self): |
---|
1104 | n/a | parser = ET.XMLPullParser(events=()) |
---|
1105 | n/a | self._feed(parser, "<root/>\n") |
---|
1106 | n/a | self.assert_event_tags(parser, []) |
---|
1107 | n/a | |
---|
1108 | n/a | parser = ET.XMLPullParser(events=('start', 'end')) |
---|
1109 | n/a | self._feed(parser, "<!-- comment -->\n") |
---|
1110 | n/a | self.assert_event_tags(parser, []) |
---|
1111 | n/a | self._feed(parser, "<root>\n") |
---|
1112 | n/a | self.assert_event_tags(parser, [('start', 'root')]) |
---|
1113 | n/a | self._feed(parser, "<element key='value'>text</element") |
---|
1114 | n/a | self.assert_event_tags(parser, [('start', 'element')]) |
---|
1115 | n/a | self._feed(parser, ">\n") |
---|
1116 | n/a | self.assert_event_tags(parser, [('end', 'element')]) |
---|
1117 | n/a | self._feed(parser, |
---|
1118 | n/a | "<element xmlns='foo'>text<empty-element/></element>tail\n") |
---|
1119 | n/a | self.assert_event_tags(parser, [ |
---|
1120 | n/a | ('start', '{foo}element'), |
---|
1121 | n/a | ('start', '{foo}empty-element'), |
---|
1122 | n/a | ('end', '{foo}empty-element'), |
---|
1123 | n/a | ('end', '{foo}element'), |
---|
1124 | n/a | ]) |
---|
1125 | n/a | self._feed(parser, "</root>") |
---|
1126 | n/a | self.assertIsNone(parser.close()) |
---|
1127 | n/a | self.assert_event_tags(parser, [('end', 'root')]) |
---|
1128 | n/a | |
---|
1129 | n/a | parser = ET.XMLPullParser(events=('start',)) |
---|
1130 | n/a | self._feed(parser, "<!-- comment -->\n") |
---|
1131 | n/a | self.assert_event_tags(parser, []) |
---|
1132 | n/a | self._feed(parser, "<root>\n") |
---|
1133 | n/a | self.assert_event_tags(parser, [('start', 'root')]) |
---|
1134 | n/a | self._feed(parser, "<element key='value'>text</element") |
---|
1135 | n/a | self.assert_event_tags(parser, [('start', 'element')]) |
---|
1136 | n/a | self._feed(parser, ">\n") |
---|
1137 | n/a | self.assert_event_tags(parser, []) |
---|
1138 | n/a | self._feed(parser, |
---|
1139 | n/a | "<element xmlns='foo'>text<empty-element/></element>tail\n") |
---|
1140 | n/a | self.assert_event_tags(parser, [ |
---|
1141 | n/a | ('start', '{foo}element'), |
---|
1142 | n/a | ('start', '{foo}empty-element'), |
---|
1143 | n/a | ]) |
---|
1144 | n/a | self._feed(parser, "</root>") |
---|
1145 | n/a | self.assertIsNone(parser.close()) |
---|
1146 | n/a | |
---|
1147 | n/a | def test_events_sequence(self): |
---|
1148 | n/a | # Test that events can be some sequence that's not just a tuple or list |
---|
1149 | n/a | eventset = {'end', 'start'} |
---|
1150 | n/a | parser = ET.XMLPullParser(events=eventset) |
---|
1151 | n/a | self._feed(parser, "<foo>bar</foo>") |
---|
1152 | n/a | self.assert_event_tags(parser, [('start', 'foo'), ('end', 'foo')]) |
---|
1153 | n/a | |
---|
1154 | n/a | class DummyIter: |
---|
1155 | n/a | def __init__(self): |
---|
1156 | n/a | self.events = iter(['start', 'end', 'start-ns']) |
---|
1157 | n/a | def __iter__(self): |
---|
1158 | n/a | return self |
---|
1159 | n/a | def __next__(self): |
---|
1160 | n/a | return next(self.events) |
---|
1161 | n/a | |
---|
1162 | n/a | parser = ET.XMLPullParser(events=DummyIter()) |
---|
1163 | n/a | self._feed(parser, "<foo>bar</foo>") |
---|
1164 | n/a | self.assert_event_tags(parser, [('start', 'foo'), ('end', 'foo')]) |
---|
1165 | n/a | |
---|
1166 | n/a | |
---|
1167 | n/a | def test_unknown_event(self): |
---|
1168 | n/a | with self.assertRaises(ValueError): |
---|
1169 | n/a | ET.XMLPullParser(events=('start', 'end', 'bogus')) |
---|
1170 | n/a | |
---|
1171 | n/a | |
---|
1172 | n/a | # |
---|
1173 | n/a | # xinclude tests (samples from appendix C of the xinclude specification) |
---|
1174 | n/a | |
---|
1175 | n/a | XINCLUDE = {} |
---|
1176 | n/a | |
---|
1177 | n/a | XINCLUDE["C1.xml"] = """\ |
---|
1178 | n/a | <?xml version='1.0'?> |
---|
1179 | n/a | <document xmlns:xi="http://www.w3.org/2001/XInclude"> |
---|
1180 | n/a | <p>120 Mz is adequate for an average home user.</p> |
---|
1181 | n/a | <xi:include href="disclaimer.xml"/> |
---|
1182 | n/a | </document> |
---|
1183 | n/a | """ |
---|
1184 | n/a | |
---|
1185 | n/a | XINCLUDE["disclaimer.xml"] = """\ |
---|
1186 | n/a | <?xml version='1.0'?> |
---|
1187 | n/a | <disclaimer> |
---|
1188 | n/a | <p>The opinions represented herein represent those of the individual |
---|
1189 | n/a | and should not be interpreted as official policy endorsed by this |
---|
1190 | n/a | organization.</p> |
---|
1191 | n/a | </disclaimer> |
---|
1192 | n/a | """ |
---|
1193 | n/a | |
---|
1194 | n/a | XINCLUDE["C2.xml"] = """\ |
---|
1195 | n/a | <?xml version='1.0'?> |
---|
1196 | n/a | <document xmlns:xi="http://www.w3.org/2001/XInclude"> |
---|
1197 | n/a | <p>This document has been accessed |
---|
1198 | n/a | <xi:include href="count.txt" parse="text"/> times.</p> |
---|
1199 | n/a | </document> |
---|
1200 | n/a | """ |
---|
1201 | n/a | |
---|
1202 | n/a | XINCLUDE["count.txt"] = "324387" |
---|
1203 | n/a | |
---|
1204 | n/a | XINCLUDE["C2b.xml"] = """\ |
---|
1205 | n/a | <?xml version='1.0'?> |
---|
1206 | n/a | <document xmlns:xi="http://www.w3.org/2001/XInclude"> |
---|
1207 | n/a | <p>This document has been <em>accessed</em> |
---|
1208 | n/a | <xi:include href="count.txt" parse="text"/> times.</p> |
---|
1209 | n/a | </document> |
---|
1210 | n/a | """ |
---|
1211 | n/a | |
---|
1212 | n/a | XINCLUDE["C3.xml"] = """\ |
---|
1213 | n/a | <?xml version='1.0'?> |
---|
1214 | n/a | <document xmlns:xi="http://www.w3.org/2001/XInclude"> |
---|
1215 | n/a | <p>The following is the source of the "data.xml" resource:</p> |
---|
1216 | n/a | <example><xi:include href="data.xml" parse="text"/></example> |
---|
1217 | n/a | </document> |
---|
1218 | n/a | """ |
---|
1219 | n/a | |
---|
1220 | n/a | XINCLUDE["data.xml"] = """\ |
---|
1221 | n/a | <?xml version='1.0'?> |
---|
1222 | n/a | <data> |
---|
1223 | n/a | <item><![CDATA[Brooks & Shields]]></item> |
---|
1224 | n/a | </data> |
---|
1225 | n/a | """ |
---|
1226 | n/a | |
---|
1227 | n/a | XINCLUDE["C5.xml"] = """\ |
---|
1228 | n/a | <?xml version='1.0'?> |
---|
1229 | n/a | <div xmlns:xi="http://www.w3.org/2001/XInclude"> |
---|
1230 | n/a | <xi:include href="example.txt" parse="text"> |
---|
1231 | n/a | <xi:fallback> |
---|
1232 | n/a | <xi:include href="fallback-example.txt" parse="text"> |
---|
1233 | n/a | <xi:fallback><a href="mailto:bob@example.org">Report error</a></xi:fallback> |
---|
1234 | n/a | </xi:include> |
---|
1235 | n/a | </xi:fallback> |
---|
1236 | n/a | </xi:include> |
---|
1237 | n/a | </div> |
---|
1238 | n/a | """ |
---|
1239 | n/a | |
---|
1240 | n/a | XINCLUDE["default.xml"] = """\ |
---|
1241 | n/a | <?xml version='1.0'?> |
---|
1242 | n/a | <document xmlns:xi="http://www.w3.org/2001/XInclude"> |
---|
1243 | n/a | <p>Example.</p> |
---|
1244 | n/a | <xi:include href="{}"/> |
---|
1245 | n/a | </document> |
---|
1246 | n/a | """.format(html.escape(SIMPLE_XMLFILE, True)) |
---|
1247 | n/a | |
---|
1248 | n/a | # |
---|
1249 | n/a | # badly formatted xi:include tags |
---|
1250 | n/a | |
---|
1251 | n/a | XINCLUDE_BAD = {} |
---|
1252 | n/a | |
---|
1253 | n/a | XINCLUDE_BAD["B1.xml"] = """\ |
---|
1254 | n/a | <?xml version='1.0'?> |
---|
1255 | n/a | <document xmlns:xi="http://www.w3.org/2001/XInclude"> |
---|
1256 | n/a | <p>120 Mz is adequate for an average home user.</p> |
---|
1257 | n/a | <xi:include href="disclaimer.xml" parse="BAD_TYPE"/> |
---|
1258 | n/a | </document> |
---|
1259 | n/a | """ |
---|
1260 | n/a | |
---|
1261 | n/a | XINCLUDE_BAD["B2.xml"] = """\ |
---|
1262 | n/a | <?xml version='1.0'?> |
---|
1263 | n/a | <div xmlns:xi="http://www.w3.org/2001/XInclude"> |
---|
1264 | n/a | <xi:fallback></xi:fallback> |
---|
1265 | n/a | </div> |
---|
1266 | n/a | """ |
---|
1267 | n/a | |
---|
1268 | n/a | class XIncludeTest(unittest.TestCase): |
---|
1269 | n/a | |
---|
1270 | n/a | def xinclude_loader(self, href, parse="xml", encoding=None): |
---|
1271 | n/a | try: |
---|
1272 | n/a | data = XINCLUDE[href] |
---|
1273 | n/a | except KeyError: |
---|
1274 | n/a | raise OSError("resource not found") |
---|
1275 | n/a | if parse == "xml": |
---|
1276 | n/a | data = ET.XML(data) |
---|
1277 | n/a | return data |
---|
1278 | n/a | |
---|
1279 | n/a | def none_loader(self, href, parser, encoding=None): |
---|
1280 | n/a | return None |
---|
1281 | n/a | |
---|
1282 | n/a | def _my_loader(self, href, parse): |
---|
1283 | n/a | # Used to avoid a test-dependency problem where the default loader |
---|
1284 | n/a | # of ElementInclude uses the pyET parser for cET tests. |
---|
1285 | n/a | if parse == 'xml': |
---|
1286 | n/a | with open(href, 'rb') as f: |
---|
1287 | n/a | return ET.parse(f).getroot() |
---|
1288 | n/a | else: |
---|
1289 | n/a | return None |
---|
1290 | n/a | |
---|
1291 | n/a | def test_xinclude_default(self): |
---|
1292 | n/a | from xml.etree import ElementInclude |
---|
1293 | n/a | doc = self.xinclude_loader('default.xml') |
---|
1294 | n/a | ElementInclude.include(doc, self._my_loader) |
---|
1295 | n/a | self.assertEqual(serialize(doc), |
---|
1296 | n/a | '<document>\n' |
---|
1297 | n/a | ' <p>Example.</p>\n' |
---|
1298 | n/a | ' <root>\n' |
---|
1299 | n/a | ' <element key="value">text</element>\n' |
---|
1300 | n/a | ' <element>text</element>tail\n' |
---|
1301 | n/a | ' <empty-element />\n' |
---|
1302 | n/a | '</root>\n' |
---|
1303 | n/a | '</document>') |
---|
1304 | n/a | |
---|
1305 | n/a | def test_xinclude(self): |
---|
1306 | n/a | from xml.etree import ElementInclude |
---|
1307 | n/a | |
---|
1308 | n/a | # Basic inclusion example (XInclude C.1) |
---|
1309 | n/a | document = self.xinclude_loader("C1.xml") |
---|
1310 | n/a | ElementInclude.include(document, self.xinclude_loader) |
---|
1311 | n/a | self.assertEqual(serialize(document), |
---|
1312 | n/a | '<document>\n' |
---|
1313 | n/a | ' <p>120 Mz is adequate for an average home user.</p>\n' |
---|
1314 | n/a | ' <disclaimer>\n' |
---|
1315 | n/a | ' <p>The opinions represented herein represent those of the individual\n' |
---|
1316 | n/a | ' and should not be interpreted as official policy endorsed by this\n' |
---|
1317 | n/a | ' organization.</p>\n' |
---|
1318 | n/a | '</disclaimer>\n' |
---|
1319 | n/a | '</document>') # C1 |
---|
1320 | n/a | |
---|
1321 | n/a | # Textual inclusion example (XInclude C.2) |
---|
1322 | n/a | document = self.xinclude_loader("C2.xml") |
---|
1323 | n/a | ElementInclude.include(document, self.xinclude_loader) |
---|
1324 | n/a | self.assertEqual(serialize(document), |
---|
1325 | n/a | '<document>\n' |
---|
1326 | n/a | ' <p>This document has been accessed\n' |
---|
1327 | n/a | ' 324387 times.</p>\n' |
---|
1328 | n/a | '</document>') # C2 |
---|
1329 | n/a | |
---|
1330 | n/a | # Textual inclusion after sibling element (based on modified XInclude C.2) |
---|
1331 | n/a | document = self.xinclude_loader("C2b.xml") |
---|
1332 | n/a | ElementInclude.include(document, self.xinclude_loader) |
---|
1333 | n/a | self.assertEqual(serialize(document), |
---|
1334 | n/a | '<document>\n' |
---|
1335 | n/a | ' <p>This document has been <em>accessed</em>\n' |
---|
1336 | n/a | ' 324387 times.</p>\n' |
---|
1337 | n/a | '</document>') # C2b |
---|
1338 | n/a | |
---|
1339 | n/a | # Textual inclusion of XML example (XInclude C.3) |
---|
1340 | n/a | document = self.xinclude_loader("C3.xml") |
---|
1341 | n/a | ElementInclude.include(document, self.xinclude_loader) |
---|
1342 | n/a | self.assertEqual(serialize(document), |
---|
1343 | n/a | '<document>\n' |
---|
1344 | n/a | ' <p>The following is the source of the "data.xml" resource:</p>\n' |
---|
1345 | n/a | " <example><?xml version='1.0'?>\n" |
---|
1346 | n/a | '<data>\n' |
---|
1347 | n/a | ' <item><![CDATA[Brooks & Shields]]></item>\n' |
---|
1348 | n/a | '</data>\n' |
---|
1349 | n/a | '</example>\n' |
---|
1350 | n/a | '</document>') # C3 |
---|
1351 | n/a | |
---|
1352 | n/a | # Fallback example (XInclude C.5) |
---|
1353 | n/a | # Note! Fallback support is not yet implemented |
---|
1354 | n/a | document = self.xinclude_loader("C5.xml") |
---|
1355 | n/a | with self.assertRaises(OSError) as cm: |
---|
1356 | n/a | ElementInclude.include(document, self.xinclude_loader) |
---|
1357 | n/a | self.assertEqual(str(cm.exception), 'resource not found') |
---|
1358 | n/a | self.assertEqual(serialize(document), |
---|
1359 | n/a | '<div xmlns:ns0="http://www.w3.org/2001/XInclude">\n' |
---|
1360 | n/a | ' <ns0:include href="example.txt" parse="text">\n' |
---|
1361 | n/a | ' <ns0:fallback>\n' |
---|
1362 | n/a | ' <ns0:include href="fallback-example.txt" parse="text">\n' |
---|
1363 | n/a | ' <ns0:fallback><a href="mailto:bob@example.org">Report error</a></ns0:fallback>\n' |
---|
1364 | n/a | ' </ns0:include>\n' |
---|
1365 | n/a | ' </ns0:fallback>\n' |
---|
1366 | n/a | ' </ns0:include>\n' |
---|
1367 | n/a | '</div>') # C5 |
---|
1368 | n/a | |
---|
1369 | n/a | def test_xinclude_failures(self): |
---|
1370 | n/a | from xml.etree import ElementInclude |
---|
1371 | n/a | |
---|
1372 | n/a | # Test failure to locate included XML file. |
---|
1373 | n/a | document = ET.XML(XINCLUDE["C1.xml"]) |
---|
1374 | n/a | with self.assertRaises(ElementInclude.FatalIncludeError) as cm: |
---|
1375 | n/a | ElementInclude.include(document, loader=self.none_loader) |
---|
1376 | n/a | self.assertEqual(str(cm.exception), |
---|
1377 | n/a | "cannot load 'disclaimer.xml' as 'xml'") |
---|
1378 | n/a | |
---|
1379 | n/a | # Test failure to locate included text file. |
---|
1380 | n/a | document = ET.XML(XINCLUDE["C2.xml"]) |
---|
1381 | n/a | with self.assertRaises(ElementInclude.FatalIncludeError) as cm: |
---|
1382 | n/a | ElementInclude.include(document, loader=self.none_loader) |
---|
1383 | n/a | self.assertEqual(str(cm.exception), |
---|
1384 | n/a | "cannot load 'count.txt' as 'text'") |
---|
1385 | n/a | |
---|
1386 | n/a | # Test bad parse type. |
---|
1387 | n/a | document = ET.XML(XINCLUDE_BAD["B1.xml"]) |
---|
1388 | n/a | with self.assertRaises(ElementInclude.FatalIncludeError) as cm: |
---|
1389 | n/a | ElementInclude.include(document, loader=self.none_loader) |
---|
1390 | n/a | self.assertEqual(str(cm.exception), |
---|
1391 | n/a | "unknown parse type in xi:include tag ('BAD_TYPE')") |
---|
1392 | n/a | |
---|
1393 | n/a | # Test xi:fallback outside xi:include. |
---|
1394 | n/a | document = ET.XML(XINCLUDE_BAD["B2.xml"]) |
---|
1395 | n/a | with self.assertRaises(ElementInclude.FatalIncludeError) as cm: |
---|
1396 | n/a | ElementInclude.include(document, loader=self.none_loader) |
---|
1397 | n/a | self.assertEqual(str(cm.exception), |
---|
1398 | n/a | "xi:fallback tag must be child of xi:include " |
---|
1399 | n/a | "('{http://www.w3.org/2001/XInclude}fallback')") |
---|
1400 | n/a | |
---|
1401 | n/a | # -------------------------------------------------------------------- |
---|
1402 | n/a | # reported bugs |
---|
1403 | n/a | |
---|
1404 | n/a | class BugsTest(unittest.TestCase): |
---|
1405 | n/a | |
---|
1406 | n/a | def test_bug_xmltoolkit21(self): |
---|
1407 | n/a | # marshaller gives obscure errors for non-string values |
---|
1408 | n/a | |
---|
1409 | n/a | def check(elem): |
---|
1410 | n/a | with self.assertRaises(TypeError) as cm: |
---|
1411 | n/a | serialize(elem) |
---|
1412 | n/a | self.assertEqual(str(cm.exception), |
---|
1413 | n/a | 'cannot serialize 123 (type int)') |
---|
1414 | n/a | |
---|
1415 | n/a | elem = ET.Element(123) |
---|
1416 | n/a | check(elem) # tag |
---|
1417 | n/a | |
---|
1418 | n/a | elem = ET.Element("elem") |
---|
1419 | n/a | elem.text = 123 |
---|
1420 | n/a | check(elem) # text |
---|
1421 | n/a | |
---|
1422 | n/a | elem = ET.Element("elem") |
---|
1423 | n/a | elem.tail = 123 |
---|
1424 | n/a | check(elem) # tail |
---|
1425 | n/a | |
---|
1426 | n/a | elem = ET.Element("elem") |
---|
1427 | n/a | elem.set(123, "123") |
---|
1428 | n/a | check(elem) # attribute key |
---|
1429 | n/a | |
---|
1430 | n/a | elem = ET.Element("elem") |
---|
1431 | n/a | elem.set("123", 123) |
---|
1432 | n/a | check(elem) # attribute value |
---|
1433 | n/a | |
---|
1434 | n/a | def test_bug_xmltoolkit25(self): |
---|
1435 | n/a | # typo in ElementTree.findtext |
---|
1436 | n/a | |
---|
1437 | n/a | elem = ET.XML(SAMPLE_XML) |
---|
1438 | n/a | tree = ET.ElementTree(elem) |
---|
1439 | n/a | self.assertEqual(tree.findtext("tag"), 'text') |
---|
1440 | n/a | self.assertEqual(tree.findtext("section/tag"), 'subtext') |
---|
1441 | n/a | |
---|
1442 | n/a | def test_bug_xmltoolkit28(self): |
---|
1443 | n/a | # .//tag causes exceptions |
---|
1444 | n/a | |
---|
1445 | n/a | tree = ET.XML("<doc><table><tbody/></table></doc>") |
---|
1446 | n/a | self.assertEqual(summarize_list(tree.findall(".//thead")), []) |
---|
1447 | n/a | self.assertEqual(summarize_list(tree.findall(".//tbody")), ['tbody']) |
---|
1448 | n/a | |
---|
1449 | n/a | def test_bug_xmltoolkitX1(self): |
---|
1450 | n/a | # dump() doesn't flush the output buffer |
---|
1451 | n/a | |
---|
1452 | n/a | tree = ET.XML("<doc><table><tbody/></table></doc>") |
---|
1453 | n/a | with support.captured_stdout() as stdout: |
---|
1454 | n/a | ET.dump(tree) |
---|
1455 | n/a | self.assertEqual(stdout.getvalue(), '<doc><table><tbody /></table></doc>\n') |
---|
1456 | n/a | |
---|
1457 | n/a | def test_bug_xmltoolkit39(self): |
---|
1458 | n/a | # non-ascii element and attribute names doesn't work |
---|
1459 | n/a | |
---|
1460 | n/a | tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?><t\xe4g />") |
---|
1461 | n/a | self.assertEqual(ET.tostring(tree, "utf-8"), b'<t\xc3\xa4g />') |
---|
1462 | n/a | |
---|
1463 | n/a | tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?>" |
---|
1464 | n/a | b"<tag \xe4ttr='välue' />") |
---|
1465 | n/a | self.assertEqual(tree.attrib, {'\xe4ttr': 'v\xe4lue'}) |
---|
1466 | n/a | self.assertEqual(ET.tostring(tree, "utf-8"), |
---|
1467 | n/a | b'<tag \xc3\xa4ttr="v\xc3\xa4lue" />') |
---|
1468 | n/a | |
---|
1469 | n/a | tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?>" |
---|
1470 | n/a | b'<t\xe4g>text</t\xe4g>') |
---|
1471 | n/a | self.assertEqual(ET.tostring(tree, "utf-8"), |
---|
1472 | n/a | b'<t\xc3\xa4g>text</t\xc3\xa4g>') |
---|
1473 | n/a | |
---|
1474 | n/a | tree = ET.Element("t\u00e4g") |
---|
1475 | n/a | self.assertEqual(ET.tostring(tree, "utf-8"), b'<t\xc3\xa4g />') |
---|
1476 | n/a | |
---|
1477 | n/a | tree = ET.Element("tag") |
---|
1478 | n/a | tree.set("\u00e4ttr", "v\u00e4lue") |
---|
1479 | n/a | self.assertEqual(ET.tostring(tree, "utf-8"), |
---|
1480 | n/a | b'<tag \xc3\xa4ttr="v\xc3\xa4lue" />') |
---|
1481 | n/a | |
---|
1482 | n/a | def test_bug_xmltoolkit54(self): |
---|
1483 | n/a | # problems handling internally defined entities |
---|
1484 | n/a | |
---|
1485 | n/a | e = ET.XML("<!DOCTYPE doc [<!ENTITY ldots '舰'>]>" |
---|
1486 | n/a | '<doc>&ldots;</doc>') |
---|
1487 | n/a | self.assertEqual(serialize(e, encoding="us-ascii"), |
---|
1488 | n/a | b'<doc>舰</doc>') |
---|
1489 | n/a | self.assertEqual(serialize(e), '<doc>\u8230</doc>') |
---|
1490 | n/a | |
---|
1491 | n/a | def test_bug_xmltoolkit55(self): |
---|
1492 | n/a | # make sure we're reporting the first error, not the last |
---|
1493 | n/a | |
---|
1494 | n/a | with self.assertRaises(ET.ParseError) as cm: |
---|
1495 | n/a | ET.XML(b"<!DOCTYPE doc SYSTEM 'doc.dtd'>" |
---|
1496 | n/a | b'<doc>&ldots;&ndots;&rdots;</doc>') |
---|
1497 | n/a | self.assertEqual(str(cm.exception), |
---|
1498 | n/a | 'undefined entity &ldots;: line 1, column 36') |
---|
1499 | n/a | |
---|
1500 | n/a | def test_bug_xmltoolkit60(self): |
---|
1501 | n/a | # Handle crash in stream source. |
---|
1502 | n/a | |
---|
1503 | n/a | class ExceptionFile: |
---|
1504 | n/a | def read(self, x): |
---|
1505 | n/a | raise OSError |
---|
1506 | n/a | |
---|
1507 | n/a | self.assertRaises(OSError, ET.parse, ExceptionFile()) |
---|
1508 | n/a | |
---|
1509 | n/a | def test_bug_xmltoolkit62(self): |
---|
1510 | n/a | # Don't crash when using custom entities. |
---|
1511 | n/a | |
---|
1512 | n/a | ENTITIES = {'rsquo': '\u2019', 'lsquo': '\u2018'} |
---|
1513 | n/a | parser = ET.XMLParser() |
---|
1514 | n/a | parser.entity.update(ENTITIES) |
---|
1515 | n/a | parser.feed("""<?xml version="1.0" encoding="UTF-8"?> |
---|
1516 | n/a | <!DOCTYPE patent-application-publication SYSTEM "pap-v15-2001-01-31.dtd" []> |
---|
1517 | n/a | <patent-application-publication> |
---|
1518 | n/a | <subdoc-abstract> |
---|
1519 | n/a | <paragraph id="A-0001" lvl="0">A new cultivar of Begonia plant named ‘BCT9801BEG’.</paragraph> |
---|
1520 | n/a | </subdoc-abstract> |
---|
1521 | n/a | </patent-application-publication>""") |
---|
1522 | n/a | t = parser.close() |
---|
1523 | n/a | self.assertEqual(t.find('.//paragraph').text, |
---|
1524 | n/a | 'A new cultivar of Begonia plant named \u2018BCT9801BEG\u2019.') |
---|
1525 | n/a | |
---|
1526 | n/a | def test_bug_xmltoolkit63(self): |
---|
1527 | n/a | # Check reference leak. |
---|
1528 | n/a | def xmltoolkit63(): |
---|
1529 | n/a | tree = ET.TreeBuilder() |
---|
1530 | n/a | tree.start("tag", {}) |
---|
1531 | n/a | tree.data("text") |
---|
1532 | n/a | tree.end("tag") |
---|
1533 | n/a | |
---|
1534 | n/a | xmltoolkit63() |
---|
1535 | n/a | count = sys.getrefcount(None) |
---|
1536 | n/a | for i in range(1000): |
---|
1537 | n/a | xmltoolkit63() |
---|
1538 | n/a | self.assertEqual(sys.getrefcount(None), count) |
---|
1539 | n/a | |
---|
1540 | n/a | def test_bug_200708_newline(self): |
---|
1541 | n/a | # Preserve newlines in attributes. |
---|
1542 | n/a | |
---|
1543 | n/a | e = ET.Element('SomeTag', text="def _f():\n return 3\n") |
---|
1544 | n/a | self.assertEqual(ET.tostring(e), |
---|
1545 | n/a | b'<SomeTag text="def _f(): return 3 " />') |
---|
1546 | n/a | self.assertEqual(ET.XML(ET.tostring(e)).get("text"), |
---|
1547 | n/a | 'def _f():\n return 3\n') |
---|
1548 | n/a | self.assertEqual(ET.tostring(ET.XML(ET.tostring(e))), |
---|
1549 | n/a | b'<SomeTag text="def _f(): return 3 " />') |
---|
1550 | n/a | |
---|
1551 | n/a | def test_bug_200708_close(self): |
---|
1552 | n/a | # Test default builder. |
---|
1553 | n/a | parser = ET.XMLParser() # default |
---|
1554 | n/a | parser.feed("<element>some text</element>") |
---|
1555 | n/a | self.assertEqual(parser.close().tag, 'element') |
---|
1556 | n/a | |
---|
1557 | n/a | # Test custom builder. |
---|
1558 | n/a | class EchoTarget: |
---|
1559 | n/a | def close(self): |
---|
1560 | n/a | return ET.Element("element") # simulate root |
---|
1561 | n/a | parser = ET.XMLParser(EchoTarget()) |
---|
1562 | n/a | parser.feed("<element>some text</element>") |
---|
1563 | n/a | self.assertEqual(parser.close().tag, 'element') |
---|
1564 | n/a | |
---|
1565 | n/a | def test_bug_200709_default_namespace(self): |
---|
1566 | n/a | e = ET.Element("{default}elem") |
---|
1567 | n/a | s = ET.SubElement(e, "{default}elem") |
---|
1568 | n/a | self.assertEqual(serialize(e, default_namespace="default"), # 1 |
---|
1569 | n/a | '<elem xmlns="default"><elem /></elem>') |
---|
1570 | n/a | |
---|
1571 | n/a | e = ET.Element("{default}elem") |
---|
1572 | n/a | s = ET.SubElement(e, "{default}elem") |
---|
1573 | n/a | s = ET.SubElement(e, "{not-default}elem") |
---|
1574 | n/a | self.assertEqual(serialize(e, default_namespace="default"), # 2 |
---|
1575 | n/a | '<elem xmlns="default" xmlns:ns1="not-default">' |
---|
1576 | n/a | '<elem />' |
---|
1577 | n/a | '<ns1:elem />' |
---|
1578 | n/a | '</elem>') |
---|
1579 | n/a | |
---|
1580 | n/a | e = ET.Element("{default}elem") |
---|
1581 | n/a | s = ET.SubElement(e, "{default}elem") |
---|
1582 | n/a | s = ET.SubElement(e, "elem") # unprefixed name |
---|
1583 | n/a | with self.assertRaises(ValueError) as cm: |
---|
1584 | n/a | serialize(e, default_namespace="default") # 3 |
---|
1585 | n/a | self.assertEqual(str(cm.exception), |
---|
1586 | n/a | 'cannot use non-qualified names with default_namespace option') |
---|
1587 | n/a | |
---|
1588 | n/a | def test_bug_200709_register_namespace(self): |
---|
1589 | n/a | e = ET.Element("{http://namespace.invalid/does/not/exist/}title") |
---|
1590 | n/a | self.assertEqual(ET.tostring(e), |
---|
1591 | n/a | b'<ns0:title xmlns:ns0="http://namespace.invalid/does/not/exist/" />') |
---|
1592 | n/a | ET.register_namespace("foo", "http://namespace.invalid/does/not/exist/") |
---|
1593 | n/a | e = ET.Element("{http://namespace.invalid/does/not/exist/}title") |
---|
1594 | n/a | self.assertEqual(ET.tostring(e), |
---|
1595 | n/a | b'<foo:title xmlns:foo="http://namespace.invalid/does/not/exist/" />') |
---|
1596 | n/a | |
---|
1597 | n/a | # And the Dublin Core namespace is in the default list: |
---|
1598 | n/a | |
---|
1599 | n/a | e = ET.Element("{http://purl.org/dc/elements/1.1/}title") |
---|
1600 | n/a | self.assertEqual(ET.tostring(e), |
---|
1601 | n/a | b'<dc:title xmlns:dc="http://purl.org/dc/elements/1.1/" />') |
---|
1602 | n/a | |
---|
1603 | n/a | def test_bug_200709_element_comment(self): |
---|
1604 | n/a | # Not sure if this can be fixed, really (since the serializer needs |
---|
1605 | n/a | # ET.Comment, not cET.comment). |
---|
1606 | n/a | |
---|
1607 | n/a | a = ET.Element('a') |
---|
1608 | n/a | a.append(ET.Comment('foo')) |
---|
1609 | n/a | self.assertEqual(a[0].tag, ET.Comment) |
---|
1610 | n/a | |
---|
1611 | n/a | a = ET.Element('a') |
---|
1612 | n/a | a.append(ET.PI('foo')) |
---|
1613 | n/a | self.assertEqual(a[0].tag, ET.PI) |
---|
1614 | n/a | |
---|
1615 | n/a | def test_bug_200709_element_insert(self): |
---|
1616 | n/a | a = ET.Element('a') |
---|
1617 | n/a | b = ET.SubElement(a, 'b') |
---|
1618 | n/a | c = ET.SubElement(a, 'c') |
---|
1619 | n/a | d = ET.Element('d') |
---|
1620 | n/a | a.insert(0, d) |
---|
1621 | n/a | self.assertEqual(summarize_list(a), ['d', 'b', 'c']) |
---|
1622 | n/a | a.insert(-1, d) |
---|
1623 | n/a | self.assertEqual(summarize_list(a), ['d', 'b', 'd', 'c']) |
---|
1624 | n/a | |
---|
1625 | n/a | def test_bug_200709_iter_comment(self): |
---|
1626 | n/a | a = ET.Element('a') |
---|
1627 | n/a | b = ET.SubElement(a, 'b') |
---|
1628 | n/a | comment_b = ET.Comment("TEST-b") |
---|
1629 | n/a | b.append(comment_b) |
---|
1630 | n/a | self.assertEqual(summarize_list(a.iter(ET.Comment)), [ET.Comment]) |
---|
1631 | n/a | |
---|
1632 | n/a | # -------------------------------------------------------------------- |
---|
1633 | n/a | # reported on bugs.python.org |
---|
1634 | n/a | |
---|
1635 | n/a | def test_bug_1534630(self): |
---|
1636 | n/a | bob = ET.TreeBuilder() |
---|
1637 | n/a | e = bob.data("data") |
---|
1638 | n/a | e = bob.start("tag", {}) |
---|
1639 | n/a | e = bob.end("tag") |
---|
1640 | n/a | e = bob.close() |
---|
1641 | n/a | self.assertEqual(serialize(e), '<tag />') |
---|
1642 | n/a | |
---|
1643 | n/a | def test_issue6233(self): |
---|
1644 | n/a | e = ET.XML(b"<?xml version='1.0' encoding='utf-8'?>" |
---|
1645 | n/a | b'<body>t\xc3\xa3g</body>') |
---|
1646 | n/a | self.assertEqual(ET.tostring(e, 'ascii'), |
---|
1647 | n/a | b"<?xml version='1.0' encoding='ascii'?>\n" |
---|
1648 | n/a | b'<body>tãg</body>') |
---|
1649 | n/a | e = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?>" |
---|
1650 | n/a | b'<body>t\xe3g</body>') |
---|
1651 | n/a | self.assertEqual(ET.tostring(e, 'ascii'), |
---|
1652 | n/a | b"<?xml version='1.0' encoding='ascii'?>\n" |
---|
1653 | n/a | b'<body>tãg</body>') |
---|
1654 | n/a | |
---|
1655 | n/a | def test_issue3151(self): |
---|
1656 | n/a | e = ET.XML('<prefix:localname xmlns:prefix="${stuff}"/>') |
---|
1657 | n/a | self.assertEqual(e.tag, '{${stuff}}localname') |
---|
1658 | n/a | t = ET.ElementTree(e) |
---|
1659 | n/a | self.assertEqual(ET.tostring(e), b'<ns0:localname xmlns:ns0="${stuff}" />') |
---|
1660 | n/a | |
---|
1661 | n/a | def test_issue6565(self): |
---|
1662 | n/a | elem = ET.XML("<body><tag/></body>") |
---|
1663 | n/a | self.assertEqual(summarize_list(elem), ['tag']) |
---|
1664 | n/a | newelem = ET.XML(SAMPLE_XML) |
---|
1665 | n/a | elem[:] = newelem[:] |
---|
1666 | n/a | self.assertEqual(summarize_list(elem), ['tag', 'tag', 'section']) |
---|
1667 | n/a | |
---|
1668 | n/a | def test_issue10777(self): |
---|
1669 | n/a | # Registering a namespace twice caused a "dictionary changed size during |
---|
1670 | n/a | # iteration" bug. |
---|
1671 | n/a | |
---|
1672 | n/a | ET.register_namespace('test10777', 'http://myuri/') |
---|
1673 | n/a | ET.register_namespace('test10777', 'http://myuri/') |
---|
1674 | n/a | |
---|
1675 | n/a | def test_lost_text(self): |
---|
1676 | n/a | # Issue #25902: Borrowed text can disappear |
---|
1677 | n/a | class Text: |
---|
1678 | n/a | def __bool__(self): |
---|
1679 | n/a | e.text = 'changed' |
---|
1680 | n/a | return True |
---|
1681 | n/a | |
---|
1682 | n/a | e = ET.Element('tag') |
---|
1683 | n/a | e.text = Text() |
---|
1684 | n/a | i = e.itertext() |
---|
1685 | n/a | t = next(i) |
---|
1686 | n/a | self.assertIsInstance(t, Text) |
---|
1687 | n/a | self.assertIsInstance(e.text, str) |
---|
1688 | n/a | self.assertEqual(e.text, 'changed') |
---|
1689 | n/a | |
---|
1690 | n/a | def test_lost_tail(self): |
---|
1691 | n/a | # Issue #25902: Borrowed tail can disappear |
---|
1692 | n/a | class Text: |
---|
1693 | n/a | def __bool__(self): |
---|
1694 | n/a | e[0].tail = 'changed' |
---|
1695 | n/a | return True |
---|
1696 | n/a | |
---|
1697 | n/a | e = ET.Element('root') |
---|
1698 | n/a | e.append(ET.Element('tag')) |
---|
1699 | n/a | e[0].tail = Text() |
---|
1700 | n/a | i = e.itertext() |
---|
1701 | n/a | t = next(i) |
---|
1702 | n/a | self.assertIsInstance(t, Text) |
---|
1703 | n/a | self.assertIsInstance(e[0].tail, str) |
---|
1704 | n/a | self.assertEqual(e[0].tail, 'changed') |
---|
1705 | n/a | |
---|
1706 | n/a | def test_lost_elem(self): |
---|
1707 | n/a | # Issue #25902: Borrowed element can disappear |
---|
1708 | n/a | class Tag: |
---|
1709 | n/a | def __eq__(self, other): |
---|
1710 | n/a | e[0] = ET.Element('changed') |
---|
1711 | n/a | next(i) |
---|
1712 | n/a | return True |
---|
1713 | n/a | |
---|
1714 | n/a | e = ET.Element('root') |
---|
1715 | n/a | e.append(ET.Element(Tag())) |
---|
1716 | n/a | e.append(ET.Element('tag')) |
---|
1717 | n/a | i = e.iter('tag') |
---|
1718 | n/a | try: |
---|
1719 | n/a | t = next(i) |
---|
1720 | n/a | except ValueError: |
---|
1721 | n/a | self.skipTest('generators are not reentrant') |
---|
1722 | n/a | self.assertIsInstance(t.tag, Tag) |
---|
1723 | n/a | self.assertIsInstance(e[0].tag, str) |
---|
1724 | n/a | self.assertEqual(e[0].tag, 'changed') |
---|
1725 | n/a | |
---|
1726 | n/a | |
---|
1727 | n/a | # -------------------------------------------------------------------- |
---|
1728 | n/a | |
---|
1729 | n/a | |
---|
1730 | n/a | class BasicElementTest(ElementTestCase, unittest.TestCase): |
---|
1731 | n/a | def test_augmentation_type_errors(self): |
---|
1732 | n/a | e = ET.Element('joe') |
---|
1733 | n/a | self.assertRaises(TypeError, e.append, 'b') |
---|
1734 | n/a | self.assertRaises(TypeError, e.extend, [ET.Element('bar'), 'foo']) |
---|
1735 | n/a | self.assertRaises(TypeError, e.insert, 0, 'foo') |
---|
1736 | n/a | |
---|
1737 | n/a | def test_cyclic_gc(self): |
---|
1738 | n/a | class Dummy: |
---|
1739 | n/a | pass |
---|
1740 | n/a | |
---|
1741 | n/a | # Test the shortest cycle: d->element->d |
---|
1742 | n/a | d = Dummy() |
---|
1743 | n/a | d.dummyref = ET.Element('joe', attr=d) |
---|
1744 | n/a | wref = weakref.ref(d) |
---|
1745 | n/a | del d |
---|
1746 | n/a | gc_collect() |
---|
1747 | n/a | self.assertIsNone(wref()) |
---|
1748 | n/a | |
---|
1749 | n/a | # A longer cycle: d->e->e2->d |
---|
1750 | n/a | e = ET.Element('joe') |
---|
1751 | n/a | d = Dummy() |
---|
1752 | n/a | d.dummyref = e |
---|
1753 | n/a | wref = weakref.ref(d) |
---|
1754 | n/a | e2 = ET.SubElement(e, 'foo', attr=d) |
---|
1755 | n/a | del d, e, e2 |
---|
1756 | n/a | gc_collect() |
---|
1757 | n/a | self.assertIsNone(wref()) |
---|
1758 | n/a | |
---|
1759 | n/a | # A cycle between Element objects as children of one another |
---|
1760 | n/a | # e1->e2->e3->e1 |
---|
1761 | n/a | e1 = ET.Element('e1') |
---|
1762 | n/a | e2 = ET.Element('e2') |
---|
1763 | n/a | e3 = ET.Element('e3') |
---|
1764 | n/a | e1.append(e2) |
---|
1765 | n/a | e2.append(e2) |
---|
1766 | n/a | e3.append(e1) |
---|
1767 | n/a | wref = weakref.ref(e1) |
---|
1768 | n/a | del e1, e2, e3 |
---|
1769 | n/a | gc_collect() |
---|
1770 | n/a | self.assertIsNone(wref()) |
---|
1771 | n/a | |
---|
1772 | n/a | def test_weakref(self): |
---|
1773 | n/a | flag = False |
---|
1774 | n/a | def wref_cb(w): |
---|
1775 | n/a | nonlocal flag |
---|
1776 | n/a | flag = True |
---|
1777 | n/a | e = ET.Element('e') |
---|
1778 | n/a | wref = weakref.ref(e, wref_cb) |
---|
1779 | n/a | self.assertEqual(wref().tag, 'e') |
---|
1780 | n/a | del e |
---|
1781 | n/a | self.assertEqual(flag, True) |
---|
1782 | n/a | self.assertEqual(wref(), None) |
---|
1783 | n/a | |
---|
1784 | n/a | def test_get_keyword_args(self): |
---|
1785 | n/a | e1 = ET.Element('foo' , x=1, y=2, z=3) |
---|
1786 | n/a | self.assertEqual(e1.get('x', default=7), 1) |
---|
1787 | n/a | self.assertEqual(e1.get('w', default=7), 7) |
---|
1788 | n/a | |
---|
1789 | n/a | def test_pickle(self): |
---|
1790 | n/a | # issue #16076: the C implementation wasn't pickleable. |
---|
1791 | n/a | for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): |
---|
1792 | n/a | for dumper, loader in product(self.modules, repeat=2): |
---|
1793 | n/a | e = dumper.Element('foo', bar=42) |
---|
1794 | n/a | e.text = "text goes here" |
---|
1795 | n/a | e.tail = "opposite of head" |
---|
1796 | n/a | dumper.SubElement(e, 'child').append(dumper.Element('grandchild')) |
---|
1797 | n/a | e.append(dumper.Element('child')) |
---|
1798 | n/a | e.findall('.//grandchild')[0].set('attr', 'other value') |
---|
1799 | n/a | |
---|
1800 | n/a | e2 = self.pickleRoundTrip(e, 'xml.etree.ElementTree', |
---|
1801 | n/a | dumper, loader, proto) |
---|
1802 | n/a | |
---|
1803 | n/a | self.assertEqual(e2.tag, 'foo') |
---|
1804 | n/a | self.assertEqual(e2.attrib['bar'], 42) |
---|
1805 | n/a | self.assertEqual(len(e2), 2) |
---|
1806 | n/a | self.assertEqualElements(e, e2) |
---|
1807 | n/a | |
---|
1808 | n/a | def test_pickle_issue18997(self): |
---|
1809 | n/a | for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): |
---|
1810 | n/a | for dumper, loader in product(self.modules, repeat=2): |
---|
1811 | n/a | XMLTEXT = """<?xml version="1.0"?> |
---|
1812 | n/a | <group><dogs>4</dogs> |
---|
1813 | n/a | </group>""" |
---|
1814 | n/a | e1 = dumper.fromstring(XMLTEXT) |
---|
1815 | n/a | if hasattr(e1, '__getstate__'): |
---|
1816 | n/a | self.assertEqual(e1.__getstate__()['tag'], 'group') |
---|
1817 | n/a | e2 = self.pickleRoundTrip(e1, 'xml.etree.ElementTree', |
---|
1818 | n/a | dumper, loader, proto) |
---|
1819 | n/a | self.assertEqual(e2.tag, 'group') |
---|
1820 | n/a | self.assertEqual(e2[0].tag, 'dogs') |
---|
1821 | n/a | |
---|
1822 | n/a | |
---|
1823 | n/a | class BadElementTest(ElementTestCase, unittest.TestCase): |
---|
1824 | n/a | def test_extend_mutable_list(self): |
---|
1825 | n/a | class X: |
---|
1826 | n/a | @property |
---|
1827 | n/a | def __class__(self): |
---|
1828 | n/a | L[:] = [ET.Element('baz')] |
---|
1829 | n/a | return ET.Element |
---|
1830 | n/a | L = [X()] |
---|
1831 | n/a | e = ET.Element('foo') |
---|
1832 | n/a | try: |
---|
1833 | n/a | e.extend(L) |
---|
1834 | n/a | except TypeError: |
---|
1835 | n/a | pass |
---|
1836 | n/a | |
---|
1837 | n/a | class Y(X, ET.Element): |
---|
1838 | n/a | pass |
---|
1839 | n/a | L = [Y('x')] |
---|
1840 | n/a | e = ET.Element('foo') |
---|
1841 | n/a | e.extend(L) |
---|
1842 | n/a | |
---|
1843 | n/a | def test_extend_mutable_list2(self): |
---|
1844 | n/a | class X: |
---|
1845 | n/a | @property |
---|
1846 | n/a | def __class__(self): |
---|
1847 | n/a | del L[:] |
---|
1848 | n/a | return ET.Element |
---|
1849 | n/a | L = [X(), ET.Element('baz')] |
---|
1850 | n/a | e = ET.Element('foo') |
---|
1851 | n/a | try: |
---|
1852 | n/a | e.extend(L) |
---|
1853 | n/a | except TypeError: |
---|
1854 | n/a | pass |
---|
1855 | n/a | |
---|
1856 | n/a | class Y(X, ET.Element): |
---|
1857 | n/a | pass |
---|
1858 | n/a | L = [Y('bar'), ET.Element('baz')] |
---|
1859 | n/a | e = ET.Element('foo') |
---|
1860 | n/a | e.extend(L) |
---|
1861 | n/a | |
---|
1862 | n/a | def test_remove_with_mutating(self): |
---|
1863 | n/a | class X(ET.Element): |
---|
1864 | n/a | def __eq__(self, o): |
---|
1865 | n/a | del e[:] |
---|
1866 | n/a | return False |
---|
1867 | n/a | e = ET.Element('foo') |
---|
1868 | n/a | e.extend([X('bar')]) |
---|
1869 | n/a | self.assertRaises(ValueError, e.remove, ET.Element('baz')) |
---|
1870 | n/a | |
---|
1871 | n/a | e = ET.Element('foo') |
---|
1872 | n/a | e.extend([ET.Element('bar')]) |
---|
1873 | n/a | self.assertRaises(ValueError, e.remove, X('baz')) |
---|
1874 | n/a | |
---|
1875 | n/a | def test_recursive_repr(self): |
---|
1876 | n/a | # Issue #25455 |
---|
1877 | n/a | e = ET.Element('foo') |
---|
1878 | n/a | with swap_attr(e, 'tag', e): |
---|
1879 | n/a | with self.assertRaises(RuntimeError): |
---|
1880 | n/a | repr(e) # Should not crash |
---|
1881 | n/a | |
---|
1882 | n/a | class MutatingElementPath(str): |
---|
1883 | n/a | def __new__(cls, elem, *args): |
---|
1884 | n/a | self = str.__new__(cls, *args) |
---|
1885 | n/a | self.elem = elem |
---|
1886 | n/a | return self |
---|
1887 | n/a | def __eq__(self, o): |
---|
1888 | n/a | del self.elem[:] |
---|
1889 | n/a | return True |
---|
1890 | n/a | MutatingElementPath.__hash__ = str.__hash__ |
---|
1891 | n/a | |
---|
1892 | n/a | class BadElementPath(str): |
---|
1893 | n/a | def __eq__(self, o): |
---|
1894 | n/a | raise 1/0 |
---|
1895 | n/a | BadElementPath.__hash__ = str.__hash__ |
---|
1896 | n/a | |
---|
1897 | n/a | class BadElementPathTest(ElementTestCase, unittest.TestCase): |
---|
1898 | n/a | def setUp(self): |
---|
1899 | n/a | super().setUp() |
---|
1900 | n/a | from xml.etree import ElementPath |
---|
1901 | n/a | self.path_cache = ElementPath._cache |
---|
1902 | n/a | ElementPath._cache = {} |
---|
1903 | n/a | |
---|
1904 | n/a | def tearDown(self): |
---|
1905 | n/a | from xml.etree import ElementPath |
---|
1906 | n/a | ElementPath._cache = self.path_cache |
---|
1907 | n/a | super().tearDown() |
---|
1908 | n/a | |
---|
1909 | n/a | def test_find_with_mutating(self): |
---|
1910 | n/a | e = ET.Element('foo') |
---|
1911 | n/a | e.extend([ET.Element('bar')]) |
---|
1912 | n/a | e.find(MutatingElementPath(e, 'x')) |
---|
1913 | n/a | |
---|
1914 | n/a | def test_find_with_error(self): |
---|
1915 | n/a | e = ET.Element('foo') |
---|
1916 | n/a | e.extend([ET.Element('bar')]) |
---|
1917 | n/a | try: |
---|
1918 | n/a | e.find(BadElementPath('x')) |
---|
1919 | n/a | except ZeroDivisionError: |
---|
1920 | n/a | pass |
---|
1921 | n/a | |
---|
1922 | n/a | def test_findtext_with_mutating(self): |
---|
1923 | n/a | e = ET.Element('foo') |
---|
1924 | n/a | e.extend([ET.Element('bar')]) |
---|
1925 | n/a | e.findtext(MutatingElementPath(e, 'x')) |
---|
1926 | n/a | |
---|
1927 | n/a | def test_findtext_with_error(self): |
---|
1928 | n/a | e = ET.Element('foo') |
---|
1929 | n/a | e.extend([ET.Element('bar')]) |
---|
1930 | n/a | try: |
---|
1931 | n/a | e.findtext(BadElementPath('x')) |
---|
1932 | n/a | except ZeroDivisionError: |
---|
1933 | n/a | pass |
---|
1934 | n/a | |
---|
1935 | n/a | def test_findall_with_mutating(self): |
---|
1936 | n/a | e = ET.Element('foo') |
---|
1937 | n/a | e.extend([ET.Element('bar')]) |
---|
1938 | n/a | e.findall(MutatingElementPath(e, 'x')) |
---|
1939 | n/a | |
---|
1940 | n/a | def test_findall_with_error(self): |
---|
1941 | n/a | e = ET.Element('foo') |
---|
1942 | n/a | e.extend([ET.Element('bar')]) |
---|
1943 | n/a | try: |
---|
1944 | n/a | e.findall(BadElementPath('x')) |
---|
1945 | n/a | except ZeroDivisionError: |
---|
1946 | n/a | pass |
---|
1947 | n/a | |
---|
1948 | n/a | |
---|
1949 | n/a | class ElementTreeTypeTest(unittest.TestCase): |
---|
1950 | n/a | def test_istype(self): |
---|
1951 | n/a | self.assertIsInstance(ET.ParseError, type) |
---|
1952 | n/a | self.assertIsInstance(ET.QName, type) |
---|
1953 | n/a | self.assertIsInstance(ET.ElementTree, type) |
---|
1954 | n/a | self.assertIsInstance(ET.Element, type) |
---|
1955 | n/a | self.assertIsInstance(ET.TreeBuilder, type) |
---|
1956 | n/a | self.assertIsInstance(ET.XMLParser, type) |
---|
1957 | n/a | |
---|
1958 | n/a | def test_Element_subclass_trivial(self): |
---|
1959 | n/a | class MyElement(ET.Element): |
---|
1960 | n/a | pass |
---|
1961 | n/a | |
---|
1962 | n/a | mye = MyElement('foo') |
---|
1963 | n/a | self.assertIsInstance(mye, ET.Element) |
---|
1964 | n/a | self.assertIsInstance(mye, MyElement) |
---|
1965 | n/a | self.assertEqual(mye.tag, 'foo') |
---|
1966 | n/a | |
---|
1967 | n/a | # test that attribute assignment works (issue 14849) |
---|
1968 | n/a | mye.text = "joe" |
---|
1969 | n/a | self.assertEqual(mye.text, "joe") |
---|
1970 | n/a | |
---|
1971 | n/a | def test_Element_subclass_constructor(self): |
---|
1972 | n/a | class MyElement(ET.Element): |
---|
1973 | n/a | def __init__(self, tag, attrib={}, **extra): |
---|
1974 | n/a | super(MyElement, self).__init__(tag + '__', attrib, **extra) |
---|
1975 | n/a | |
---|
1976 | n/a | mye = MyElement('foo', {'a': 1, 'b': 2}, c=3, d=4) |
---|
1977 | n/a | self.assertEqual(mye.tag, 'foo__') |
---|
1978 | n/a | self.assertEqual(sorted(mye.items()), |
---|
1979 | n/a | [('a', 1), ('b', 2), ('c', 3), ('d', 4)]) |
---|
1980 | n/a | |
---|
1981 | n/a | def test_Element_subclass_new_method(self): |
---|
1982 | n/a | class MyElement(ET.Element): |
---|
1983 | n/a | def newmethod(self): |
---|
1984 | n/a | return self.tag |
---|
1985 | n/a | |
---|
1986 | n/a | mye = MyElement('joe') |
---|
1987 | n/a | self.assertEqual(mye.newmethod(), 'joe') |
---|
1988 | n/a | |
---|
1989 | n/a | |
---|
1990 | n/a | class ElementFindTest(unittest.TestCase): |
---|
1991 | n/a | def test_find_simple(self): |
---|
1992 | n/a | e = ET.XML(SAMPLE_XML) |
---|
1993 | n/a | self.assertEqual(e.find('tag').tag, 'tag') |
---|
1994 | n/a | self.assertEqual(e.find('section/tag').tag, 'tag') |
---|
1995 | n/a | self.assertEqual(e.find('./tag').tag, 'tag') |
---|
1996 | n/a | |
---|
1997 | n/a | e[2] = ET.XML(SAMPLE_SECTION) |
---|
1998 | n/a | self.assertEqual(e.find('section/nexttag').tag, 'nexttag') |
---|
1999 | n/a | |
---|
2000 | n/a | self.assertEqual(e.findtext('./tag'), 'text') |
---|
2001 | n/a | self.assertEqual(e.findtext('section/tag'), 'subtext') |
---|
2002 | n/a | |
---|
2003 | n/a | # section/nexttag is found but has no text |
---|
2004 | n/a | self.assertEqual(e.findtext('section/nexttag'), '') |
---|
2005 | n/a | self.assertEqual(e.findtext('section/nexttag', 'default'), '') |
---|
2006 | n/a | |
---|
2007 | n/a | # tog doesn't exist and 'default' kicks in |
---|
2008 | n/a | self.assertIsNone(e.findtext('tog')) |
---|
2009 | n/a | self.assertEqual(e.findtext('tog', 'default'), 'default') |
---|
2010 | n/a | |
---|
2011 | n/a | # Issue #16922 |
---|
2012 | n/a | self.assertEqual(ET.XML('<tag><empty /></tag>').findtext('empty'), '') |
---|
2013 | n/a | |
---|
2014 | n/a | def test_find_xpath(self): |
---|
2015 | n/a | LINEAR_XML = ''' |
---|
2016 | n/a | <body> |
---|
2017 | n/a | <tag class='a'/> |
---|
2018 | n/a | <tag class='b'/> |
---|
2019 | n/a | <tag class='c'/> |
---|
2020 | n/a | <tag class='d'/> |
---|
2021 | n/a | </body>''' |
---|
2022 | n/a | e = ET.XML(LINEAR_XML) |
---|
2023 | n/a | |
---|
2024 | n/a | # Test for numeric indexing and last() |
---|
2025 | n/a | self.assertEqual(e.find('./tag[1]').attrib['class'], 'a') |
---|
2026 | n/a | self.assertEqual(e.find('./tag[2]').attrib['class'], 'b') |
---|
2027 | n/a | self.assertEqual(e.find('./tag[last()]').attrib['class'], 'd') |
---|
2028 | n/a | self.assertEqual(e.find('./tag[last()-1]').attrib['class'], 'c') |
---|
2029 | n/a | self.assertEqual(e.find('./tag[last()-2]').attrib['class'], 'b') |
---|
2030 | n/a | |
---|
2031 | n/a | self.assertRaisesRegex(SyntaxError, 'XPath', e.find, './tag[0]') |
---|
2032 | n/a | self.assertRaisesRegex(SyntaxError, 'XPath', e.find, './tag[-1]') |
---|
2033 | n/a | self.assertRaisesRegex(SyntaxError, 'XPath', e.find, './tag[last()-0]') |
---|
2034 | n/a | self.assertRaisesRegex(SyntaxError, 'XPath', e.find, './tag[last()+1]') |
---|
2035 | n/a | |
---|
2036 | n/a | def test_findall(self): |
---|
2037 | n/a | e = ET.XML(SAMPLE_XML) |
---|
2038 | n/a | e[2] = ET.XML(SAMPLE_SECTION) |
---|
2039 | n/a | self.assertEqual(summarize_list(e.findall('.')), ['body']) |
---|
2040 | n/a | self.assertEqual(summarize_list(e.findall('tag')), ['tag', 'tag']) |
---|
2041 | n/a | self.assertEqual(summarize_list(e.findall('tog')), []) |
---|
2042 | n/a | self.assertEqual(summarize_list(e.findall('tog/foo')), []) |
---|
2043 | n/a | self.assertEqual(summarize_list(e.findall('*')), |
---|
2044 | n/a | ['tag', 'tag', 'section']) |
---|
2045 | n/a | self.assertEqual(summarize_list(e.findall('.//tag')), |
---|
2046 | n/a | ['tag'] * 4) |
---|
2047 | n/a | self.assertEqual(summarize_list(e.findall('section/tag')), ['tag']) |
---|
2048 | n/a | self.assertEqual(summarize_list(e.findall('section//tag')), ['tag'] * 2) |
---|
2049 | n/a | self.assertEqual(summarize_list(e.findall('section/*')), |
---|
2050 | n/a | ['tag', 'nexttag', 'nextsection']) |
---|
2051 | n/a | self.assertEqual(summarize_list(e.findall('section//*')), |
---|
2052 | n/a | ['tag', 'nexttag', 'nextsection', 'tag']) |
---|
2053 | n/a | self.assertEqual(summarize_list(e.findall('section/.//*')), |
---|
2054 | n/a | ['tag', 'nexttag', 'nextsection', 'tag']) |
---|
2055 | n/a | self.assertEqual(summarize_list(e.findall('*/*')), |
---|
2056 | n/a | ['tag', 'nexttag', 'nextsection']) |
---|
2057 | n/a | self.assertEqual(summarize_list(e.findall('*//*')), |
---|
2058 | n/a | ['tag', 'nexttag', 'nextsection', 'tag']) |
---|
2059 | n/a | self.assertEqual(summarize_list(e.findall('*/tag')), ['tag']) |
---|
2060 | n/a | self.assertEqual(summarize_list(e.findall('*/./tag')), ['tag']) |
---|
2061 | n/a | self.assertEqual(summarize_list(e.findall('./tag')), ['tag'] * 2) |
---|
2062 | n/a | self.assertEqual(summarize_list(e.findall('././tag')), ['tag'] * 2) |
---|
2063 | n/a | |
---|
2064 | n/a | self.assertEqual(summarize_list(e.findall('.//tag[@class]')), |
---|
2065 | n/a | ['tag'] * 3) |
---|
2066 | n/a | self.assertEqual(summarize_list(e.findall('.//tag[@class="a"]')), |
---|
2067 | n/a | ['tag']) |
---|
2068 | n/a | self.assertEqual(summarize_list(e.findall('.//tag[@class="b"]')), |
---|
2069 | n/a | ['tag'] * 2) |
---|
2070 | n/a | self.assertEqual(summarize_list(e.findall('.//tag[@id]')), |
---|
2071 | n/a | ['tag']) |
---|
2072 | n/a | self.assertEqual(summarize_list(e.findall('.//section[tag]')), |
---|
2073 | n/a | ['section']) |
---|
2074 | n/a | self.assertEqual(summarize_list(e.findall('.//section[element]')), []) |
---|
2075 | n/a | self.assertEqual(summarize_list(e.findall('../tag')), []) |
---|
2076 | n/a | self.assertEqual(summarize_list(e.findall('section/../tag')), |
---|
2077 | n/a | ['tag'] * 2) |
---|
2078 | n/a | self.assertEqual(e.findall('section//'), e.findall('section//*')) |
---|
2079 | n/a | |
---|
2080 | n/a | def test_test_find_with_ns(self): |
---|
2081 | n/a | e = ET.XML(SAMPLE_XML_NS) |
---|
2082 | n/a | self.assertEqual(summarize_list(e.findall('tag')), []) |
---|
2083 | n/a | self.assertEqual( |
---|
2084 | n/a | summarize_list(e.findall("{http://effbot.org/ns}tag")), |
---|
2085 | n/a | ['{http://effbot.org/ns}tag'] * 2) |
---|
2086 | n/a | self.assertEqual( |
---|
2087 | n/a | summarize_list(e.findall(".//{http://effbot.org/ns}tag")), |
---|
2088 | n/a | ['{http://effbot.org/ns}tag'] * 3) |
---|
2089 | n/a | |
---|
2090 | n/a | def test_findall_different_nsmaps(self): |
---|
2091 | n/a | root = ET.XML(''' |
---|
2092 | n/a | <a xmlns:x="X" xmlns:y="Y"> |
---|
2093 | n/a | <x:b><c/></x:b> |
---|
2094 | n/a | <b/> |
---|
2095 | n/a | <c><x:b/><b/></c><y:b/> |
---|
2096 | n/a | </a>''') |
---|
2097 | n/a | nsmap = {'xx': 'X'} |
---|
2098 | n/a | self.assertEqual(len(root.findall(".//xx:b", namespaces=nsmap)), 2) |
---|
2099 | n/a | self.assertEqual(len(root.findall(".//b", namespaces=nsmap)), 2) |
---|
2100 | n/a | nsmap = {'xx': 'Y'} |
---|
2101 | n/a | self.assertEqual(len(root.findall(".//xx:b", namespaces=nsmap)), 1) |
---|
2102 | n/a | self.assertEqual(len(root.findall(".//b", namespaces=nsmap)), 2) |
---|
2103 | n/a | |
---|
2104 | n/a | def test_bad_find(self): |
---|
2105 | n/a | e = ET.XML(SAMPLE_XML) |
---|
2106 | n/a | with self.assertRaisesRegex(SyntaxError, 'cannot use absolute path'): |
---|
2107 | n/a | e.findall('/tag') |
---|
2108 | n/a | |
---|
2109 | n/a | def test_find_through_ElementTree(self): |
---|
2110 | n/a | e = ET.XML(SAMPLE_XML) |
---|
2111 | n/a | self.assertEqual(ET.ElementTree(e).find('tag').tag, 'tag') |
---|
2112 | n/a | self.assertEqual(ET.ElementTree(e).findtext('tag'), 'text') |
---|
2113 | n/a | self.assertEqual(summarize_list(ET.ElementTree(e).findall('tag')), |
---|
2114 | n/a | ['tag'] * 2) |
---|
2115 | n/a | # this produces a warning |
---|
2116 | n/a | self.assertEqual(summarize_list(ET.ElementTree(e).findall('//tag')), |
---|
2117 | n/a | ['tag'] * 3) |
---|
2118 | n/a | |
---|
2119 | n/a | |
---|
2120 | n/a | class ElementIterTest(unittest.TestCase): |
---|
2121 | n/a | def _ilist(self, elem, tag=None): |
---|
2122 | n/a | return summarize_list(elem.iter(tag)) |
---|
2123 | n/a | |
---|
2124 | n/a | def test_basic(self): |
---|
2125 | n/a | doc = ET.XML("<html><body>this is a <i>paragraph</i>.</body>..</html>") |
---|
2126 | n/a | self.assertEqual(self._ilist(doc), ['html', 'body', 'i']) |
---|
2127 | n/a | self.assertEqual(self._ilist(doc.find('body')), ['body', 'i']) |
---|
2128 | n/a | self.assertEqual(next(doc.iter()).tag, 'html') |
---|
2129 | n/a | self.assertEqual(''.join(doc.itertext()), 'this is a paragraph...') |
---|
2130 | n/a | self.assertEqual(''.join(doc.find('body').itertext()), |
---|
2131 | n/a | 'this is a paragraph.') |
---|
2132 | n/a | self.assertEqual(next(doc.itertext()), 'this is a ') |
---|
2133 | n/a | |
---|
2134 | n/a | # iterparse should return an iterator |
---|
2135 | n/a | sourcefile = serialize(doc, to_string=False) |
---|
2136 | n/a | self.assertEqual(next(ET.iterparse(sourcefile))[0], 'end') |
---|
2137 | n/a | |
---|
2138 | n/a | # With an explitit parser too (issue #9708) |
---|
2139 | n/a | sourcefile = serialize(doc, to_string=False) |
---|
2140 | n/a | parser = ET.XMLParser(target=ET.TreeBuilder()) |
---|
2141 | n/a | self.assertEqual(next(ET.iterparse(sourcefile, parser=parser))[0], |
---|
2142 | n/a | 'end') |
---|
2143 | n/a | |
---|
2144 | n/a | tree = ET.ElementTree(None) |
---|
2145 | n/a | self.assertRaises(AttributeError, tree.iter) |
---|
2146 | n/a | |
---|
2147 | n/a | # Issue #16913 |
---|
2148 | n/a | doc = ET.XML("<root>a&<sub>b&</sub>c&</root>") |
---|
2149 | n/a | self.assertEqual(''.join(doc.itertext()), 'a&b&c&') |
---|
2150 | n/a | |
---|
2151 | n/a | def test_corners(self): |
---|
2152 | n/a | # single root, no subelements |
---|
2153 | n/a | a = ET.Element('a') |
---|
2154 | n/a | self.assertEqual(self._ilist(a), ['a']) |
---|
2155 | n/a | |
---|
2156 | n/a | # one child |
---|
2157 | n/a | b = ET.SubElement(a, 'b') |
---|
2158 | n/a | self.assertEqual(self._ilist(a), ['a', 'b']) |
---|
2159 | n/a | |
---|
2160 | n/a | # one child and one grandchild |
---|
2161 | n/a | c = ET.SubElement(b, 'c') |
---|
2162 | n/a | self.assertEqual(self._ilist(a), ['a', 'b', 'c']) |
---|
2163 | n/a | |
---|
2164 | n/a | # two children, only first with grandchild |
---|
2165 | n/a | d = ET.SubElement(a, 'd') |
---|
2166 | n/a | self.assertEqual(self._ilist(a), ['a', 'b', 'c', 'd']) |
---|
2167 | n/a | |
---|
2168 | n/a | # replace first child by second |
---|
2169 | n/a | a[0] = a[1] |
---|
2170 | n/a | del a[1] |
---|
2171 | n/a | self.assertEqual(self._ilist(a), ['a', 'd']) |
---|
2172 | n/a | |
---|
2173 | n/a | def test_iter_by_tag(self): |
---|
2174 | n/a | doc = ET.XML(''' |
---|
2175 | n/a | <document> |
---|
2176 | n/a | <house> |
---|
2177 | n/a | <room>bedroom1</room> |
---|
2178 | n/a | <room>bedroom2</room> |
---|
2179 | n/a | </house> |
---|
2180 | n/a | <shed>nothing here |
---|
2181 | n/a | </shed> |
---|
2182 | n/a | <house> |
---|
2183 | n/a | <room>bedroom8</room> |
---|
2184 | n/a | </house> |
---|
2185 | n/a | </document>''') |
---|
2186 | n/a | |
---|
2187 | n/a | self.assertEqual(self._ilist(doc, 'room'), ['room'] * 3) |
---|
2188 | n/a | self.assertEqual(self._ilist(doc, 'house'), ['house'] * 2) |
---|
2189 | n/a | |
---|
2190 | n/a | # test that iter also accepts 'tag' as a keyword arg |
---|
2191 | n/a | self.assertEqual( |
---|
2192 | n/a | summarize_list(doc.iter(tag='room')), |
---|
2193 | n/a | ['room'] * 3) |
---|
2194 | n/a | |
---|
2195 | n/a | # make sure both tag=None and tag='*' return all tags |
---|
2196 | n/a | all_tags = ['document', 'house', 'room', 'room', |
---|
2197 | n/a | 'shed', 'house', 'room'] |
---|
2198 | n/a | self.assertEqual(summarize_list(doc.iter()), all_tags) |
---|
2199 | n/a | self.assertEqual(self._ilist(doc), all_tags) |
---|
2200 | n/a | self.assertEqual(self._ilist(doc, '*'), all_tags) |
---|
2201 | n/a | |
---|
2202 | n/a | def test_getiterator(self): |
---|
2203 | n/a | doc = ET.XML(''' |
---|
2204 | n/a | <document> |
---|
2205 | n/a | <house> |
---|
2206 | n/a | <room>bedroom1</room> |
---|
2207 | n/a | <room>bedroom2</room> |
---|
2208 | n/a | </house> |
---|
2209 | n/a | <shed>nothing here |
---|
2210 | n/a | </shed> |
---|
2211 | n/a | <house> |
---|
2212 | n/a | <room>bedroom8</room> |
---|
2213 | n/a | </house> |
---|
2214 | n/a | </document>''') |
---|
2215 | n/a | |
---|
2216 | n/a | self.assertEqual(summarize_list(doc.getiterator('room')), |
---|
2217 | n/a | ['room'] * 3) |
---|
2218 | n/a | self.assertEqual(summarize_list(doc.getiterator('house')), |
---|
2219 | n/a | ['house'] * 2) |
---|
2220 | n/a | |
---|
2221 | n/a | # test that getiterator also accepts 'tag' as a keyword arg |
---|
2222 | n/a | self.assertEqual( |
---|
2223 | n/a | summarize_list(doc.getiterator(tag='room')), |
---|
2224 | n/a | ['room'] * 3) |
---|
2225 | n/a | |
---|
2226 | n/a | # make sure both tag=None and tag='*' return all tags |
---|
2227 | n/a | all_tags = ['document', 'house', 'room', 'room', |
---|
2228 | n/a | 'shed', 'house', 'room'] |
---|
2229 | n/a | self.assertEqual(summarize_list(doc.getiterator()), all_tags) |
---|
2230 | n/a | self.assertEqual(summarize_list(doc.getiterator(None)), all_tags) |
---|
2231 | n/a | self.assertEqual(summarize_list(doc.getiterator('*')), all_tags) |
---|
2232 | n/a | |
---|
2233 | n/a | def test_copy(self): |
---|
2234 | n/a | a = ET.Element('a') |
---|
2235 | n/a | it = a.iter() |
---|
2236 | n/a | with self.assertRaises(TypeError): |
---|
2237 | n/a | copy.copy(it) |
---|
2238 | n/a | |
---|
2239 | n/a | def test_pickle(self): |
---|
2240 | n/a | a = ET.Element('a') |
---|
2241 | n/a | it = a.iter() |
---|
2242 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
2243 | n/a | with self.assertRaises((TypeError, pickle.PicklingError)): |
---|
2244 | n/a | pickle.dumps(it, proto) |
---|
2245 | n/a | |
---|
2246 | n/a | |
---|
2247 | n/a | class TreeBuilderTest(unittest.TestCase): |
---|
2248 | n/a | sample1 = ('<!DOCTYPE html PUBLIC' |
---|
2249 | n/a | ' "-//W3C//DTD XHTML 1.0 Transitional//EN"' |
---|
2250 | n/a | ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' |
---|
2251 | n/a | '<html>text<div>subtext</div>tail</html>') |
---|
2252 | n/a | |
---|
2253 | n/a | sample2 = '''<toplevel>sometext</toplevel>''' |
---|
2254 | n/a | |
---|
2255 | n/a | def _check_sample1_element(self, e): |
---|
2256 | n/a | self.assertEqual(e.tag, 'html') |
---|
2257 | n/a | self.assertEqual(e.text, 'text') |
---|
2258 | n/a | self.assertEqual(e.tail, None) |
---|
2259 | n/a | self.assertEqual(e.attrib, {}) |
---|
2260 | n/a | children = list(e) |
---|
2261 | n/a | self.assertEqual(len(children), 1) |
---|
2262 | n/a | child = children[0] |
---|
2263 | n/a | self.assertEqual(child.tag, 'div') |
---|
2264 | n/a | self.assertEqual(child.text, 'subtext') |
---|
2265 | n/a | self.assertEqual(child.tail, 'tail') |
---|
2266 | n/a | self.assertEqual(child.attrib, {}) |
---|
2267 | n/a | |
---|
2268 | n/a | def test_dummy_builder(self): |
---|
2269 | n/a | class BaseDummyBuilder: |
---|
2270 | n/a | def close(self): |
---|
2271 | n/a | return 42 |
---|
2272 | n/a | |
---|
2273 | n/a | class DummyBuilder(BaseDummyBuilder): |
---|
2274 | n/a | data = start = end = lambda *a: None |
---|
2275 | n/a | |
---|
2276 | n/a | parser = ET.XMLParser(target=DummyBuilder()) |
---|
2277 | n/a | parser.feed(self.sample1) |
---|
2278 | n/a | self.assertEqual(parser.close(), 42) |
---|
2279 | n/a | |
---|
2280 | n/a | parser = ET.XMLParser(target=BaseDummyBuilder()) |
---|
2281 | n/a | parser.feed(self.sample1) |
---|
2282 | n/a | self.assertEqual(parser.close(), 42) |
---|
2283 | n/a | |
---|
2284 | n/a | parser = ET.XMLParser(target=object()) |
---|
2285 | n/a | parser.feed(self.sample1) |
---|
2286 | n/a | self.assertIsNone(parser.close()) |
---|
2287 | n/a | |
---|
2288 | n/a | def test_treebuilder_elementfactory_none(self): |
---|
2289 | n/a | parser = ET.XMLParser(target=ET.TreeBuilder(element_factory=None)) |
---|
2290 | n/a | parser.feed(self.sample1) |
---|
2291 | n/a | e = parser.close() |
---|
2292 | n/a | self._check_sample1_element(e) |
---|
2293 | n/a | |
---|
2294 | n/a | def test_subclass(self): |
---|
2295 | n/a | class MyTreeBuilder(ET.TreeBuilder): |
---|
2296 | n/a | def foobar(self, x): |
---|
2297 | n/a | return x * 2 |
---|
2298 | n/a | |
---|
2299 | n/a | tb = MyTreeBuilder() |
---|
2300 | n/a | self.assertEqual(tb.foobar(10), 20) |
---|
2301 | n/a | |
---|
2302 | n/a | parser = ET.XMLParser(target=tb) |
---|
2303 | n/a | parser.feed(self.sample1) |
---|
2304 | n/a | |
---|
2305 | n/a | e = parser.close() |
---|
2306 | n/a | self._check_sample1_element(e) |
---|
2307 | n/a | |
---|
2308 | n/a | def test_element_factory(self): |
---|
2309 | n/a | lst = [] |
---|
2310 | n/a | def myfactory(tag, attrib): |
---|
2311 | n/a | nonlocal lst |
---|
2312 | n/a | lst.append(tag) |
---|
2313 | n/a | return ET.Element(tag, attrib) |
---|
2314 | n/a | |
---|
2315 | n/a | tb = ET.TreeBuilder(element_factory=myfactory) |
---|
2316 | n/a | parser = ET.XMLParser(target=tb) |
---|
2317 | n/a | parser.feed(self.sample2) |
---|
2318 | n/a | parser.close() |
---|
2319 | n/a | |
---|
2320 | n/a | self.assertEqual(lst, ['toplevel']) |
---|
2321 | n/a | |
---|
2322 | n/a | def _check_element_factory_class(self, cls): |
---|
2323 | n/a | tb = ET.TreeBuilder(element_factory=cls) |
---|
2324 | n/a | |
---|
2325 | n/a | parser = ET.XMLParser(target=tb) |
---|
2326 | n/a | parser.feed(self.sample1) |
---|
2327 | n/a | e = parser.close() |
---|
2328 | n/a | self.assertIsInstance(e, cls) |
---|
2329 | n/a | self._check_sample1_element(e) |
---|
2330 | n/a | |
---|
2331 | n/a | def test_element_factory_subclass(self): |
---|
2332 | n/a | class MyElement(ET.Element): |
---|
2333 | n/a | pass |
---|
2334 | n/a | self._check_element_factory_class(MyElement) |
---|
2335 | n/a | |
---|
2336 | n/a | def test_element_factory_pure_python_subclass(self): |
---|
2337 | n/a | # Mimick SimpleTAL's behaviour (issue #16089): both versions of |
---|
2338 | n/a | # TreeBuilder should be able to cope with a subclass of the |
---|
2339 | n/a | # pure Python Element class. |
---|
2340 | n/a | base = ET._Element_Py |
---|
2341 | n/a | # Not from a C extension |
---|
2342 | n/a | self.assertEqual(base.__module__, 'xml.etree.ElementTree') |
---|
2343 | n/a | # Force some multiple inheritance with a C class to make things |
---|
2344 | n/a | # more interesting. |
---|
2345 | n/a | class MyElement(base, ValueError): |
---|
2346 | n/a | pass |
---|
2347 | n/a | self._check_element_factory_class(MyElement) |
---|
2348 | n/a | |
---|
2349 | n/a | def test_doctype(self): |
---|
2350 | n/a | class DoctypeParser: |
---|
2351 | n/a | _doctype = None |
---|
2352 | n/a | |
---|
2353 | n/a | def doctype(self, name, pubid, system): |
---|
2354 | n/a | self._doctype = (name, pubid, system) |
---|
2355 | n/a | |
---|
2356 | n/a | def close(self): |
---|
2357 | n/a | return self._doctype |
---|
2358 | n/a | |
---|
2359 | n/a | parser = ET.XMLParser(target=DoctypeParser()) |
---|
2360 | n/a | parser.feed(self.sample1) |
---|
2361 | n/a | |
---|
2362 | n/a | self.assertEqual(parser.close(), |
---|
2363 | n/a | ('html', '-//W3C//DTD XHTML 1.0 Transitional//EN', |
---|
2364 | n/a | 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd')) |
---|
2365 | n/a | |
---|
2366 | n/a | |
---|
2367 | n/a | class XMLParserTest(unittest.TestCase): |
---|
2368 | n/a | sample1 = b'<file><line>22</line></file>' |
---|
2369 | n/a | sample2 = (b'<!DOCTYPE html PUBLIC' |
---|
2370 | n/a | b' "-//W3C//DTD XHTML 1.0 Transitional//EN"' |
---|
2371 | n/a | b' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' |
---|
2372 | n/a | b'<html>text</html>') |
---|
2373 | n/a | sample3 = ('<?xml version="1.0" encoding="iso-8859-1"?>\n' |
---|
2374 | n/a | '<money value="$\xa3\u20ac\U0001017b">$\xa3\u20ac\U0001017b</money>') |
---|
2375 | n/a | |
---|
2376 | n/a | def _check_sample_element(self, e): |
---|
2377 | n/a | self.assertEqual(e.tag, 'file') |
---|
2378 | n/a | self.assertEqual(e[0].tag, 'line') |
---|
2379 | n/a | self.assertEqual(e[0].text, '22') |
---|
2380 | n/a | |
---|
2381 | n/a | def test_constructor_args(self): |
---|
2382 | n/a | # Positional args. The first (html) is not supported, but should be |
---|
2383 | n/a | # nevertheless correctly accepted. |
---|
2384 | n/a | parser = ET.XMLParser(None, ET.TreeBuilder(), 'utf-8') |
---|
2385 | n/a | parser.feed(self.sample1) |
---|
2386 | n/a | self._check_sample_element(parser.close()) |
---|
2387 | n/a | |
---|
2388 | n/a | # Now as keyword args. |
---|
2389 | n/a | parser2 = ET.XMLParser(encoding='utf-8', |
---|
2390 | n/a | html=[{}], |
---|
2391 | n/a | target=ET.TreeBuilder()) |
---|
2392 | n/a | parser2.feed(self.sample1) |
---|
2393 | n/a | self._check_sample_element(parser2.close()) |
---|
2394 | n/a | |
---|
2395 | n/a | def test_subclass(self): |
---|
2396 | n/a | class MyParser(ET.XMLParser): |
---|
2397 | n/a | pass |
---|
2398 | n/a | parser = MyParser() |
---|
2399 | n/a | parser.feed(self.sample1) |
---|
2400 | n/a | self._check_sample_element(parser.close()) |
---|
2401 | n/a | |
---|
2402 | n/a | def test_doctype_warning(self): |
---|
2403 | n/a | parser = ET.XMLParser() |
---|
2404 | n/a | with self.assertWarns(DeprecationWarning): |
---|
2405 | n/a | parser.doctype('html', '-//W3C//DTD XHTML 1.0 Transitional//EN', |
---|
2406 | n/a | 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd') |
---|
2407 | n/a | parser.feed('<html/>') |
---|
2408 | n/a | parser.close() |
---|
2409 | n/a | |
---|
2410 | n/a | with warnings.catch_warnings(): |
---|
2411 | n/a | warnings.simplefilter('error', DeprecationWarning) |
---|
2412 | n/a | parser = ET.XMLParser() |
---|
2413 | n/a | parser.feed(self.sample2) |
---|
2414 | n/a | parser.close() |
---|
2415 | n/a | |
---|
2416 | n/a | def test_subclass_doctype(self): |
---|
2417 | n/a | _doctype = None |
---|
2418 | n/a | class MyParserWithDoctype(ET.XMLParser): |
---|
2419 | n/a | def doctype(self, name, pubid, system): |
---|
2420 | n/a | nonlocal _doctype |
---|
2421 | n/a | _doctype = (name, pubid, system) |
---|
2422 | n/a | |
---|
2423 | n/a | parser = MyParserWithDoctype() |
---|
2424 | n/a | with self.assertWarns(DeprecationWarning): |
---|
2425 | n/a | parser.feed(self.sample2) |
---|
2426 | n/a | parser.close() |
---|
2427 | n/a | self.assertEqual(_doctype, |
---|
2428 | n/a | ('html', '-//W3C//DTD XHTML 1.0 Transitional//EN', |
---|
2429 | n/a | 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd')) |
---|
2430 | n/a | |
---|
2431 | n/a | _doctype = _doctype2 = None |
---|
2432 | n/a | with warnings.catch_warnings(): |
---|
2433 | n/a | warnings.simplefilter('error', DeprecationWarning) |
---|
2434 | n/a | class DoctypeParser: |
---|
2435 | n/a | def doctype(self, name, pubid, system): |
---|
2436 | n/a | nonlocal _doctype2 |
---|
2437 | n/a | _doctype2 = (name, pubid, system) |
---|
2438 | n/a | |
---|
2439 | n/a | parser = MyParserWithDoctype(target=DoctypeParser()) |
---|
2440 | n/a | parser.feed(self.sample2) |
---|
2441 | n/a | parser.close() |
---|
2442 | n/a | self.assertIsNone(_doctype) |
---|
2443 | n/a | self.assertEqual(_doctype2, |
---|
2444 | n/a | ('html', '-//W3C//DTD XHTML 1.0 Transitional//EN', |
---|
2445 | n/a | 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd')) |
---|
2446 | n/a | |
---|
2447 | n/a | def test_inherited_doctype(self): |
---|
2448 | n/a | '''Ensure that ordinary usage is not deprecated (Issue 19176)''' |
---|
2449 | n/a | with warnings.catch_warnings(): |
---|
2450 | n/a | warnings.simplefilter('error', DeprecationWarning) |
---|
2451 | n/a | class MyParserWithoutDoctype(ET.XMLParser): |
---|
2452 | n/a | pass |
---|
2453 | n/a | parser = MyParserWithoutDoctype() |
---|
2454 | n/a | parser.feed(self.sample2) |
---|
2455 | n/a | parser.close() |
---|
2456 | n/a | |
---|
2457 | n/a | def test_parse_string(self): |
---|
2458 | n/a | parser = ET.XMLParser(target=ET.TreeBuilder()) |
---|
2459 | n/a | parser.feed(self.sample3) |
---|
2460 | n/a | e = parser.close() |
---|
2461 | n/a | self.assertEqual(e.tag, 'money') |
---|
2462 | n/a | self.assertEqual(e.attrib['value'], '$\xa3\u20ac\U0001017b') |
---|
2463 | n/a | self.assertEqual(e.text, '$\xa3\u20ac\U0001017b') |
---|
2464 | n/a | |
---|
2465 | n/a | |
---|
2466 | n/a | class NamespaceParseTest(unittest.TestCase): |
---|
2467 | n/a | def test_find_with_namespace(self): |
---|
2468 | n/a | nsmap = {'h': 'hello', 'f': 'foo'} |
---|
2469 | n/a | doc = ET.fromstring(SAMPLE_XML_NS_ELEMS) |
---|
2470 | n/a | |
---|
2471 | n/a | self.assertEqual(len(doc.findall('{hello}table', nsmap)), 1) |
---|
2472 | n/a | self.assertEqual(len(doc.findall('.//{hello}td', nsmap)), 2) |
---|
2473 | n/a | self.assertEqual(len(doc.findall('.//{foo}name', nsmap)), 1) |
---|
2474 | n/a | |
---|
2475 | n/a | |
---|
2476 | n/a | class ElementSlicingTest(unittest.TestCase): |
---|
2477 | n/a | def _elem_tags(self, elemlist): |
---|
2478 | n/a | return [e.tag for e in elemlist] |
---|
2479 | n/a | |
---|
2480 | n/a | def _subelem_tags(self, elem): |
---|
2481 | n/a | return self._elem_tags(list(elem)) |
---|
2482 | n/a | |
---|
2483 | n/a | def _make_elem_with_children(self, numchildren): |
---|
2484 | n/a | """Create an Element with a tag 'a', with the given amount of children |
---|
2485 | n/a | named 'a0', 'a1' ... and so on. |
---|
2486 | n/a | |
---|
2487 | n/a | """ |
---|
2488 | n/a | e = ET.Element('a') |
---|
2489 | n/a | for i in range(numchildren): |
---|
2490 | n/a | ET.SubElement(e, 'a%s' % i) |
---|
2491 | n/a | return e |
---|
2492 | n/a | |
---|
2493 | n/a | def test_getslice_single_index(self): |
---|
2494 | n/a | e = self._make_elem_with_children(10) |
---|
2495 | n/a | |
---|
2496 | n/a | self.assertEqual(e[1].tag, 'a1') |
---|
2497 | n/a | self.assertEqual(e[-2].tag, 'a8') |
---|
2498 | n/a | |
---|
2499 | n/a | self.assertRaises(IndexError, lambda: e[12]) |
---|
2500 | n/a | self.assertRaises(IndexError, lambda: e[-12]) |
---|
2501 | n/a | |
---|
2502 | n/a | def test_getslice_range(self): |
---|
2503 | n/a | e = self._make_elem_with_children(6) |
---|
2504 | n/a | |
---|
2505 | n/a | self.assertEqual(self._elem_tags(e[3:]), ['a3', 'a4', 'a5']) |
---|
2506 | n/a | self.assertEqual(self._elem_tags(e[3:6]), ['a3', 'a4', 'a5']) |
---|
2507 | n/a | self.assertEqual(self._elem_tags(e[3:16]), ['a3', 'a4', 'a5']) |
---|
2508 | n/a | self.assertEqual(self._elem_tags(e[3:5]), ['a3', 'a4']) |
---|
2509 | n/a | self.assertEqual(self._elem_tags(e[3:-1]), ['a3', 'a4']) |
---|
2510 | n/a | self.assertEqual(self._elem_tags(e[:2]), ['a0', 'a1']) |
---|
2511 | n/a | |
---|
2512 | n/a | def test_getslice_steps(self): |
---|
2513 | n/a | e = self._make_elem_with_children(10) |
---|
2514 | n/a | |
---|
2515 | n/a | self.assertEqual(self._elem_tags(e[8:10:1]), ['a8', 'a9']) |
---|
2516 | n/a | self.assertEqual(self._elem_tags(e[::3]), ['a0', 'a3', 'a6', 'a9']) |
---|
2517 | n/a | self.assertEqual(self._elem_tags(e[::8]), ['a0', 'a8']) |
---|
2518 | n/a | self.assertEqual(self._elem_tags(e[1::8]), ['a1', 'a9']) |
---|
2519 | n/a | self.assertEqual(self._elem_tags(e[3::sys.maxsize]), ['a3']) |
---|
2520 | n/a | self.assertEqual(self._elem_tags(e[3::sys.maxsize<<64]), ['a3']) |
---|
2521 | n/a | |
---|
2522 | n/a | def test_getslice_negative_steps(self): |
---|
2523 | n/a | e = self._make_elem_with_children(4) |
---|
2524 | n/a | |
---|
2525 | n/a | self.assertEqual(self._elem_tags(e[::-1]), ['a3', 'a2', 'a1', 'a0']) |
---|
2526 | n/a | self.assertEqual(self._elem_tags(e[::-2]), ['a3', 'a1']) |
---|
2527 | n/a | self.assertEqual(self._elem_tags(e[3::-sys.maxsize]), ['a3']) |
---|
2528 | n/a | self.assertEqual(self._elem_tags(e[3::-sys.maxsize-1]), ['a3']) |
---|
2529 | n/a | self.assertEqual(self._elem_tags(e[3::-sys.maxsize<<64]), ['a3']) |
---|
2530 | n/a | |
---|
2531 | n/a | def test_delslice(self): |
---|
2532 | n/a | e = self._make_elem_with_children(4) |
---|
2533 | n/a | del e[0:2] |
---|
2534 | n/a | self.assertEqual(self._subelem_tags(e), ['a2', 'a3']) |
---|
2535 | n/a | |
---|
2536 | n/a | e = self._make_elem_with_children(4) |
---|
2537 | n/a | del e[0:] |
---|
2538 | n/a | self.assertEqual(self._subelem_tags(e), []) |
---|
2539 | n/a | |
---|
2540 | n/a | e = self._make_elem_with_children(4) |
---|
2541 | n/a | del e[::-1] |
---|
2542 | n/a | self.assertEqual(self._subelem_tags(e), []) |
---|
2543 | n/a | |
---|
2544 | n/a | e = self._make_elem_with_children(4) |
---|
2545 | n/a | del e[::-2] |
---|
2546 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'a2']) |
---|
2547 | n/a | |
---|
2548 | n/a | e = self._make_elem_with_children(4) |
---|
2549 | n/a | del e[1::2] |
---|
2550 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'a2']) |
---|
2551 | n/a | |
---|
2552 | n/a | e = self._make_elem_with_children(2) |
---|
2553 | n/a | del e[::2] |
---|
2554 | n/a | self.assertEqual(self._subelem_tags(e), ['a1']) |
---|
2555 | n/a | |
---|
2556 | n/a | def test_setslice_single_index(self): |
---|
2557 | n/a | e = self._make_elem_with_children(4) |
---|
2558 | n/a | e[1] = ET.Element('b') |
---|
2559 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'b', 'a2', 'a3']) |
---|
2560 | n/a | |
---|
2561 | n/a | e[-2] = ET.Element('c') |
---|
2562 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'b', 'c', 'a3']) |
---|
2563 | n/a | |
---|
2564 | n/a | with self.assertRaises(IndexError): |
---|
2565 | n/a | e[5] = ET.Element('d') |
---|
2566 | n/a | with self.assertRaises(IndexError): |
---|
2567 | n/a | e[-5] = ET.Element('d') |
---|
2568 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'b', 'c', 'a3']) |
---|
2569 | n/a | |
---|
2570 | n/a | def test_setslice_range(self): |
---|
2571 | n/a | e = self._make_elem_with_children(4) |
---|
2572 | n/a | e[1:3] = [ET.Element('b%s' % i) for i in range(2)] |
---|
2573 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'b0', 'b1', 'a3']) |
---|
2574 | n/a | |
---|
2575 | n/a | e = self._make_elem_with_children(4) |
---|
2576 | n/a | e[1:3] = [ET.Element('b')] |
---|
2577 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'b', 'a3']) |
---|
2578 | n/a | |
---|
2579 | n/a | e = self._make_elem_with_children(4) |
---|
2580 | n/a | e[1:3] = [ET.Element('b%s' % i) for i in range(3)] |
---|
2581 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'b0', 'b1', 'b2', 'a3']) |
---|
2582 | n/a | |
---|
2583 | n/a | def test_setslice_steps(self): |
---|
2584 | n/a | e = self._make_elem_with_children(6) |
---|
2585 | n/a | e[1:5:2] = [ET.Element('b%s' % i) for i in range(2)] |
---|
2586 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'b0', 'a2', 'b1', 'a4', 'a5']) |
---|
2587 | n/a | |
---|
2588 | n/a | e = self._make_elem_with_children(6) |
---|
2589 | n/a | with self.assertRaises(ValueError): |
---|
2590 | n/a | e[1:5:2] = [ET.Element('b')] |
---|
2591 | n/a | with self.assertRaises(ValueError): |
---|
2592 | n/a | e[1:5:2] = [ET.Element('b%s' % i) for i in range(3)] |
---|
2593 | n/a | with self.assertRaises(ValueError): |
---|
2594 | n/a | e[1:5:2] = [] |
---|
2595 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'a1', 'a2', 'a3', 'a4', 'a5']) |
---|
2596 | n/a | |
---|
2597 | n/a | e = self._make_elem_with_children(4) |
---|
2598 | n/a | e[1::sys.maxsize] = [ET.Element('b')] |
---|
2599 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'b', 'a2', 'a3']) |
---|
2600 | n/a | e[1::sys.maxsize<<64] = [ET.Element('c')] |
---|
2601 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'c', 'a2', 'a3']) |
---|
2602 | n/a | |
---|
2603 | n/a | def test_setslice_negative_steps(self): |
---|
2604 | n/a | e = self._make_elem_with_children(4) |
---|
2605 | n/a | e[2:0:-1] = [ET.Element('b%s' % i) for i in range(2)] |
---|
2606 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'b1', 'b0', 'a3']) |
---|
2607 | n/a | |
---|
2608 | n/a | e = self._make_elem_with_children(4) |
---|
2609 | n/a | with self.assertRaises(ValueError): |
---|
2610 | n/a | e[2:0:-1] = [ET.Element('b')] |
---|
2611 | n/a | with self.assertRaises(ValueError): |
---|
2612 | n/a | e[2:0:-1] = [ET.Element('b%s' % i) for i in range(3)] |
---|
2613 | n/a | with self.assertRaises(ValueError): |
---|
2614 | n/a | e[2:0:-1] = [] |
---|
2615 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'a1', 'a2', 'a3']) |
---|
2616 | n/a | |
---|
2617 | n/a | e = self._make_elem_with_children(4) |
---|
2618 | n/a | e[1::-sys.maxsize] = [ET.Element('b')] |
---|
2619 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'b', 'a2', 'a3']) |
---|
2620 | n/a | e[1::-sys.maxsize-1] = [ET.Element('c')] |
---|
2621 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'c', 'a2', 'a3']) |
---|
2622 | n/a | e[1::-sys.maxsize<<64] = [ET.Element('d')] |
---|
2623 | n/a | self.assertEqual(self._subelem_tags(e), ['a0', 'd', 'a2', 'a3']) |
---|
2624 | n/a | |
---|
2625 | n/a | |
---|
2626 | n/a | class IOTest(unittest.TestCase): |
---|
2627 | n/a | def tearDown(self): |
---|
2628 | n/a | support.unlink(TESTFN) |
---|
2629 | n/a | |
---|
2630 | n/a | def test_encoding(self): |
---|
2631 | n/a | # Test encoding issues. |
---|
2632 | n/a | elem = ET.Element("tag") |
---|
2633 | n/a | elem.text = "abc" |
---|
2634 | n/a | self.assertEqual(serialize(elem), '<tag>abc</tag>') |
---|
2635 | n/a | for enc in ("utf-8", "us-ascii"): |
---|
2636 | n/a | with self.subTest(enc): |
---|
2637 | n/a | self.assertEqual(serialize(elem, encoding=enc), |
---|
2638 | n/a | b'<tag>abc</tag>') |
---|
2639 | n/a | self.assertEqual(serialize(elem, encoding=enc.upper()), |
---|
2640 | n/a | b'<tag>abc</tag>') |
---|
2641 | n/a | for enc in ("iso-8859-1", "utf-16", "utf-32"): |
---|
2642 | n/a | with self.subTest(enc): |
---|
2643 | n/a | self.assertEqual(serialize(elem, encoding=enc), |
---|
2644 | n/a | ("<?xml version='1.0' encoding='%s'?>\n" |
---|
2645 | n/a | "<tag>abc</tag>" % enc).encode(enc)) |
---|
2646 | n/a | upper = enc.upper() |
---|
2647 | n/a | self.assertEqual(serialize(elem, encoding=upper), |
---|
2648 | n/a | ("<?xml version='1.0' encoding='%s'?>\n" |
---|
2649 | n/a | "<tag>abc</tag>" % upper).encode(enc)) |
---|
2650 | n/a | |
---|
2651 | n/a | elem = ET.Element("tag") |
---|
2652 | n/a | elem.text = "<&\"\'>" |
---|
2653 | n/a | self.assertEqual(serialize(elem), '<tag><&"\'></tag>') |
---|
2654 | n/a | self.assertEqual(serialize(elem, encoding="utf-8"), |
---|
2655 | n/a | b'<tag><&"\'></tag>') |
---|
2656 | n/a | self.assertEqual(serialize(elem, encoding="us-ascii"), |
---|
2657 | n/a | b'<tag><&"\'></tag>') |
---|
2658 | n/a | for enc in ("iso-8859-1", "utf-16", "utf-32"): |
---|
2659 | n/a | self.assertEqual(serialize(elem, encoding=enc), |
---|
2660 | n/a | ("<?xml version='1.0' encoding='%s'?>\n" |
---|
2661 | n/a | "<tag><&\"'></tag>" % enc).encode(enc)) |
---|
2662 | n/a | |
---|
2663 | n/a | elem = ET.Element("tag") |
---|
2664 | n/a | elem.attrib["key"] = "<&\"\'>" |
---|
2665 | n/a | self.assertEqual(serialize(elem), '<tag key="<&"\'>" />') |
---|
2666 | n/a | self.assertEqual(serialize(elem, encoding="utf-8"), |
---|
2667 | n/a | b'<tag key="<&"\'>" />') |
---|
2668 | n/a | self.assertEqual(serialize(elem, encoding="us-ascii"), |
---|
2669 | n/a | b'<tag key="<&"\'>" />') |
---|
2670 | n/a | for enc in ("iso-8859-1", "utf-16", "utf-32"): |
---|
2671 | n/a | self.assertEqual(serialize(elem, encoding=enc), |
---|
2672 | n/a | ("<?xml version='1.0' encoding='%s'?>\n" |
---|
2673 | n/a | "<tag key=\"<&"'>\" />" % enc).encode(enc)) |
---|
2674 | n/a | |
---|
2675 | n/a | elem = ET.Element("tag") |
---|
2676 | n/a | elem.text = '\xe5\xf6\xf6<>' |
---|
2677 | n/a | self.assertEqual(serialize(elem), '<tag>\xe5\xf6\xf6<></tag>') |
---|
2678 | n/a | self.assertEqual(serialize(elem, encoding="utf-8"), |
---|
2679 | n/a | b'<tag>\xc3\xa5\xc3\xb6\xc3\xb6<></tag>') |
---|
2680 | n/a | self.assertEqual(serialize(elem, encoding="us-ascii"), |
---|
2681 | n/a | b'<tag>åöö<></tag>') |
---|
2682 | n/a | for enc in ("iso-8859-1", "utf-16", "utf-32"): |
---|
2683 | n/a | self.assertEqual(serialize(elem, encoding=enc), |
---|
2684 | n/a | ("<?xml version='1.0' encoding='%s'?>\n" |
---|
2685 | n/a | "<tag>åöö<></tag>" % enc).encode(enc)) |
---|
2686 | n/a | |
---|
2687 | n/a | elem = ET.Element("tag") |
---|
2688 | n/a | elem.attrib["key"] = '\xe5\xf6\xf6<>' |
---|
2689 | n/a | self.assertEqual(serialize(elem), '<tag key="\xe5\xf6\xf6<>" />') |
---|
2690 | n/a | self.assertEqual(serialize(elem, encoding="utf-8"), |
---|
2691 | n/a | b'<tag key="\xc3\xa5\xc3\xb6\xc3\xb6<>" />') |
---|
2692 | n/a | self.assertEqual(serialize(elem, encoding="us-ascii"), |
---|
2693 | n/a | b'<tag key="åöö<>" />') |
---|
2694 | n/a | for enc in ("iso-8859-1", "utf-16", "utf-16le", "utf-16be", "utf-32"): |
---|
2695 | n/a | self.assertEqual(serialize(elem, encoding=enc), |
---|
2696 | n/a | ("<?xml version='1.0' encoding='%s'?>\n" |
---|
2697 | n/a | "<tag key=\"åöö<>\" />" % enc).encode(enc)) |
---|
2698 | n/a | |
---|
2699 | n/a | def test_write_to_filename(self): |
---|
2700 | n/a | tree = ET.ElementTree(ET.XML('''<site />''')) |
---|
2701 | n/a | tree.write(TESTFN) |
---|
2702 | n/a | with open(TESTFN, 'rb') as f: |
---|
2703 | n/a | self.assertEqual(f.read(), b'''<site />''') |
---|
2704 | n/a | |
---|
2705 | n/a | def test_write_to_text_file(self): |
---|
2706 | n/a | tree = ET.ElementTree(ET.XML('''<site />''')) |
---|
2707 | n/a | with open(TESTFN, 'w', encoding='utf-8') as f: |
---|
2708 | n/a | tree.write(f, encoding='unicode') |
---|
2709 | n/a | self.assertFalse(f.closed) |
---|
2710 | n/a | with open(TESTFN, 'rb') as f: |
---|
2711 | n/a | self.assertEqual(f.read(), b'''<site />''') |
---|
2712 | n/a | |
---|
2713 | n/a | def test_write_to_binary_file(self): |
---|
2714 | n/a | tree = ET.ElementTree(ET.XML('''<site />''')) |
---|
2715 | n/a | with open(TESTFN, 'wb') as f: |
---|
2716 | n/a | tree.write(f) |
---|
2717 | n/a | self.assertFalse(f.closed) |
---|
2718 | n/a | with open(TESTFN, 'rb') as f: |
---|
2719 | n/a | self.assertEqual(f.read(), b'''<site />''') |
---|
2720 | n/a | |
---|
2721 | n/a | def test_write_to_binary_file_with_bom(self): |
---|
2722 | n/a | tree = ET.ElementTree(ET.XML('''<site />''')) |
---|
2723 | n/a | # test BOM writing to buffered file |
---|
2724 | n/a | with open(TESTFN, 'wb') as f: |
---|
2725 | n/a | tree.write(f, encoding='utf-16') |
---|
2726 | n/a | self.assertFalse(f.closed) |
---|
2727 | n/a | with open(TESTFN, 'rb') as f: |
---|
2728 | n/a | self.assertEqual(f.read(), |
---|
2729 | n/a | '''<?xml version='1.0' encoding='utf-16'?>\n''' |
---|
2730 | n/a | '''<site />'''.encode("utf-16")) |
---|
2731 | n/a | # test BOM writing to non-buffered file |
---|
2732 | n/a | with open(TESTFN, 'wb', buffering=0) as f: |
---|
2733 | n/a | tree.write(f, encoding='utf-16') |
---|
2734 | n/a | self.assertFalse(f.closed) |
---|
2735 | n/a | with open(TESTFN, 'rb') as f: |
---|
2736 | n/a | self.assertEqual(f.read(), |
---|
2737 | n/a | '''<?xml version='1.0' encoding='utf-16'?>\n''' |
---|
2738 | n/a | '''<site />'''.encode("utf-16")) |
---|
2739 | n/a | |
---|
2740 | n/a | def test_read_from_stringio(self): |
---|
2741 | n/a | tree = ET.ElementTree() |
---|
2742 | n/a | stream = io.StringIO('''<?xml version="1.0"?><site></site>''') |
---|
2743 | n/a | tree.parse(stream) |
---|
2744 | n/a | self.assertEqual(tree.getroot().tag, 'site') |
---|
2745 | n/a | |
---|
2746 | n/a | def test_write_to_stringio(self): |
---|
2747 | n/a | tree = ET.ElementTree(ET.XML('''<site />''')) |
---|
2748 | n/a | stream = io.StringIO() |
---|
2749 | n/a | tree.write(stream, encoding='unicode') |
---|
2750 | n/a | self.assertEqual(stream.getvalue(), '''<site />''') |
---|
2751 | n/a | |
---|
2752 | n/a | def test_read_from_bytesio(self): |
---|
2753 | n/a | tree = ET.ElementTree() |
---|
2754 | n/a | raw = io.BytesIO(b'''<?xml version="1.0"?><site></site>''') |
---|
2755 | n/a | tree.parse(raw) |
---|
2756 | n/a | self.assertEqual(tree.getroot().tag, 'site') |
---|
2757 | n/a | |
---|
2758 | n/a | def test_write_to_bytesio(self): |
---|
2759 | n/a | tree = ET.ElementTree(ET.XML('''<site />''')) |
---|
2760 | n/a | raw = io.BytesIO() |
---|
2761 | n/a | tree.write(raw) |
---|
2762 | n/a | self.assertEqual(raw.getvalue(), b'''<site />''') |
---|
2763 | n/a | |
---|
2764 | n/a | class dummy: |
---|
2765 | n/a | pass |
---|
2766 | n/a | |
---|
2767 | n/a | def test_read_from_user_text_reader(self): |
---|
2768 | n/a | stream = io.StringIO('''<?xml version="1.0"?><site></site>''') |
---|
2769 | n/a | reader = self.dummy() |
---|
2770 | n/a | reader.read = stream.read |
---|
2771 | n/a | tree = ET.ElementTree() |
---|
2772 | n/a | tree.parse(reader) |
---|
2773 | n/a | self.assertEqual(tree.getroot().tag, 'site') |
---|
2774 | n/a | |
---|
2775 | n/a | def test_write_to_user_text_writer(self): |
---|
2776 | n/a | tree = ET.ElementTree(ET.XML('''<site />''')) |
---|
2777 | n/a | stream = io.StringIO() |
---|
2778 | n/a | writer = self.dummy() |
---|
2779 | n/a | writer.write = stream.write |
---|
2780 | n/a | tree.write(writer, encoding='unicode') |
---|
2781 | n/a | self.assertEqual(stream.getvalue(), '''<site />''') |
---|
2782 | n/a | |
---|
2783 | n/a | def test_read_from_user_binary_reader(self): |
---|
2784 | n/a | raw = io.BytesIO(b'''<?xml version="1.0"?><site></site>''') |
---|
2785 | n/a | reader = self.dummy() |
---|
2786 | n/a | reader.read = raw.read |
---|
2787 | n/a | tree = ET.ElementTree() |
---|
2788 | n/a | tree.parse(reader) |
---|
2789 | n/a | self.assertEqual(tree.getroot().tag, 'site') |
---|
2790 | n/a | tree = ET.ElementTree() |
---|
2791 | n/a | |
---|
2792 | n/a | def test_write_to_user_binary_writer(self): |
---|
2793 | n/a | tree = ET.ElementTree(ET.XML('''<site />''')) |
---|
2794 | n/a | raw = io.BytesIO() |
---|
2795 | n/a | writer = self.dummy() |
---|
2796 | n/a | writer.write = raw.write |
---|
2797 | n/a | tree.write(writer) |
---|
2798 | n/a | self.assertEqual(raw.getvalue(), b'''<site />''') |
---|
2799 | n/a | |
---|
2800 | n/a | def test_write_to_user_binary_writer_with_bom(self): |
---|
2801 | n/a | tree = ET.ElementTree(ET.XML('''<site />''')) |
---|
2802 | n/a | raw = io.BytesIO() |
---|
2803 | n/a | writer = self.dummy() |
---|
2804 | n/a | writer.write = raw.write |
---|
2805 | n/a | writer.seekable = lambda: True |
---|
2806 | n/a | writer.tell = raw.tell |
---|
2807 | n/a | tree.write(writer, encoding="utf-16") |
---|
2808 | n/a | self.assertEqual(raw.getvalue(), |
---|
2809 | n/a | '''<?xml version='1.0' encoding='utf-16'?>\n''' |
---|
2810 | n/a | '''<site />'''.encode("utf-16")) |
---|
2811 | n/a | |
---|
2812 | n/a | def test_tostringlist_invariant(self): |
---|
2813 | n/a | root = ET.fromstring('<tag>foo</tag>') |
---|
2814 | n/a | self.assertEqual( |
---|
2815 | n/a | ET.tostring(root, 'unicode'), |
---|
2816 | n/a | ''.join(ET.tostringlist(root, 'unicode'))) |
---|
2817 | n/a | self.assertEqual( |
---|
2818 | n/a | ET.tostring(root, 'utf-16'), |
---|
2819 | n/a | b''.join(ET.tostringlist(root, 'utf-16'))) |
---|
2820 | n/a | |
---|
2821 | n/a | def test_short_empty_elements(self): |
---|
2822 | n/a | root = ET.fromstring('<tag>a<x />b<y></y>c</tag>') |
---|
2823 | n/a | self.assertEqual( |
---|
2824 | n/a | ET.tostring(root, 'unicode'), |
---|
2825 | n/a | '<tag>a<x />b<y />c</tag>') |
---|
2826 | n/a | self.assertEqual( |
---|
2827 | n/a | ET.tostring(root, 'unicode', short_empty_elements=True), |
---|
2828 | n/a | '<tag>a<x />b<y />c</tag>') |
---|
2829 | n/a | self.assertEqual( |
---|
2830 | n/a | ET.tostring(root, 'unicode', short_empty_elements=False), |
---|
2831 | n/a | '<tag>a<x></x>b<y></y>c</tag>') |
---|
2832 | n/a | |
---|
2833 | n/a | |
---|
2834 | n/a | class ParseErrorTest(unittest.TestCase): |
---|
2835 | n/a | def test_subclass(self): |
---|
2836 | n/a | self.assertIsInstance(ET.ParseError(), SyntaxError) |
---|
2837 | n/a | |
---|
2838 | n/a | def _get_error(self, s): |
---|
2839 | n/a | try: |
---|
2840 | n/a | ET.fromstring(s) |
---|
2841 | n/a | except ET.ParseError as e: |
---|
2842 | n/a | return e |
---|
2843 | n/a | |
---|
2844 | n/a | def test_error_position(self): |
---|
2845 | n/a | self.assertEqual(self._get_error('foo').position, (1, 0)) |
---|
2846 | n/a | self.assertEqual(self._get_error('<tag>&foo;</tag>').position, (1, 5)) |
---|
2847 | n/a | self.assertEqual(self._get_error('foobar<').position, (1, 6)) |
---|
2848 | n/a | |
---|
2849 | n/a | def test_error_code(self): |
---|
2850 | n/a | import xml.parsers.expat.errors as ERRORS |
---|
2851 | n/a | self.assertEqual(self._get_error('foo').code, |
---|
2852 | n/a | ERRORS.codes[ERRORS.XML_ERROR_SYNTAX]) |
---|
2853 | n/a | |
---|
2854 | n/a | |
---|
2855 | n/a | class KeywordArgsTest(unittest.TestCase): |
---|
2856 | n/a | # Test various issues with keyword arguments passed to ET.Element |
---|
2857 | n/a | # constructor and methods |
---|
2858 | n/a | def test_issue14818(self): |
---|
2859 | n/a | x = ET.XML("<a>foo</a>") |
---|
2860 | n/a | self.assertEqual(x.find('a', None), |
---|
2861 | n/a | x.find(path='a', namespaces=None)) |
---|
2862 | n/a | self.assertEqual(x.findtext('a', None, None), |
---|
2863 | n/a | x.findtext(path='a', default=None, namespaces=None)) |
---|
2864 | n/a | self.assertEqual(x.findall('a', None), |
---|
2865 | n/a | x.findall(path='a', namespaces=None)) |
---|
2866 | n/a | self.assertEqual(list(x.iterfind('a', None)), |
---|
2867 | n/a | list(x.iterfind(path='a', namespaces=None))) |
---|
2868 | n/a | |
---|
2869 | n/a | self.assertEqual(ET.Element('a').attrib, {}) |
---|
2870 | n/a | elements = [ |
---|
2871 | n/a | ET.Element('a', dict(href="#", id="foo")), |
---|
2872 | n/a | ET.Element('a', attrib=dict(href="#", id="foo")), |
---|
2873 | n/a | ET.Element('a', dict(href="#"), id="foo"), |
---|
2874 | n/a | ET.Element('a', href="#", id="foo"), |
---|
2875 | n/a | ET.Element('a', dict(href="#", id="foo"), href="#", id="foo"), |
---|
2876 | n/a | ] |
---|
2877 | n/a | for e in elements: |
---|
2878 | n/a | self.assertEqual(e.tag, 'a') |
---|
2879 | n/a | self.assertEqual(e.attrib, dict(href="#", id="foo")) |
---|
2880 | n/a | |
---|
2881 | n/a | e2 = ET.SubElement(elements[0], 'foobar', attrib={'key1': 'value1'}) |
---|
2882 | n/a | self.assertEqual(e2.attrib['key1'], 'value1') |
---|
2883 | n/a | |
---|
2884 | n/a | with self.assertRaisesRegex(TypeError, 'must be dict, not str'): |
---|
2885 | n/a | ET.Element('a', "I'm not a dict") |
---|
2886 | n/a | with self.assertRaisesRegex(TypeError, 'must be dict, not str'): |
---|
2887 | n/a | ET.Element('a', attrib="I'm not a dict") |
---|
2888 | n/a | |
---|
2889 | n/a | # -------------------------------------------------------------------- |
---|
2890 | n/a | |
---|
2891 | n/a | class NoAcceleratorTest(unittest.TestCase): |
---|
2892 | n/a | def setUp(self): |
---|
2893 | n/a | if not pyET: |
---|
2894 | n/a | raise unittest.SkipTest('only for the Python version') |
---|
2895 | n/a | |
---|
2896 | n/a | # Test that the C accelerator was not imported for pyET |
---|
2897 | n/a | def test_correct_import_pyET(self): |
---|
2898 | n/a | # The type of methods defined in Python code is types.FunctionType, |
---|
2899 | n/a | # while the type of methods defined inside _elementtree is |
---|
2900 | n/a | # <class 'wrapper_descriptor'> |
---|
2901 | n/a | self.assertIsInstance(pyET.Element.__init__, types.FunctionType) |
---|
2902 | n/a | self.assertIsInstance(pyET.XMLParser.__init__, types.FunctionType) |
---|
2903 | n/a | |
---|
2904 | n/a | # -------------------------------------------------------------------- |
---|
2905 | n/a | |
---|
2906 | n/a | |
---|
2907 | n/a | class CleanContext(object): |
---|
2908 | n/a | """Provide default namespace mapping and path cache.""" |
---|
2909 | n/a | checkwarnings = None |
---|
2910 | n/a | |
---|
2911 | n/a | def __init__(self, quiet=False): |
---|
2912 | n/a | if sys.flags.optimize >= 2: |
---|
2913 | n/a | # under -OO, doctests cannot be run and therefore not all warnings |
---|
2914 | n/a | # will be emitted |
---|
2915 | n/a | quiet = True |
---|
2916 | n/a | deprecations = ( |
---|
2917 | n/a | # Search behaviour is broken if search path starts with "/". |
---|
2918 | n/a | ("This search is broken in 1.3 and earlier, and will be fixed " |
---|
2919 | n/a | "in a future version. If you rely on the current behaviour, " |
---|
2920 | n/a | "change it to '.+'", FutureWarning), |
---|
2921 | n/a | # Element.getchildren() and Element.getiterator() are deprecated. |
---|
2922 | n/a | ("This method will be removed in future versions. " |
---|
2923 | n/a | "Use .+ instead.", DeprecationWarning), |
---|
2924 | n/a | ("This method will be removed in future versions. " |
---|
2925 | n/a | "Use .+ instead.", PendingDeprecationWarning)) |
---|
2926 | n/a | self.checkwarnings = support.check_warnings(*deprecations, quiet=quiet) |
---|
2927 | n/a | |
---|
2928 | n/a | def __enter__(self): |
---|
2929 | n/a | from xml.etree import ElementPath |
---|
2930 | n/a | self._nsmap = ET.register_namespace._namespace_map |
---|
2931 | n/a | # Copy the default namespace mapping |
---|
2932 | n/a | self._nsmap_copy = self._nsmap.copy() |
---|
2933 | n/a | # Copy the path cache (should be empty) |
---|
2934 | n/a | self._path_cache = ElementPath._cache |
---|
2935 | n/a | ElementPath._cache = self._path_cache.copy() |
---|
2936 | n/a | self.checkwarnings.__enter__() |
---|
2937 | n/a | |
---|
2938 | n/a | def __exit__(self, *args): |
---|
2939 | n/a | from xml.etree import ElementPath |
---|
2940 | n/a | # Restore mapping and path cache |
---|
2941 | n/a | self._nsmap.clear() |
---|
2942 | n/a | self._nsmap.update(self._nsmap_copy) |
---|
2943 | n/a | ElementPath._cache = self._path_cache |
---|
2944 | n/a | self.checkwarnings.__exit__(*args) |
---|
2945 | n/a | |
---|
2946 | n/a | |
---|
2947 | n/a | def test_main(module=None): |
---|
2948 | n/a | # When invoked without a module, runs the Python ET tests by loading pyET. |
---|
2949 | n/a | # Otherwise, uses the given module as the ET. |
---|
2950 | n/a | global pyET |
---|
2951 | n/a | pyET = import_fresh_module('xml.etree.ElementTree', |
---|
2952 | n/a | blocked=['_elementtree']) |
---|
2953 | n/a | if module is None: |
---|
2954 | n/a | module = pyET |
---|
2955 | n/a | |
---|
2956 | n/a | global ET |
---|
2957 | n/a | ET = module |
---|
2958 | n/a | |
---|
2959 | n/a | test_classes = [ |
---|
2960 | n/a | ModuleTest, |
---|
2961 | n/a | ElementSlicingTest, |
---|
2962 | n/a | BasicElementTest, |
---|
2963 | n/a | BadElementTest, |
---|
2964 | n/a | BadElementPathTest, |
---|
2965 | n/a | ElementTreeTest, |
---|
2966 | n/a | IOTest, |
---|
2967 | n/a | ParseErrorTest, |
---|
2968 | n/a | XIncludeTest, |
---|
2969 | n/a | ElementTreeTypeTest, |
---|
2970 | n/a | ElementFindTest, |
---|
2971 | n/a | ElementIterTest, |
---|
2972 | n/a | TreeBuilderTest, |
---|
2973 | n/a | XMLParserTest, |
---|
2974 | n/a | XMLPullParserTest, |
---|
2975 | n/a | BugsTest, |
---|
2976 | n/a | ] |
---|
2977 | n/a | |
---|
2978 | n/a | # These tests will only run for the pure-Python version that doesn't import |
---|
2979 | n/a | # _elementtree. We can't use skipUnless here, because pyET is filled in only |
---|
2980 | n/a | # after the module is loaded. |
---|
2981 | n/a | if pyET is not ET: |
---|
2982 | n/a | test_classes.extend([ |
---|
2983 | n/a | NoAcceleratorTest, |
---|
2984 | n/a | ]) |
---|
2985 | n/a | |
---|
2986 | n/a | try: |
---|
2987 | n/a | # XXX the C module should give the same warnings as the Python module |
---|
2988 | n/a | with CleanContext(quiet=(pyET is not ET)): |
---|
2989 | n/a | support.run_unittest(*test_classes) |
---|
2990 | n/a | finally: |
---|
2991 | n/a | # don't interfere with subsequent tests |
---|
2992 | n/a | ET = pyET = None |
---|
2993 | n/a | |
---|
2994 | n/a | |
---|
2995 | n/a | if __name__ == '__main__': |
---|
2996 | n/a | test_main() |
---|