Debian Codegraph @

Lib/test/test_minidom.py

raw
1 # test for xml.dom.minidom
2
3 import copy
4 import pickle
5 import io
6 from test import support
7 import unittest
8
9 import xml.dom.minidom
10
11 from xml.dom.minidom import parse, Attr, Node, Document, Element, parseString
12 from xml.dom.minidom import getDOMImplementation
13 from xml.parsers.expat import ExpatError
14
15
16 tstfile = support.findfile("test.xml", subdir="xmltestdata")
17 sample = ("<?xml version='1.0' encoding='us-ascii'?>\n"
18 "<!DOCTYPE doc PUBLIC 'http://xml.python.org/public'"
19 " 'http://xml.python.org/system' [\n"
20 " <!ELEMENT e EMPTY>\n"
21 " <!ENTITY ent SYSTEM 'http://xml.python.org/entity'>\n"
22 "]><doc attr='value'> text\n"
23 "<?pi sample?> <!-- comment --> <e/> </doc>")
24
25 # The tests of DocumentType importing use these helpers to construct
26 # the documents to work with, since not all DOM builders actually
27 # create the DocumentType nodes.
28 def create_doc_without_doctype(doctype=None):
29 return getDOMImplementation().createDocument(None, "doc", doctype)
30
31 def create_nonempty_doctype():
32 doctype = getDOMImplementation().createDocumentType("doc", None, None)
33 doctype.entities._seq = []
34 doctype.notations._seq = []
35 notation = xml.dom.minidom.Notation("my-notation", None,
36 "http://xml.python.org/notations/my")
37 doctype.notations._seq.append(notation)
38 entity = xml.dom.minidom.Entity("my-entity", None,
39 "http://xml.python.org/entities/my",
40 "my-notation")
41 entity.version = "1.0"
42 entity.encoding = "utf-8"
43 entity.actualEncoding = "us-ascii"
44 doctype.entities._seq.append(entity)
45 return doctype
46
47 def create_doc_with_doctype():
48 doctype = create_nonempty_doctype()
49 doc = create_doc_without_doctype(doctype)
50 doctype.entities.item(0).ownerDocument = doc
51 doctype.notations.item(0).ownerDocument = doc
52 return doc
53
54 class MinidomTest(unittest.TestCase):
55 def confirm(self, test, testname = "Test"):
56 self.assertTrue(test, testname)
57
58 def checkWholeText(self, node, s):
59 t = node.wholeText
60 self.assertEqual(t, s, "looking for %r, found %r" % (s, t))
61
62 def testDocumentAsyncAttr(self):
63 doc = Document()
64 self.assertFalse(doc.async_)
65 self.assertFalse(Document.async_)
66
67 def testParseFromBinaryFile(self):
68 with open(tstfile, 'rb') as file:
69 dom = parse(file)
70 dom.unlink()
71 self.assertIsInstance(dom, Document)
72
73 def testParseFromTextFile(self):
74 with open(tstfile, 'r', encoding='iso-8859-1') as file:
75 dom = parse(file)
76 dom.unlink()
77 self.assertIsInstance(dom, Document)
78
79 def testAttrModeSetsParamsAsAttrs(self):
80 attr = Attr("qName", "namespaceURI", "localName", "prefix")
81 self.assertEqual(attr.name, "qName")
82 self.assertEqual(attr.namespaceURI, "namespaceURI")
83 self.assertEqual(attr.prefix, "prefix")
84 self.assertEqual(attr.localName, "localName")
85
86 def testAttrModeSetsNonOptionalAttrs(self):
87 attr = Attr("qName", "namespaceURI", None, "prefix")
88 self.assertEqual(attr.name, "qName")
89 self.assertEqual(attr.namespaceURI, "namespaceURI")
90 self.assertEqual(attr.prefix, "prefix")
91 self.assertEqual(attr.localName, attr.name)
92
93 def testGetElementsByTagName(self):
94 dom = parse(tstfile)
95 self.assertEqual(dom.getElementsByTagName("LI"),
96 dom.documentElement.getElementsByTagName("LI"))
97 dom.unlink()
98
99 def testInsertBefore(self):
100 dom = parseString("<doc><foo/></doc>")
101 root = dom.documentElement
102 elem = root.childNodes[0]
103 nelem = dom.createElement("element")
104 root.insertBefore(nelem, elem)
105 self.assertEqual(len(root.childNodes), 2)
106 self.assertEqual(root.childNodes.length, 2)
107 self.assertIs(root.childNodes[0], nelem)
108 self.assertIs(root.childNodes.item(0), nelem)
109 self.assertIs(root.childNodes[1], elem)
110 self.assertIs(root.childNodes.item(1), elem)
111 self.assertIs(root.firstChild, nelem)
112 self.assertIs(root.lastChild, elem)
113 self.assertEqual(root.toxml(), "<doc><element/><foo/></doc>")
114 nelem = dom.createElement("element")
115 root.insertBefore(nelem, None)
116 self.assertEqual(len(root.childNodes), 3)
117 self.assertEqual(root.childNodes.length, 3)
118 self.assertIs(root.childNodes[1], elem)
119 self.assertIs(root.childNodes.item(1), elem)
120 self.assertIs(root.childNodes[2], nelem)
121 self.assertIs(root.childNodes.item(2), nelem)
122 self.assertIs(root.lastChild, nelem)
123 self.assertIs(nelem.previousSibling, elem)
124 self.assertEqual(root.toxml(), "<doc><element/><foo/><element/></doc>")
125 nelem2 = dom.createElement("bar")
126 root.insertBefore(nelem2, nelem)
127 self.assertEqual(len(root.childNodes), 4)
128 self.assertEqual(root.childNodes.length, 4)
129 self.assertIs(root.childNodes[2], nelem2)
130 self.assertIs(root.childNodes.item(2), nelem2)
131 self.assertIs(root.childNodes[3], nelem)
132 self.assertIs(root.childNodes.item(3), nelem)
133 self.assertIs(nelem2.nextSibling, nelem)
134 self.assertIs(nelem.previousSibling, nelem2)
135 self.assertEqual(root.toxml(),
136 "<doc><element/><foo/><bar/><element/></doc>")
137 dom.unlink()
138
139 def _create_fragment_test_nodes(self):
140 dom = parseString("<doc/>")
141 orig = dom.createTextNode("original")
142 c1 = dom.createTextNode("foo")
143 c2 = dom.createTextNode("bar")
144 c3 = dom.createTextNode("bat")
145 dom.documentElement.appendChild(orig)
146 frag = dom.createDocumentFragment()
147 frag.appendChild(c1)
148 frag.appendChild(c2)
149 frag.appendChild(c3)
150 return dom, orig, c1, c2, c3, frag
151
152 def testInsertBeforeFragment(self):
153 dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
154 dom.documentElement.insertBefore(frag, None)
155 self.assertTupleEqual(tuple(dom.documentElement.childNodes),
156 (orig, c1, c2, c3),
157 "insertBefore(<fragment>, None)")
158 frag.unlink()
159 dom.unlink()
160
161 dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
162 dom.documentElement.insertBefore(frag, orig)
163 self.assertTupleEqual(tuple(dom.documentElement.childNodes),
164 (c1, c2, c3, orig),
165 "insertBefore(<fragment>, orig)")
166 frag.unlink()
167 dom.unlink()
168
169 def testAppendChild(self):
170 dom = parse(tstfile)
171 dom.documentElement.appendChild(dom.createComment("Hello"))
172 self.assertEqual(dom.documentElement.childNodes[-1].nodeName, "#comment")
173 self.assertEqual(dom.documentElement.childNodes[-1].data, "Hello")
174 dom.unlink()
175
176 @support.requires_resource('cpu')
177 def testAppendChildNoQuadraticComplexity(self):
178 impl = getDOMImplementation()
179
180 def work(n):
181 doc = impl.createDocument(None, "some_tag", None)
182 element = doc.documentElement
183 total_calls = 0
184
185 # Count attribute accesses as a proxy for work done
186 def getattribute_counter(self, attr):
187 nonlocal total_calls
188 total_calls += 1
189 return object.__getattribute__(self, attr)
190
191 with support.swap_attr(Element, "__getattribute__", getattribute_counter):
192 for _ in range(n):
193 child = doc.createElement("child")
194 element.appendChild(child)
195 element = child
196 return total_calls
197
198 # Doubling N should not ~quadruple the work.
199 w1 = work(1024)
200 w2 = work(2048)
201 w3 = work(4096)
202
203 self.assertGreater(w1, 0)
204 r1 = w2 / w1
205 r2 = w3 / w2
206 self.assertLess(
207 max(r1, r2), 3.2,
208 msg=f"Possible quadratic behavior: work={w1,w2,w3} ratios={r1,r2}"
209 )
210
211 def testSetAttributeNodeWithoutOwnerDocument(self):
212 # regression test for gh-142754
213 elem = Element("test")
214 attr = Attr("id")
215 attr.value = "test-id"
216 elem.setAttributeNode(attr)
217 self.assertEqual(elem.getAttribute("id"), "test-id")
218
219 def testAppendChildFragment(self):
220 dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
221 dom.documentElement.appendChild(frag)
222 self.assertTupleEqual(tuple(dom.documentElement.childNodes),
223 (orig, c1, c2, c3),
224 "appendChild(<fragment>)")
225 frag.unlink()
226 dom.unlink()
227
228 def testReplaceChildFragment(self):
229 dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
230 dom.documentElement.replaceChild(frag, orig)
231 orig.unlink()
232 self.assertTupleEqual(tuple(dom.documentElement.childNodes), (c1, c2, c3),
233 "replaceChild(<fragment>)")
234 frag.unlink()
235 dom.unlink()
236
237 def testLegalChildren(self):
238 dom = Document()
239 elem = dom.createElement('element')
240 text = dom.createTextNode('text')
241 self.assertRaises(xml.dom.HierarchyRequestErr, dom.appendChild, text)
242
243 dom.appendChild(elem)
244 self.assertRaises(xml.dom.HierarchyRequestErr, dom.insertBefore, text,
245 elem)
246 self.assertRaises(xml.dom.HierarchyRequestErr, dom.replaceChild, text,
247 elem)
248
249 nodemap = elem.attributes
250 self.assertRaises(xml.dom.HierarchyRequestErr, nodemap.setNamedItem,
251 text)
252 self.assertRaises(xml.dom.HierarchyRequestErr, nodemap.setNamedItemNS,
253 text)
254
255 elem.appendChild(text)
256 dom.unlink()
257
258 def testNamedNodeMapSetItem(self):
259 dom = Document()
260 elem = dom.createElement('element')
261 attrs = elem.attributes
262 attrs["foo"] = "bar"
263 a = attrs.item(0)
264 self.assertIs(a.ownerDocument, dom,
265 "NamedNodeMap.__setitem__() sets ownerDocument")
266 self.assertIs(a.ownerElement, elem,
267 "NamedNodeMap.__setitem__() sets ownerElement")
268 self.assertEqual(a.value, "bar",
269 "NamedNodeMap.__setitem__() sets value")
270 self.assertEqual(a.nodeValue, "bar",
271 "NamedNodeMap.__setitem__() sets nodeValue")
272 elem.unlink()
273 dom.unlink()
274
275 def testNonZero(self):
276 dom = parse(tstfile)
277 self.assertTrue(dom) # should not be zero
278 dom.appendChild(dom.createComment("foo"))
279 self.assertFalse(dom.childNodes[-1].childNodes)
280 dom.unlink()
281
282 def testUnlink(self):
283 dom = parse(tstfile)
284 self.assertTrue(dom.childNodes)
285 dom.unlink()
286 self.assertFalse(dom.childNodes)
287
288 def testContext(self):
289 with parse(tstfile) as dom:
290 self.assertTrue(dom.childNodes)
291 self.assertFalse(dom.childNodes)
292
293 def testElement(self):
294 dom = Document()
295 dom.appendChild(dom.createElement("abc"))
296 self.assertTrue(dom.documentElement)
297 dom.unlink()
298
299 def testAAA(self):
300 dom = parseString("<abc/>")
301 el = dom.documentElement
302 el.setAttribute("spam", "jam2")
303 self.assertEqual(el.toxml(), '<abc spam="jam2"/>', "testAAA")
304 a = el.getAttributeNode("spam")
305 self.assertIs(a.ownerDocument, dom,
306 "setAttribute() sets ownerDocument")
307 self.assertIs(a.ownerElement, dom.documentElement,
308 "setAttribute() sets ownerElement")
309 dom.unlink()
310
311 def testAAB(self):
312 dom = parseString("<abc/>")
313 el = dom.documentElement
314 el.setAttribute("spam", "jam")
315 el.setAttribute("spam", "jam2")
316 self.assertEqual(el.toxml(), '<abc spam="jam2"/>', "testAAB")
317 dom.unlink()
318
319 def testAddAttr(self):
320 dom = Document()
321 child = dom.appendChild(dom.createElement("abc"))
322
323 child.setAttribute("def", "ghi")
324 self.assertEqual(child.getAttribute("def"), "ghi")
325 self.assertEqual(child.attributes["def"].value, "ghi")
326
327 child.setAttribute("jkl", "mno")
328 self.assertEqual(child.getAttribute("jkl"), "mno")
329 self.assertEqual(child.attributes["jkl"].value, "mno")
330
331 self.assertEqual(len(child.attributes), 2)
332
333 child.setAttribute("def", "newval")
334 self.assertEqual(child.getAttribute("def"), "newval")
335 self.assertEqual(child.attributes["def"].value, "newval")
336
337 self.assertEqual(len(child.attributes), 2)
338 dom.unlink()
339
340 def testDeleteAttr(self):
341 dom = Document()
342 child = dom.appendChild(dom.createElement("abc"))
343
344 self.assertEqual(len(child.attributes), 0)
345 child.setAttribute("def", "ghi")
346 self.assertEqual(len(child.attributes), 1)
347 del child.attributes["def"]
348 self.assertEqual(len(child.attributes), 0)
349 dom.unlink()
350
351 def testRemoveAttr(self):
352 dom = Document()
353 child = dom.appendChild(dom.createElement("abc"))
354
355 child.setAttribute("def", "ghi")
356 self.assertEqual(len(child.attributes), 1)
357 self.assertRaises(xml.dom.NotFoundErr, child.removeAttribute, "foo")
358 child.removeAttribute("def")
359 self.assertEqual(len(child.attributes), 0)
360 dom.unlink()
361
362 def testRemoveAttrNS(self):
363 dom = Document()
364 child = dom.appendChild(
365 dom.createElementNS("http://www.python.org", "python:abc"))
366 child.setAttributeNS("http://www.w3.org", "xmlns:python",
367 "http://www.python.org")
368 child.setAttributeNS("http://www.python.org", "python:abcattr", "foo")
369 self.assertRaises(xml.dom.NotFoundErr, child.removeAttributeNS,
370 "foo", "http://www.python.org")
371 self.assertEqual(len(child.attributes), 2)
372 child.removeAttributeNS("http://www.python.org", "abcattr")
373 self.assertEqual(len(child.attributes), 1)
374 dom.unlink()
375
376 def testRemoveAttributeNode(self):
377 dom = Document()
378 child = dom.appendChild(dom.createElement("foo"))
379 child.setAttribute("spam", "jam")
380 self.assertEqual(len(child.attributes), 1)
381 node = child.getAttributeNode("spam")
382 self.assertRaises(xml.dom.NotFoundErr, child.removeAttributeNode,
383 None)
384 self.assertIs(node, child.removeAttributeNode(node))
385 self.assertEqual(len(child.attributes), 0)
386 self.assertIsNone(child.getAttributeNode("spam"))
387 dom2 = Document()
388 child2 = dom2.appendChild(dom2.createElement("foo"))
389 node2 = child2.getAttributeNode("spam")
390 self.assertRaises(xml.dom.NotFoundErr, child2.removeAttributeNode,
391 node2)
392 dom.unlink()
393
394 def testHasAttribute(self):
395 dom = Document()
396 child = dom.appendChild(dom.createElement("foo"))
397 child.setAttribute("spam", "jam")
398 self.assertTrue(child.hasAttribute("spam"))
399
400 def testChangeAttr(self):
401 dom = parseString("<abc/>")
402 el = dom.documentElement
403 el.setAttribute("spam", "jam")
404 self.assertEqual(len(el.attributes), 1)
405 el.setAttribute("spam", "bam")
406 # Set this attribute to be an ID and make sure that doesn't change
407 # when changing the value:
408 el.setIdAttribute("spam")
409 self.assertEqual(len(el.attributes), 1)
410 self.assertEqual(el.attributes["spam"].value, "bam")
411 self.assertEqual(el.attributes["spam"].nodeValue, "bam")
412 self.assertEqual(el.getAttribute("spam"), "bam")
413 self.assertTrue(el.getAttributeNode("spam").isId)
414 el.attributes["spam"] = "ham"
415 self.assertEqual(len(el.attributes), 1)
416 self.assertEqual(el.attributes["spam"].value, "ham")
417 self.assertEqual(el.attributes["spam"].nodeValue, "ham")
418 self.assertEqual(el.getAttribute("spam"), "ham")
419 self.assertTrue(el.attributes["spam"].isId)
420 el.setAttribute("spam2", "bam")
421 self.assertEqual(len(el.attributes), 2)
422 self.assertEqual(el.attributes["spam"].value, "ham")
423 self.assertEqual(el.attributes["spam"].nodeValue, "ham")
424 self.assertEqual(el.getAttribute("spam"), "ham")
425 self.assertEqual(el.attributes["spam2"].value, "bam")
426 self.assertEqual(el.attributes["spam2"].nodeValue, "bam")
427 self.assertEqual(el.getAttribute("spam2"), "bam")
428 el.attributes["spam2"] = "bam2"
429
430 self.assertEqual(len(el.attributes), 2)
431 self.assertEqual(el.attributes["spam"].value, "ham")
432 self.assertEqual(el.attributes["spam"].nodeValue, "ham")
433 self.assertEqual(el.getAttribute("spam"), "ham")
434 self.assertEqual(el.attributes["spam2"].value, "bam2")
435 self.assertEqual(el.attributes["spam2"].nodeValue, "bam2")
436 self.assertEqual(el.getAttribute("spam2"), "bam2")
437 dom.unlink()
438
439 def testGetAttrList(self):
440 dom = parseString("<abc/>")
441 self.addCleanup(dom.unlink)
442 el = dom.documentElement
443 el.setAttribute("spam", "jam")
444 self.assertEqual(len(el.attributes.items()), 1)
445 el.setAttribute("foo", "bar")
446 items = el.attributes.items()
447 self.assertEqual(len(items), 2)
448 self.assertIn(('spam', 'jam'), items)
449 self.assertIn(('foo', 'bar'), items)
450
451 def testGetAttrValues(self):
452 dom = parseString("<abc/>")
453 self.addCleanup(dom.unlink)
454 el = dom.documentElement
455 el.setAttribute("spam", "jam")
456 values = [x.value for x in el.attributes.values()]
457 self.assertIn("jam", values)
458 el.setAttribute("foo", "bar")
459 values = [x.value for x in el.attributes.values()]
460 self.assertIn("bar", values)
461 self.assertIn("jam", values)
462
463 def testGetAttribute(self):
464 dom = Document()
465 child = dom.appendChild(
466 dom.createElementNS("http://www.python.org", "python:abc"))
467 self.assertEqual(child.getAttribute('missing'), '')
468
469 def testGetAttributeNS(self):
470 dom = Document()
471 child = dom.appendChild(
472 dom.createElementNS("http://www.python.org", "python:abc"))
473 child.setAttributeNS("http://www.w3.org", "xmlns:python",
474 "http://www.python.org")
475 self.assertEqual(child.getAttributeNS("http://www.w3.org", "python"),
476 'http://www.python.org')
477 self.assertEqual(child.getAttributeNS("http://www.w3.org", "other"),
478 '')
479 child2 = child.appendChild(dom.createElement('abc'))
480 self.assertEqual(child2.getAttributeNS("http://www.python.org", "missing"),
481 '')
482
483 def testGetAttributeNode(self): pass
484
485 def testGetElementsByTagNameNS(self):
486 d="""<foo xmlns:minidom='http://pyxml.sf.net/minidom'>
487 <minidom:myelem/>
488 </foo>"""
489 dom = parseString(d)
490 elems = dom.getElementsByTagNameNS("http://pyxml.sf.net/minidom",
491 "myelem")
492 self.assertEqual(len(elems), 1)
493 self.assertEqual(elems[0].namespaceURI, "http://pyxml.sf.net/minidom")
494 self.assertEqual(elems[0].localName, "myelem")
495 self.assertEqual(elems[0].prefix, "minidom")
496 self.assertEqual(elems[0].tagName, "minidom:myelem")
497 self.assertEqual(elems[0].nodeName, "minidom:myelem")
498 dom.unlink()
499
500 def get_empty_nodelist_from_elements_by_tagName_ns_helper(self, doc, nsuri,
501 lname):
502 nodelist = doc.getElementsByTagNameNS(nsuri, lname)
503 self.assertEqual(len(nodelist), 0)
504
505 def testGetEmptyNodeListFromElementsByTagNameNS(self):
506 doc = parseString('<doc/>')
507 self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
508 doc, 'http://xml.python.org/namespaces/a', 'localname')
509 self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
510 doc, '*', 'splat')
511 self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
512 doc, 'http://xml.python.org/namespaces/a', '*')
513
514 doc = parseString('<doc xmlns="http://xml.python.org/splat"><e/></doc>')
515 self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
516 doc, "http://xml.python.org/splat", "not-there")
517 self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
518 doc, "*", "not-there")
519 self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
520 doc, "http://somewhere.else.net/not-there", "e")
521
522 def testElementReprAndStr(self):
523 dom = Document()
524 el = dom.appendChild(dom.createElement("abc"))
525 string1 = repr(el)
526 string2 = str(el)
527 self.assertEqual(string1, string2)
528 dom.unlink()
529
530 def testElementReprAndStrUnicode(self):
531 dom = Document()
532 el = dom.appendChild(dom.createElement("abc"))
533 string1 = repr(el)
534 string2 = str(el)
535 self.assertEqual(string1, string2)
536 dom.unlink()
537
538 def testElementReprAndStrUnicodeNS(self):
539 dom = Document()
540 el = dom.appendChild(
541 dom.createElementNS("http://www.slashdot.org", "slash:abc"))
542 string1 = repr(el)
543 string2 = str(el)
544 self.assertEqual(string1, string2)
545 self.assertIn("slash:abc", string1)
546 dom.unlink()
547
548 def testAttributeRepr(self):
549 dom = Document()
550 el = dom.appendChild(dom.createElement("abc"))
551 node = el.setAttribute("abc", "def")
552 self.assertEqual(str(node), repr(node))
553 dom.unlink()
554
555 def testWriteXML(self):
556 str = '<?xml version="1.0" ?><a b="c"/>'
557 dom = parseString(str)
558 domstr = dom.toxml()
559 dom.unlink()
560 self.assertEqual(str, domstr)
561
562 def test_toxml_quote_text(self):
563 dom = Document()
564 elem = dom.appendChild(dom.createElement('elem'))
565 elem.appendChild(dom.createTextNode('&<>"'))
566 cr = elem.appendChild(dom.createElement('cr'))
567 cr.appendChild(dom.createTextNode('\r'))
568 crlf = elem.appendChild(dom.createElement('crlf'))
569 crlf.appendChild(dom.createTextNode('\r\n'))
570 lflf = elem.appendChild(dom.createElement('lflf'))
571 lflf.appendChild(dom.createTextNode('\n\n'))
572 ws = elem.appendChild(dom.createElement('ws'))
573 ws.appendChild(dom.createTextNode('\t\n\r '))
574 domstr = dom.toxml()
575 dom.unlink()
576 self.assertEqual(domstr, '<?xml version="1.0" ?>'
577 '<elem>&amp;&lt;&gt;"'
578 '<cr>\r</cr>'
579 '<crlf>\r\n</crlf>'
580 '<lflf>\n\n</lflf>'
581 '<ws>\t\n\r </ws></elem>')
582
583 def test_toxml_quote_attrib(self):
584 dom = Document()
585 elem = dom.appendChild(dom.createElement('elem'))
586 elem.setAttribute("a", '&<>"')
587 elem.setAttribute("cr", "\r")
588 elem.setAttribute("lf", "\n")
589 elem.setAttribute("crlf", "\r\n")
590 elem.setAttribute("lflf", "\n\n")
591 elem.setAttribute("ws", "\t\n\r ")
592 domstr = dom.toxml()
593 dom.unlink()
594 self.assertEqual(domstr, '<?xml version="1.0" ?>'
595 '<elem a="&amp;&lt;&gt;&quot;" '
596 'cr="&#13;" '
597 'lf="&#10;" '
598 'crlf="&#13;&#10;" '
599 'lflf="&#10;&#10;" '
600 'ws="&#9;&#10;&#13; "/>')
601
602 def testAltNewline(self):
603 str = '<?xml version="1.0" ?>\n<a b="c"/>\n'
604 dom = parseString(str)
605 domstr = dom.toprettyxml(newl="\r\n")
606 dom.unlink()
607 self.assertEqual(domstr, str.replace("\n", "\r\n"))
608
609 def test_toprettyxml_with_text_nodes(self):
610 # see issue #4147, text nodes are not indented
611 decl = '<?xml version="1.0" ?>\n'
612 self.assertEqual(parseString('<B>A</B>').toprettyxml(),
613 decl + '<B>A</B>\n')
614 self.assertEqual(parseString('<C>A<B>A</B></C>').toprettyxml(),
615 decl + '<C>\n\tA\n\t<B>A</B>\n</C>\n')
616 self.assertEqual(parseString('<C><B>A</B>A</C>').toprettyxml(),
617 decl + '<C>\n\t<B>A</B>\n\tA\n</C>\n')
618 self.assertEqual(parseString('<C><B>A</B><B>A</B></C>').toprettyxml(),
619 decl + '<C>\n\t<B>A</B>\n\t<B>A</B>\n</C>\n')
620 self.assertEqual(parseString('<C><B>A</B>A<B>A</B></C>').toprettyxml(),
621 decl + '<C>\n\t<B>A</B>\n\tA\n\t<B>A</B>\n</C>\n')
622
623 def test_toprettyxml_with_adjacent_text_nodes(self):
624 # see issue #4147, adjacent text nodes are indented normally
625 dom = Document()
626 elem = dom.createElement('elem')
627 elem.appendChild(dom.createTextNode('TEXT'))
628 elem.appendChild(dom.createTextNode('TEXT'))
629 dom.appendChild(elem)
630 decl = '<?xml version="1.0" ?>\n'
631 self.assertEqual(dom.toprettyxml(),
632 decl + '<elem>\n\tTEXT\n\tTEXT\n</elem>\n')
633
634 def test_toprettyxml_preserves_content_of_text_node(self):
635 # see issue #4147
636 for str in ('<B>A</B>', '<A><B>C</B></A>'):
637 dom = parseString(str)
638 dom2 = parseString(dom.toprettyxml())
639 self.assertEqual(
640 dom.getElementsByTagName('B')[0].childNodes[0].toxml(),
641 dom2.getElementsByTagName('B')[0].childNodes[0].toxml())
642
643 def testProcessingInstruction(self):
644 dom = parseString('<e><?mypi \t\n data \t\n ?></e>')
645 pi = dom.documentElement.firstChild
646 self.assertEqual(pi.target, "mypi")
647 self.assertEqual(pi.data, "data \t\n ")
648 self.assertEqual(pi.nodeName, "mypi")
649 self.assertEqual(pi.nodeType, Node.PROCESSING_INSTRUCTION_NODE)
650 self.assertIsNone(pi.attributes)
651 self.assertFalse(pi.hasChildNodes())
652 self.assertEqual(len(pi.childNodes), 0)
653 self.assertIsNone(pi.firstChild)
654 self.assertIsNone(pi.lastChild)
655 self.assertIsNone(pi.localName)
656 self.assertEqual(pi.namespaceURI, xml.dom.EMPTY_NAMESPACE)
657
658 def testProcessingInstructionRepr(self):
659 dom = parseString('<e><?mypi \t\n data \t\n ?></e>')
660 pi = dom.documentElement.firstChild
661 self.assertEqual(str(pi.nodeType), repr(pi.nodeType))
662
663 def testTextRepr(self):
664 dom = Document()
665 self.addCleanup(dom.unlink)
666 elem = dom.createElement("elem")
667 elem.appendChild(dom.createTextNode("foo"))
668 el = elem.firstChild
669 self.assertEqual(str(el), repr(el))
670 self.assertEqual('<DOM Text node "\'foo\'">', str(el))
671
672 def testWriteText(self): pass
673
674 def testDocumentElement(self): pass
675
676 def testTooManyDocumentElements(self):
677 doc = parseString("<doc/>")
678 elem = doc.createElement("extra")
679 # Should raise an exception when adding an extra document element.
680 self.assertRaises(xml.dom.HierarchyRequestErr, doc.appendChild, elem)
681 elem.unlink()
682 doc.unlink()
683
684 def testCreateElementNS(self): pass
685
686 def testCreateAttributeNS(self): pass
687
688 def testParse(self): pass
689
690 def testParseString(self): pass
691
692 def testComment(self): pass
693
694 def testAttrListItem(self): pass
695
696 def testAttrListItems(self): pass
697
698 def testAttrListItemNS(self): pass
699
700 def testAttrListKeys(self): pass
701
702 def testAttrListKeysNS(self): pass
703
704 def testRemoveNamedItem(self):
705 doc = parseString("<doc a=''/>")
706 e = doc.documentElement
707 attrs = e.attributes
708 a1 = e.getAttributeNode("a")
709 a2 = attrs.removeNamedItem("a")
710 self.assertTrue(a1.isSameNode(a2))
711 self.assertRaises(xml.dom.NotFoundErr, attrs.removeNamedItem, "a")
712
713 def testRemoveNamedItemNS(self):
714 doc = parseString("<doc xmlns:a='http://xml.python.org/' a:b=''/>")
715 e = doc.documentElement
716 attrs = e.attributes
717 a1 = e.getAttributeNodeNS("http://xml.python.org/", "b")
718 a2 = attrs.removeNamedItemNS("http://xml.python.org/", "b")
719 self.assertTrue(a1.isSameNode(a2))
720 self.assertRaises(xml.dom.NotFoundErr, attrs.removeNamedItemNS,
721 "http://xml.python.org/", "b")
722
723 def testAttrListValues(self): pass
724
725 def testAttrListLength(self): pass
726
727 def testAttrList__getitem__(self): pass
728
729 def testAttrList__setitem__(self): pass
730
731 def testSetAttrValueandNodeValue(self): pass
732
733 def testParseElement(self): pass
734
735 def testParseAttributes(self): pass
736
737 def testParseElementNamespaces(self): pass
738
739 def testParseAttributeNamespaces(self): pass
740
741 def testParseProcessingInstructions(self): pass
742
743 def testChildNodes(self): pass
744
745 def testFirstChild(self): pass
746
747 def testHasChildNodes(self):
748 dom = parseString("<doc><foo/></doc>")
749 doc = dom.documentElement
750 self.assertTrue(doc.hasChildNodes())
751 dom2 = parseString("<doc/>")
752 doc2 = dom2.documentElement
753 self.assertFalse(doc2.hasChildNodes())
754
755 def _testCloneElementCopiesAttributes(self, e1, e2, test):
756 attrs1 = e1.attributes
757 attrs2 = e2.attributes
758 keys1 = list(attrs1.keys())
759 keys2 = list(attrs2.keys())
760 keys1.sort()
761 keys2.sort()
762 self.assertEqual(keys1, keys2)
763 for i in range(len(keys1)):
764 a1 = attrs1.item(i)
765 a2 = attrs2.item(i)
766 self.assertIsNot(a1, a2)
767 self.assertEqual(a1.value, a2.value)
768 self.assertEqual(a1.nodeValue, a2.nodeValue)
769 self.assertEqual(a1.namespaceURI,a2.namespaceURI)
770 self.assertEqual(a1.localName, a2.localName)
771 self.assertIs(a2.ownerElement, e2)
772
773 def _setupCloneElement(self, deep):
774 dom = parseString("<doc attr='value'><foo/></doc>")
775 root = dom.documentElement
776 clone = root.cloneNode(deep)
777 self._testCloneElementCopiesAttributes(
778 root, clone, "testCloneElement" + (deep and "Deep" or "Shallow"))
779 # mutilate the original so shared data is detected
780 root.tagName = root.nodeName = "MODIFIED"
781 root.setAttribute("attr", "NEW VALUE")
782 root.setAttribute("added", "VALUE")
783 return dom, clone
784
785 def testCloneElementShallow(self):
786 dom, clone = self._setupCloneElement(0)
787 self.assertEqual(len(clone.childNodes), 0)
788 self.assertEqual(clone.childNodes.length, 0)
789 self.assertIsNone(clone.parentNode)
790 self.assertEqual(clone.toxml(), '<doc attr="value"/>')
791
792 dom.unlink()
793
794 def testCloneElementDeep(self):
795 dom, clone = self._setupCloneElement(1)
796 self.assertEqual(len(clone.childNodes), 1)
797 self.assertEqual(clone.childNodes.length, 1)
798 self.assertIsNone(clone.parentNode)
799 self.assertTrue(clone.toxml(), '<doc attr="value"><foo/></doc>')
800 dom.unlink()
801
802 def testCloneDocumentShallow(self):
803 doc = parseString("<?xml version='1.0'?>\n"
804 "<!-- comment -->"
805 "<!DOCTYPE doc [\n"
806 "<!NOTATION notation SYSTEM 'http://xml.python.org/'>\n"
807 "]>\n"
808 "<doc attr='value'/>")
809 doc2 = doc.cloneNode(0)
810 self.assertIsNone(doc2,
811 "testCloneDocumentShallow:"
812 " shallow cloning of documents makes no sense!")
813
814 def testCloneDocumentDeep(self):
815 doc = parseString("<?xml version='1.0'?>\n"
816 "<!-- comment -->"
817 "<!DOCTYPE doc [\n"
818 "<!NOTATION notation SYSTEM 'http://xml.python.org/'>\n"
819 "]>\n"
820 "<doc attr='value'/>")
821 doc2 = doc.cloneNode(1)
822 self.assertFalse((doc.isSameNode(doc2) or doc2.isSameNode(doc)),
823 "testCloneDocumentDeep: document objects not distinct")
824 self.assertEqual(len(doc.childNodes), len(doc2.childNodes),
825 "testCloneDocumentDeep: wrong number of Document children")
826 self.assertEqual(doc2.documentElement.nodeType, Node.ELEMENT_NODE,
827 "testCloneDocumentDeep: documentElement not an ELEMENT_NODE")
828 self.assertTrue(doc2.documentElement.ownerDocument.isSameNode(doc2),
829 "testCloneDocumentDeep: documentElement owner is not new document")
830 self.assertFalse(doc.documentElement.isSameNode(doc2.documentElement),
831 "testCloneDocumentDeep: documentElement should not be shared")
832 if doc.doctype is not None:
833 # check the doctype iff the original DOM maintained it
834 self.assertEqual(doc2.doctype.nodeType, Node.DOCUMENT_TYPE_NODE,
835 "testCloneDocumentDeep: doctype not a DOCUMENT_TYPE_NODE")
836 self.assertTrue(doc2.doctype.ownerDocument.isSameNode(doc2))
837 self.assertFalse(doc.doctype.isSameNode(doc2.doctype))
838
839 def testCloneDocumentTypeDeepOk(self):
840 doctype = create_nonempty_doctype()
841 clone = doctype.cloneNode(1)
842 self.confirm(clone is not None
843 and clone.nodeName == doctype.nodeName
844 and clone.name == doctype.name
845 and clone.publicId == doctype.publicId
846 and clone.systemId == doctype.systemId
847 and len(clone.entities) == len(doctype.entities)
848 and clone.entities.item(len(clone.entities)) is None
849 and len(clone.notations) == len(doctype.notations)
850 and clone.notations.item(len(clone.notations)) is None
851 and len(clone.childNodes) == 0)
852 for i in range(len(doctype.entities)):
853 se = doctype.entities.item(i)
854 ce = clone.entities.item(i)
855 self.confirm((not se.isSameNode(ce))
856 and (not ce.isSameNode(se))
857 and ce.nodeName == se.nodeName
858 and ce.notationName == se.notationName
859 and ce.publicId == se.publicId
860 and ce.systemId == se.systemId
861 and ce.encoding == se.encoding
862 and ce.actualEncoding == se.actualEncoding
863 and ce.version == se.version)
864 for i in range(len(doctype.notations)):
865 sn = doctype.notations.item(i)
866 cn = clone.notations.item(i)
867 self.confirm((not sn.isSameNode(cn))
868 and (not cn.isSameNode(sn))
869 and cn.nodeName == sn.nodeName
870 and cn.publicId == sn.publicId
871 and cn.systemId == sn.systemId)
872
873 def testCloneDocumentTypeDeepNotOk(self):
874 doc = create_doc_with_doctype()
875 clone = doc.doctype.cloneNode(1)
876 self.assertIsNone(clone)
877
878 def testCloneDocumentTypeShallowOk(self):
879 doctype = create_nonempty_doctype()
880 clone = doctype.cloneNode(0)
881 self.confirm(clone is not None
882 and clone.nodeName == doctype.nodeName
883 and clone.name == doctype.name
884 and clone.publicId == doctype.publicId
885 and clone.systemId == doctype.systemId
886 and len(clone.entities) == 0
887 and clone.entities.item(0) is None
888 and len(clone.notations) == 0
889 and clone.notations.item(0) is None
890 and len(clone.childNodes) == 0)
891
892 def testCloneDocumentTypeShallowNotOk(self):
893 doc = create_doc_with_doctype()
894 clone = doc.doctype.cloneNode(0)
895 self.assertIsNone(clone)
896
897 def check_import_document(self, deep, testName):
898 doc1 = parseString("<doc/>")
899 doc2 = parseString("<doc/>")
900 self.assertRaises(xml.dom.NotSupportedErr, doc1.importNode, doc2, deep)
901
902 def testImportDocumentShallow(self):
903 self.check_import_document(0, "testImportDocumentShallow")
904
905 def testImportDocumentDeep(self):
906 self.check_import_document(1, "testImportDocumentDeep")
907
908 def testImportDocumentTypeShallow(self):
909 src = create_doc_with_doctype()
910 target = create_doc_without_doctype()
911 self.assertRaises(xml.dom.NotSupportedErr, target.importNode,
912 src.doctype, 0)
913
914 def testImportDocumentTypeDeep(self):
915 src = create_doc_with_doctype()
916 target = create_doc_without_doctype()
917 self.assertRaises(xml.dom.NotSupportedErr, target.importNode,
918 src.doctype, 1)
919
920 # Testing attribute clones uses a helper, and should always be deep,
921 # even if the argument to cloneNode is false.
922 def check_clone_attribute(self, deep, testName):
923 doc = parseString("<doc attr='value'/>")
924 attr = doc.documentElement.getAttributeNode("attr")
925 self.assertIsNotNone(attr)
926 clone = attr.cloneNode(deep)
927 self.assertFalse(clone.isSameNode(attr))
928 self.assertFalse(attr.isSameNode(clone))
929 self.assertIsNone(clone.ownerElement,
930 testName + ": ownerElement should be None")
931 self.confirm(clone.ownerDocument.isSameNode(attr.ownerDocument),
932 testName + ": ownerDocument does not match")
933 self.confirm(clone.specified,
934 testName + ": cloned attribute must have specified == True")
935
936 def testCloneAttributeShallow(self):
937 self.check_clone_attribute(0, "testCloneAttributeShallow")
938
939 def testCloneAttributeDeep(self):
940 self.check_clone_attribute(1, "testCloneAttributeDeep")
941
942 def check_clone_pi(self, deep, testName):
943 doc = parseString("<?target data?><doc/>")
944 pi = doc.firstChild
945 self.assertEqual(pi.nodeType, Node.PROCESSING_INSTRUCTION_NODE)
946 clone = pi.cloneNode(deep)
947 self.confirm(clone.target == pi.target
948 and clone.data == pi.data)
949
950 def testClonePIShallow(self):
951 self.check_clone_pi(0, "testClonePIShallow")
952
953 def testClonePIDeep(self):
954 self.check_clone_pi(1, "testClonePIDeep")
955
956 def check_clone_node_entity(self, clone_document):
957 # bpo-35052: Test user data handler in cloneNode() on a document with
958 # an entity
959 document = xml.dom.minidom.parseString("""
960 <?xml version="1.0" ?>
961 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
962 "http://www.w3.org/TR/html4/strict.dtd"
963 [ <!ENTITY smile "☺"> ]
964 >
965 <doc>Don't let entities make you frown &smile;</doc>
966 """.strip())
967
968 class Handler:
969 def handle(self, operation, key, data, src, dst):
970 self.operation = operation
971 self.key = key
972 self.data = data
973 self.src = src
974 self.dst = dst
975
976 handler = Handler()
977 doctype = document.doctype
978 entity = doctype.entities['smile']
979 entity.setUserData("key", "data", handler)
980
981 if clone_document:
982 # clone Document
983 clone = document.cloneNode(deep=True)
984
985 self.assertEqual(clone.documentElement.firstChild.wholeText,
986 "Don't let entities make you frown ☺")
987 operation = xml.dom.UserDataHandler.NODE_IMPORTED
988 dst = clone.doctype.entities['smile']
989 else:
990 # clone DocumentType
991 with support.swap_attr(doctype, 'ownerDocument', None):
992 clone = doctype.cloneNode(deep=True)
993
994 operation = xml.dom.UserDataHandler.NODE_CLONED
995 dst = clone.entities['smile']
996
997 self.assertEqual(handler.operation, operation)
998 self.assertEqual(handler.key, "key")
999 self.assertEqual(handler.data, "data")
1000 self.assertIs(handler.src, entity)
1001 self.assertIs(handler.dst, dst)
1002
1003 def testCloneNodeEntity(self):
1004 self.check_clone_node_entity(False)
1005 self.check_clone_node_entity(True)
1006
1007 def testNormalize(self):
1008 doc = parseString("<doc/>")
1009 root = doc.documentElement
1010 root.appendChild(doc.createTextNode("first"))
1011 root.appendChild(doc.createTextNode("second"))
1012 self.confirm(len(root.childNodes) == 2
1013 and root.childNodes.length == 2,
1014 "testNormalize -- preparation")
1015 doc.normalize()
1016 self.confirm(len(root.childNodes) == 1
1017 and root.childNodes.length == 1
1018 and root.firstChild is root.lastChild
1019 and root.firstChild.data == "firstsecond"
1020 , "testNormalize -- result")
1021 doc.unlink()
1022
1023 doc = parseString("<doc/>")
1024 root = doc.documentElement
1025 root.appendChild(doc.createTextNode(""))
1026 doc.normalize()
1027 self.confirm(len(root.childNodes) == 0
1028 and root.childNodes.length == 0,
1029 "testNormalize -- single empty node removed")
1030 doc.unlink()
1031
1032 def testNormalizeCombineAndNextSibling(self):
1033 doc = parseString("<doc/>")
1034 root = doc.documentElement
1035 root.appendChild(doc.createTextNode("first"))
1036 root.appendChild(doc.createTextNode("second"))
1037 root.appendChild(doc.createElement("i"))
1038 self.confirm(len(root.childNodes) == 3
1039 and root.childNodes.length == 3,
1040 "testNormalizeCombineAndNextSibling -- preparation")
1041 doc.normalize()
1042 self.confirm(len(root.childNodes) == 2
1043 and root.childNodes.length == 2
1044 and root.firstChild.data == "firstsecond"
1045 and root.firstChild is not root.lastChild
1046 and root.firstChild.nextSibling is root.lastChild
1047 and root.firstChild.previousSibling is None
1048 and root.lastChild.previousSibling is root.firstChild
1049 and root.lastChild.nextSibling is None
1050 , "testNormalizeCombinedAndNextSibling -- result")
1051 doc.unlink()
1052
1053 def testNormalizeDeleteWithPrevSibling(self):
1054 doc = parseString("<doc/>")
1055 root = doc.documentElement
1056 root.appendChild(doc.createTextNode("first"))
1057 root.appendChild(doc.createTextNode(""))
1058 self.confirm(len(root.childNodes) == 2
1059 and root.childNodes.length == 2,
1060 "testNormalizeDeleteWithPrevSibling -- preparation")
1061 doc.normalize()
1062 self.confirm(len(root.childNodes) == 1
1063 and root.childNodes.length == 1
1064 and root.firstChild.data == "first"
1065 and root.firstChild is root.lastChild
1066 and root.firstChild.nextSibling is None
1067 and root.firstChild.previousSibling is None
1068 , "testNormalizeDeleteWithPrevSibling -- result")
1069 doc.unlink()
1070
1071 def testNormalizeDeleteWithNextSibling(self):
1072 doc = parseString("<doc/>")
1073 root = doc.documentElement
1074 root.appendChild(doc.createTextNode(""))
1075 root.appendChild(doc.createTextNode("second"))
1076 self.confirm(len(root.childNodes) == 2
1077 and root.childNodes.length == 2,
1078 "testNormalizeDeleteWithNextSibling -- preparation")
1079 doc.normalize()
1080 self.confirm(len(root.childNodes) == 1
1081 and root.childNodes.length == 1
1082 and root.firstChild.data == "second"
1083 and root.firstChild is root.lastChild
1084 and root.firstChild.nextSibling is None
1085 and root.firstChild.previousSibling is None
1086 , "testNormalizeDeleteWithNextSibling -- result")
1087 doc.unlink()
1088
1089 def testNormalizeDeleteWithTwoNonTextSiblings(self):
1090 doc = parseString("<doc/>")
1091 root = doc.documentElement
1092 root.appendChild(doc.createElement("i"))
1093 root.appendChild(doc.createTextNode(""))
1094 root.appendChild(doc.createElement("i"))
1095 self.confirm(len(root.childNodes) == 3
1096 and root.childNodes.length == 3,
1097 "testNormalizeDeleteWithTwoSiblings -- preparation")
1098 doc.normalize()
1099 self.confirm(len(root.childNodes) == 2
1100 and root.childNodes.length == 2
1101 and root.firstChild is not root.lastChild
1102 and root.firstChild.nextSibling is root.lastChild
1103 and root.firstChild.previousSibling is None
1104 and root.lastChild.previousSibling is root.firstChild
1105 and root.lastChild.nextSibling is None
1106 , "testNormalizeDeleteWithTwoSiblings -- result")
1107 doc.unlink()
1108
1109 def testNormalizeDeleteAndCombine(self):
1110 doc = parseString("<doc/>")
1111 root = doc.documentElement
1112 root.appendChild(doc.createTextNode(""))
1113 root.appendChild(doc.createTextNode("second"))
1114 root.appendChild(doc.createTextNode(""))
1115 root.appendChild(doc.createTextNode("fourth"))
1116 root.appendChild(doc.createTextNode(""))
1117 self.confirm(len(root.childNodes) == 5
1118 and root.childNodes.length == 5,
1119 "testNormalizeDeleteAndCombine -- preparation")
1120 doc.normalize()
1121 self.confirm(len(root.childNodes) == 1
1122 and root.childNodes.length == 1
1123 and root.firstChild is root.lastChild
1124 and root.firstChild.data == "secondfourth"
1125 and root.firstChild.previousSibling is None
1126 and root.firstChild.nextSibling is None
1127 , "testNormalizeDeleteAndCombine -- result")
1128 doc.unlink()
1129
1130 def testNormalizeRecursion(self):
1131 doc = parseString("<doc>"
1132 "<o>"
1133 "<i/>"
1134 "t"
1135 #
1136 #x
1137 "</o>"
1138 "<o>"
1139 "<o>"
1140 "t2"
1141 #x2
1142 "</o>"
1143 "t3"
1144 #x3
1145 "</o>"
1146 #
1147 "</doc>")
1148 root = doc.documentElement
1149 root.childNodes[0].appendChild(doc.createTextNode(""))
1150 root.childNodes[0].appendChild(doc.createTextNode("x"))
1151 root.childNodes[1].childNodes[0].appendChild(doc.createTextNode("x2"))
1152 root.childNodes[1].appendChild(doc.createTextNode("x3"))
1153 root.appendChild(doc.createTextNode(""))
1154 self.confirm(len(root.childNodes) == 3
1155 and root.childNodes.length == 3
1156 and len(root.childNodes[0].childNodes) == 4
1157 and root.childNodes[0].childNodes.length == 4
1158 and len(root.childNodes[1].childNodes) == 3
1159 and root.childNodes[1].childNodes.length == 3
1160 and len(root.childNodes[1].childNodes[0].childNodes) == 2
1161 and root.childNodes[1].childNodes[0].childNodes.length == 2
1162 , "testNormalize2 -- preparation")
1163 doc.normalize()
1164 self.confirm(len(root.childNodes) == 2
1165 and root.childNodes.length == 2
1166 and len(root.childNodes[0].childNodes) == 2
1167 and root.childNodes[0].childNodes.length == 2
1168 and len(root.childNodes[1].childNodes) == 2
1169 and root.childNodes[1].childNodes.length == 2
1170 and len(root.childNodes[1].childNodes[0].childNodes) == 1
1171 and root.childNodes[1].childNodes[0].childNodes.length == 1
1172 , "testNormalize2 -- childNodes lengths")
1173 self.confirm(root.childNodes[0].childNodes[1].data == "tx"
1174 and root.childNodes[1].childNodes[0].childNodes[0].data == "t2x2"
1175 and root.childNodes[1].childNodes[1].data == "t3x3"
1176 , "testNormalize2 -- joined text fields")
1177 self.confirm(root.childNodes[0].childNodes[1].nextSibling is None
1178 and root.childNodes[0].childNodes[1].previousSibling
1179 is root.childNodes[0].childNodes[0]
1180 and root.childNodes[0].childNodes[0].previousSibling is None
1181 and root.childNodes[0].childNodes[0].nextSibling
1182 is root.childNodes[0].childNodes[1]
1183 and root.childNodes[1].childNodes[1].nextSibling is None
1184 and root.childNodes[1].childNodes[1].previousSibling
1185 is root.childNodes[1].childNodes[0]
1186 and root.childNodes[1].childNodes[0].previousSibling is None
1187 and root.childNodes[1].childNodes[0].nextSibling
1188 is root.childNodes[1].childNodes[1]
1189 , "testNormalize2 -- sibling pointers")
1190 doc.unlink()
1191
1192
1193 def testBug0777884(self):
1194 doc = parseString("<o>text</o>")
1195 text = doc.documentElement.childNodes[0]
1196 self.assertEqual(text.nodeType, Node.TEXT_NODE)
1197 # Should run quietly, doing nothing.
1198 text.normalize()
1199 doc.unlink()
1200
1201 def testBug1433694(self):
1202 doc = parseString("<o><i/>t</o>")
1203 node = doc.documentElement
1204 node.childNodes[1].nodeValue = ""
1205 node.normalize()
1206 self.assertIsNone(node.childNodes[-1].nextSibling,
1207 "Final child's .nextSibling should be None")
1208
1209 def testSiblings(self):
1210 doc = parseString("<doc><?pi?>text?<elm/></doc>")
1211 root = doc.documentElement
1212 (pi, text, elm) = root.childNodes
1213
1214 self.confirm(pi.nextSibling is text and
1215 pi.previousSibling is None and
1216 text.nextSibling is elm and
1217 text.previousSibling is pi and
1218 elm.nextSibling is None and
1219 elm.previousSibling is text, "testSiblings")
1220
1221 doc.unlink()
1222
1223 def testParents(self):
1224 doc = parseString(
1225 "<doc><elm1><elm2/><elm2><elm3/></elm2></elm1></doc>")
1226 root = doc.documentElement
1227 elm1 = root.childNodes[0]
1228 (elm2a, elm2b) = elm1.childNodes
1229 elm3 = elm2b.childNodes[0]
1230
1231 self.confirm(root.parentNode is doc and
1232 elm1.parentNode is root and
1233 elm2a.parentNode is elm1 and
1234 elm2b.parentNode is elm1 and
1235 elm3.parentNode is elm2b, "testParents")
1236 doc.unlink()
1237
1238 def testNodeListItem(self):
1239 doc = parseString("<doc><e/><e/></doc>")
1240 children = doc.childNodes
1241 docelem = children[0]
1242 self.confirm(children[0] is children.item(0)
1243 and children.item(1) is None
1244 and docelem.childNodes.item(0) is docelem.childNodes[0]
1245 and docelem.childNodes.item(1) is docelem.childNodes[1]
1246 and docelem.childNodes.item(0).childNodes.item(0) is None,
1247 "test NodeList.item()")
1248 doc.unlink()
1249
1250 def testEncodings(self):
1251 doc = parseString('<foo>&#x20ac;</foo>')
1252 self.assertEqual(doc.toxml(),
1253 '<?xml version="1.0" ?><foo>\u20ac</foo>')
1254 self.assertEqual(doc.toxml('utf-8'),
1255 b'<?xml version="1.0" encoding="utf-8"?><foo>\xe2\x82\xac</foo>')
1256 self.assertEqual(doc.toxml('iso-8859-15'),
1257 b'<?xml version="1.0" encoding="iso-8859-15"?><foo>\xa4</foo>')
1258 self.assertEqual(doc.toxml('us-ascii'),
1259 b'<?xml version="1.0" encoding="us-ascii"?><foo>&#8364;</foo>')
1260 self.assertEqual(doc.toxml('utf-16'),
1261 '<?xml version="1.0" encoding="utf-16"?>'
1262 '<foo>\u20ac</foo>'.encode('utf-16'))
1263
1264 # Verify that character decoding errors raise exceptions instead
1265 # of crashing
1266 with self.assertRaises((UnicodeDecodeError, ExpatError)):
1267 parseString(
1268 b'<fran\xe7ais>Comment \xe7a va ? Tr\xe8s bien ?</fran\xe7ais>'
1269 )
1270
1271 doc.unlink()
1272
1273 def testStandalone(self):
1274 doc = parseString('<foo>&#x20ac;</foo>')
1275 self.assertEqual(doc.toxml(),
1276 '<?xml version="1.0" ?><foo>\u20ac</foo>')
1277 self.assertEqual(doc.toxml(standalone=None),
1278 '<?xml version="1.0" ?><foo>\u20ac</foo>')
1279 self.assertEqual(doc.toxml(standalone=True),
1280 '<?xml version="1.0" standalone="yes"?><foo>\u20ac</foo>')
1281 self.assertEqual(doc.toxml(standalone=False),
1282 '<?xml version="1.0" standalone="no"?><foo>\u20ac</foo>')
1283 self.assertEqual(doc.toxml('utf-8', True),
1284 b'<?xml version="1.0" encoding="utf-8" standalone="yes"?>'
1285 b'<foo>\xe2\x82\xac</foo>')
1286
1287 doc.unlink()
1288
1289 class UserDataHandler:
1290 called = 0
1291 def handle(self, operation, key, data, src, dst):
1292 dst.setUserData(key, data + 1, self)
1293 src.setUserData(key, None, None)
1294 self.called = 1
1295
1296 def testUserData(self):
1297 dom = Document()
1298 n = dom.createElement('e')
1299 self.assertIsNone(n.getUserData("foo"))
1300 n.setUserData("foo", None, None)
1301 self.assertIsNone(n.getUserData("foo"))
1302 n.setUserData("foo", 12, 12)
1303 n.setUserData("bar", 13, 13)
1304 self.assertEqual(n.getUserData("foo"), 12)
1305 self.assertEqual(n.getUserData("bar"), 13)
1306 n.setUserData("foo", None, None)
1307 self.assertIsNone(n.getUserData("foo"))
1308 self.assertEqual(n.getUserData("bar"), 13)
1309
1310 handler = self.UserDataHandler()
1311 n.setUserData("bar", 12, handler)
1312 c = n.cloneNode(1)
1313 self.confirm(handler.called
1314 and n.getUserData("bar") is None
1315 and c.getUserData("bar") == 13)
1316 n.unlink()
1317 c.unlink()
1318 dom.unlink()
1319
1320 def checkRenameNodeSharedConstraints(self, doc, node):
1321 # Make sure illegal NS usage is detected:
1322 self.assertRaises(xml.dom.NamespaceErr, doc.renameNode, node,
1323 "http://xml.python.org/ns", "xmlns:foo")
1324 doc2 = parseString("<doc/>")
1325 self.assertRaises(xml.dom.WrongDocumentErr, doc2.renameNode, node,
1326 xml.dom.EMPTY_NAMESPACE, "foo")
1327
1328 def testRenameAttribute(self):
1329 doc = parseString("<doc a='v'/>")
1330 elem = doc.documentElement
1331 attrmap = elem.attributes
1332 attr = elem.attributes['a']
1333
1334 # Simple renaming
1335 attr = doc.renameNode(attr, xml.dom.EMPTY_NAMESPACE, "b")
1336 self.confirm(attr.name == "b"
1337 and attr.nodeName == "b"
1338 and attr.localName is None
1339 and attr.namespaceURI == xml.dom.EMPTY_NAMESPACE
1340 and attr.prefix is None
1341 and attr.value == "v"
1342 and elem.getAttributeNode("a") is None
1343 and elem.getAttributeNode("b").isSameNode(attr)
1344 and attrmap["b"].isSameNode(attr)
1345 and attr.ownerDocument.isSameNode(doc)
1346 and attr.ownerElement.isSameNode(elem))
1347
1348 # Rename to have a namespace, no prefix
1349 attr = doc.renameNode(attr, "http://xml.python.org/ns", "c")
1350 self.confirm(attr.name == "c"
1351 and attr.nodeName == "c"
1352 and attr.localName == "c"
1353 and attr.namespaceURI == "http://xml.python.org/ns"
1354 and attr.prefix is None
1355 and attr.value == "v"
1356 and elem.getAttributeNode("a") is None
1357 and elem.getAttributeNode("b") is None
1358 and elem.getAttributeNode("c").isSameNode(attr)
1359 and elem.getAttributeNodeNS(
1360 "http://xml.python.org/ns", "c").isSameNode(attr)
1361 and attrmap["c"].isSameNode(attr)
1362 and attrmap[("http://xml.python.org/ns", "c")].isSameNode(attr))
1363
1364 # Rename to have a namespace, with prefix
1365 attr = doc.renameNode(attr, "http://xml.python.org/ns2", "p:d")
1366 self.confirm(attr.name == "p:d"
1367 and attr.nodeName == "p:d"
1368 and attr.localName == "d"
1369 and attr.namespaceURI == "http://xml.python.org/ns2"
1370 and attr.prefix == "p"
1371 and attr.value == "v"
1372 and elem.getAttributeNode("a") is None
1373 and elem.getAttributeNode("b") is None
1374 and elem.getAttributeNode("c") is None
1375 and elem.getAttributeNodeNS(
1376 "http://xml.python.org/ns", "c") is None
1377 and elem.getAttributeNode("p:d").isSameNode(attr)
1378 and elem.getAttributeNodeNS(
1379 "http://xml.python.org/ns2", "d").isSameNode(attr)
1380 and attrmap["p:d"].isSameNode(attr)
1381 and attrmap[("http://xml.python.org/ns2", "d")].isSameNode(attr))
1382
1383 # Rename back to a simple non-NS node
1384 attr = doc.renameNode(attr, xml.dom.EMPTY_NAMESPACE, "e")
1385 self.confirm(attr.name == "e"
1386 and attr.nodeName == "e"
1387 and attr.localName is None
1388 and attr.namespaceURI == xml.dom.EMPTY_NAMESPACE
1389 and attr.prefix is None
1390 and attr.value == "v"
1391 and elem.getAttributeNode("a") is None
1392 and elem.getAttributeNode("b") is None
1393 and elem.getAttributeNode("c") is None
1394 and elem.getAttributeNode("p:d") is None
1395 and elem.getAttributeNodeNS(
1396 "http://xml.python.org/ns", "c") is None
1397 and elem.getAttributeNode("e").isSameNode(attr)
1398 and attrmap["e"].isSameNode(attr))
1399
1400 self.assertRaises(xml.dom.NamespaceErr, doc.renameNode, attr,
1401 "http://xml.python.org/ns", "xmlns")
1402 self.checkRenameNodeSharedConstraints(doc, attr)
1403 doc.unlink()
1404
1405 def testRenameElement(self):
1406 doc = parseString("<doc/>")
1407 elem = doc.documentElement
1408
1409 # Simple renaming
1410 elem = doc.renameNode(elem, xml.dom.EMPTY_NAMESPACE, "a")
1411 self.confirm(elem.tagName == "a"
1412 and elem.nodeName == "a"
1413 and elem.localName is None
1414 and elem.namespaceURI == xml.dom.EMPTY_NAMESPACE
1415 and elem.prefix is None
1416 and elem.ownerDocument.isSameNode(doc))
1417
1418 # Rename to have a namespace, no prefix
1419 elem = doc.renameNode(elem, "http://xml.python.org/ns", "b")
1420 self.confirm(elem.tagName == "b"
1421 and elem.nodeName == "b"
1422 and elem.localName == "b"
1423 and elem.namespaceURI == "http://xml.python.org/ns"
1424 and elem.prefix is None
1425 and elem.ownerDocument.isSameNode(doc))
1426
1427 # Rename to have a namespace, with prefix
1428 elem = doc.renameNode(elem, "http://xml.python.org/ns2", "p:c")
1429 self.confirm(elem.tagName == "p:c"
1430 and elem.nodeName == "p:c"
1431 and elem.localName == "c"
1432 and elem.namespaceURI == "http://xml.python.org/ns2"
1433 and elem.prefix == "p"
1434 and elem.ownerDocument.isSameNode(doc))
1435
1436 # Rename back to a simple non-NS node
1437 elem = doc.renameNode(elem, xml.dom.EMPTY_NAMESPACE, "d")
1438 self.confirm(elem.tagName == "d"
1439 and elem.nodeName == "d"
1440 and elem.localName is None
1441 and elem.namespaceURI == xml.dom.EMPTY_NAMESPACE
1442 and elem.prefix is None
1443 and elem.ownerDocument.isSameNode(doc))
1444
1445 self.checkRenameNodeSharedConstraints(doc, elem)
1446 doc.unlink()
1447
1448 def testRenameOther(self):
1449 # We have to create a comment node explicitly since not all DOM
1450 # builders used with minidom add comments to the DOM.
1451 doc = xml.dom.minidom.getDOMImplementation().createDocument(
1452 xml.dom.EMPTY_NAMESPACE, "e", None)
1453 node = doc.createComment("comment")
1454 self.assertRaises(xml.dom.NotSupportedErr, doc.renameNode, node,
1455 xml.dom.EMPTY_NAMESPACE, "foo")
1456 doc.unlink()
1457
1458 def testWholeText(self):
1459 doc = parseString("<doc>a</doc>")
1460 elem = doc.documentElement
1461 text = elem.childNodes[0]
1462 self.assertEqual(text.nodeType, Node.TEXT_NODE)
1463
1464 self.checkWholeText(text, "a")
1465 elem.appendChild(doc.createTextNode("b"))
1466 self.checkWholeText(text, "ab")
1467 elem.insertBefore(doc.createCDATASection("c"), text)
1468 self.checkWholeText(text, "cab")
1469
1470 # make sure we don't cross other nodes
1471 splitter = doc.createComment("comment")
1472 elem.appendChild(splitter)
1473 text2 = doc.createTextNode("d")
1474 elem.appendChild(text2)
1475 self.checkWholeText(text, "cab")
1476 self.checkWholeText(text2, "d")
1477
1478 x = doc.createElement("x")
1479 elem.replaceChild(x, splitter)
1480 splitter = x
1481 self.checkWholeText(text, "cab")
1482 self.checkWholeText(text2, "d")
1483
1484 x = doc.createProcessingInstruction("y", "z")
1485 elem.replaceChild(x, splitter)
1486 splitter = x
1487 self.checkWholeText(text, "cab")
1488 self.checkWholeText(text2, "d")
1489
1490 elem.removeChild(splitter)
1491 self.checkWholeText(text, "cabd")
1492 self.checkWholeText(text2, "cabd")
1493
1494 def testPatch1094164(self):
1495 doc = parseString("<doc><e/></doc>")
1496 elem = doc.documentElement
1497 e = elem.firstChild
1498 self.assertIs(e.parentNode, elem, "Before replaceChild()")
1499 # Check that replacing a child with itself leaves the tree unchanged
1500 elem.replaceChild(e, e)
1501 self.assertIs(e.parentNode, elem, "After replaceChild()")
1502
1503 def testReplaceWholeText(self):
1504 def setup():
1505 doc = parseString("<doc>a<e/>d</doc>")
1506 elem = doc.documentElement
1507 text1 = elem.firstChild
1508 text2 = elem.lastChild
1509 splitter = text1.nextSibling
1510 elem.insertBefore(doc.createTextNode("b"), splitter)
1511 elem.insertBefore(doc.createCDATASection("c"), text1)
1512 return doc, elem, text1, splitter, text2
1513
1514 doc, elem, text1, splitter, text2 = setup()
1515 text = text1.replaceWholeText("new content")
1516 self.checkWholeText(text, "new content")
1517 self.checkWholeText(text2, "d")
1518 self.assertEqual(len(elem.childNodes), 3)
1519
1520 doc, elem, text1, splitter, text2 = setup()
1521 text = text2.replaceWholeText("new content")
1522 self.checkWholeText(text, "new content")
1523 self.checkWholeText(text1, "cab")
1524 self.assertEqual(len(elem.childNodes), 5)
1525
1526 doc, elem, text1, splitter, text2 = setup()
1527 text = text1.replaceWholeText("")
1528 self.checkWholeText(text2, "d")
1529 self.confirm(text is None
1530 and len(elem.childNodes) == 2)
1531
1532 def testSchemaType(self):
1533 doc = parseString(
1534 "<!DOCTYPE doc [\n"
1535 " <!ENTITY e1 SYSTEM 'http://xml.python.org/e1'>\n"
1536 " <!ENTITY e2 SYSTEM 'http://xml.python.org/e2'>\n"
1537 " <!ATTLIST doc id ID #IMPLIED \n"
1538 " ref IDREF #IMPLIED \n"
1539 " refs IDREFS #IMPLIED \n"
1540 " enum (a|b) #IMPLIED \n"
1541 " ent ENTITY #IMPLIED \n"
1542 " ents ENTITIES #IMPLIED \n"
1543 " nm NMTOKEN #IMPLIED \n"
1544 " nms NMTOKENS #IMPLIED \n"
1545 " text CDATA #IMPLIED \n"
1546 " >\n"
1547 "]><doc id='name' notid='name' text='splat!' enum='b'"
1548 " ref='name' refs='name name' ent='e1' ents='e1 e2'"
1549 " nm='123' nms='123 abc' />")
1550 elem = doc.documentElement
1551 # We don't want to rely on any specific loader at this point, so
1552 # just make sure we can get to all the names, and that the
1553 # DTD-based namespace is right. The names can vary by loader
1554 # since each supports a different level of DTD information.
1555 t = elem.schemaType
1556 self.confirm(t.name is None
1557 and t.namespace == xml.dom.EMPTY_NAMESPACE)
1558 names = "id notid text enum ref refs ent ents nm nms".split()
1559 for name in names:
1560 a = elem.getAttributeNode(name)
1561 t = a.schemaType
1562 self.confirm(hasattr(t, "name")
1563 and t.namespace == xml.dom.EMPTY_NAMESPACE)
1564
1565 def testSetIdAttribute(self):
1566 doc = parseString("<doc a1='v' a2='w'/>")
1567 e = doc.documentElement
1568 a1 = e.getAttributeNode("a1")
1569 a2 = e.getAttributeNode("a2")
1570 self.confirm(doc.getElementById("v") is None
1571 and not a1.isId
1572 and not a2.isId)
1573 e.setIdAttribute("a1")
1574 self.confirm(e.isSameNode(doc.getElementById("v"))
1575 and a1.isId
1576 and not a2.isId)
1577 e.setIdAttribute("a2")
1578 self.confirm(e.isSameNode(doc.getElementById("v"))
1579 and e.isSameNode(doc.getElementById("w"))
1580 and a1.isId
1581 and a2.isId)
1582 # replace the a1 node; the new node should *not* be an ID
1583 a3 = doc.createAttribute("a1")
1584 a3.value = "v"
1585 e.setAttributeNode(a3)
1586 self.confirm(doc.getElementById("v") is None
1587 and e.isSameNode(doc.getElementById("w"))
1588 and not a1.isId
1589 and a2.isId
1590 and not a3.isId)
1591 # renaming an attribute should not affect its ID-ness:
1592 doc.renameNode(a2, xml.dom.EMPTY_NAMESPACE, "an")
1593 self.confirm(e.isSameNode(doc.getElementById("w"))
1594 and a2.isId)
1595
1596 def testSetIdAttributeNS(self):
1597 NS1 = "http://xml.python.org/ns1"
1598 NS2 = "http://xml.python.org/ns2"
1599 doc = parseString("<doc"
1600 " xmlns:ns1='" + NS1 + "'"
1601 " xmlns:ns2='" + NS2 + "'"
1602 " ns1:a1='v' ns2:a2='w'/>")
1603 e = doc.documentElement
1604 a1 = e.getAttributeNodeNS(NS1, "a1")
1605 a2 = e.getAttributeNodeNS(NS2, "a2")
1606 self.confirm(doc.getElementById("v") is None
1607 and not a1.isId
1608 and not a2.isId)
1609 e.setIdAttributeNS(NS1, "a1")
1610 self.confirm(e.isSameNode(doc.getElementById("v"))
1611 and a1.isId
1612 and not a2.isId)
1613 e.setIdAttributeNS(NS2, "a2")
1614 self.confirm(e.isSameNode(doc.getElementById("v"))
1615 and e.isSameNode(doc.getElementById("w"))
1616 and a1.isId
1617 and a2.isId)
1618 # replace the a1 node; the new node should *not* be an ID
1619 a3 = doc.createAttributeNS(NS1, "a1")
1620 a3.value = "v"
1621 e.setAttributeNode(a3)
1622 self.assertTrue(e.isSameNode(doc.getElementById("w")))
1623 self.assertFalse(a1.isId)
1624 self.assertTrue(a2.isId)
1625 self.assertFalse(a3.isId)
1626 self.assertIsNone(doc.getElementById("v"))
1627 # renaming an attribute should not affect its ID-ness:
1628 doc.renameNode(a2, xml.dom.EMPTY_NAMESPACE, "an")
1629 self.confirm(e.isSameNode(doc.getElementById("w"))
1630 and a2.isId)
1631
1632 def testSetIdAttributeNode(self):
1633 NS1 = "http://xml.python.org/ns1"
1634 NS2 = "http://xml.python.org/ns2"
1635 doc = parseString("<doc"
1636 " xmlns:ns1='" + NS1 + "'"
1637 " xmlns:ns2='" + NS2 + "'"
1638 " ns1:a1='v' ns2:a2='w'/>")
1639 e = doc.documentElement
1640 a1 = e.getAttributeNodeNS(NS1, "a1")
1641 a2 = e.getAttributeNodeNS(NS2, "a2")
1642 self.confirm(doc.getElementById("v") is None
1643 and not a1.isId
1644 and not a2.isId)
1645 e.setIdAttributeNode(a1)
1646 self.confirm(e.isSameNode(doc.getElementById("v"))
1647 and a1.isId
1648 and not a2.isId)
1649 e.setIdAttributeNode(a2)
1650 self.confirm(e.isSameNode(doc.getElementById("v"))
1651 and e.isSameNode(doc.getElementById("w"))
1652 and a1.isId
1653 and a2.isId)
1654 # replace the a1 node; the new node should *not* be an ID
1655 a3 = doc.createAttributeNS(NS1, "a1")
1656 a3.value = "v"
1657 e.setAttributeNode(a3)
1658 self.assertTrue(e.isSameNode(doc.getElementById("w")))
1659 self.assertFalse(a1.isId)
1660 self.assertTrue(a2.isId)
1661 self.assertFalse(a3.isId)
1662 self.assertIsNone(doc.getElementById("v"))
1663 # renaming an attribute should not affect its ID-ness:
1664 doc.renameNode(a2, xml.dom.EMPTY_NAMESPACE, "an")
1665 self.confirm(e.isSameNode(doc.getElementById("w"))
1666 and a2.isId)
1667
1668 def assert_recursive_equal(self, doc, doc2):
1669 stack = [(doc, doc2)]
1670 while stack:
1671 n1, n2 = stack.pop()
1672 self.assertEqual(n1.nodeType, n2.nodeType)
1673 self.assertEqual(len(n1.childNodes), len(n2.childNodes))
1674 self.assertEqual(n1.nodeName, n2.nodeName)
1675 self.assertFalse(n1.isSameNode(n2))
1676 self.assertFalse(n2.isSameNode(n1))
1677 if n1.nodeType == Node.DOCUMENT_TYPE_NODE:
1678 len(n1.entities)
1679 len(n2.entities)
1680 len(n1.notations)
1681 len(n2.notations)
1682 self.assertEqual(len(n1.entities), len(n2.entities))
1683 self.assertEqual(len(n1.notations), len(n2.notations))
1684 for i in range(len(n1.notations)):
1685 # XXX this loop body doesn't seem to be executed?
1686 no1 = n1.notations.item(i)
1687 no2 = n1.notations.item(i)
1688 self.assertEqual(no1.name, no2.name)
1689 self.assertEqual(no1.publicId, no2.publicId)
1690 self.assertEqual(no1.systemId, no2.systemId)
1691 stack.append((no1, no2))
1692 for i in range(len(n1.entities)):
1693 e1 = n1.entities.item(i)
1694 e2 = n2.entities.item(i)
1695 self.assertEqual(e1.notationName, e2.notationName)
1696 self.assertEqual(e1.publicId, e2.publicId)
1697 self.assertEqual(e1.systemId, e2.systemId)
1698 stack.append((e1, e2))
1699 if n1.nodeType != Node.DOCUMENT_NODE:
1700 self.assertTrue(n1.ownerDocument.isSameNode(doc))
1701 self.assertTrue(n2.ownerDocument.isSameNode(doc2))
1702 for i in range(len(n1.childNodes)):
1703 stack.append((n1.childNodes[i], n2.childNodes[i]))
1704
1705 def testPickledDocument(self):
1706 doc = parseString(sample)
1707 for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
1708 s = pickle.dumps(doc, proto)
1709 doc2 = pickle.loads(s)
1710 self.assert_recursive_equal(doc, doc2)
1711
1712 def testDeepcopiedDocument(self):
1713 doc = parseString(sample)
1714 doc2 = copy.deepcopy(doc)
1715 self.assert_recursive_equal(doc, doc2)
1716
1717 def testSerializeCommentNodeWithDoubleHyphen(self):
1718 doc = create_doc_without_doctype()
1719 doc.appendChild(doc.createComment("foo--bar"))
1720 self.assertRaises(ValueError, doc.toxml)
1721
1722
1723 def testEmptyXMLNSValue(self):
1724 doc = parseString("<element xmlns=''>\n"
1725 "<foo/>\n</element>")
1726 doc2 = parseString(doc.toxml())
1727 self.assertEqual(doc2.namespaceURI, xml.dom.EMPTY_NAMESPACE)
1728
1729 def testExceptionOnSpacesInXMLNSValue(self):
1730 with self.assertRaises((ValueError, ExpatError)):
1731 parseString(
1732 '<element xmlns:abc="http:abc.com/de f g/hi/j k">' +
1733 '<abc:foo /></element>'
1734 )
1735
1736 def testDocRemoveChild(self):
1737 doc = parse(tstfile)
1738 title_tag = doc.documentElement.getElementsByTagName("TITLE")[0]
1739 self.assertRaises( xml.dom.NotFoundErr, doc.removeChild, title_tag)
1740 num_children_before = len(doc.childNodes)
1741 doc.removeChild(doc.childNodes[0])
1742 num_children_after = len(doc.childNodes)
1743 self.assertEqual(num_children_after, num_children_before - 1)
1744
1745 def testProcessingInstructionNameError(self):
1746 # wrong variable in .nodeValue property will
1747 # lead to "NameError: name 'data' is not defined"
1748 doc = parse(tstfile)
1749 pi = doc.createProcessingInstruction("y", "z")
1750 pi.nodeValue = "crash"
1751
1752 def test_minidom_attribute_order(self):
1753 xml_str = '<?xml version="1.0" ?><curriculum status="public" company="example"/>'
1754 doc = parseString(xml_str)
1755 output = io.StringIO()
1756 doc.writexml(output)
1757 self.assertEqual(output.getvalue(), xml_str)
1758
1759 def test_toxml_with_attributes_ordered(self):
1760 xml_str = '<?xml version="1.0" ?><curriculum status="public" company="example"/>'
1761 doc = parseString(xml_str)
1762 self.assertEqual(doc.toxml(), xml_str)
1763
1764 def test_toprettyxml_with_attributes_ordered(self):
1765 xml_str = '<?xml version="1.0" ?><curriculum status="public" company="example"/>'
1766 doc = parseString(xml_str)
1767 self.assertEqual(doc.toprettyxml(),
1768 '<?xml version="1.0" ?>\n'
1769 '<curriculum status="public" company="example"/>\n')
1770
1771 def test_toprettyxml_with_cdata(self):
1772 xml_str = '<?xml version="1.0" ?><root><node><![CDATA[</data>]]></node></root>'
1773 doc = parseString(xml_str)
1774 self.assertEqual(doc.toprettyxml(),
1775 '<?xml version="1.0" ?>\n'
1776 '<root>\n'
1777 '\t<node><![CDATA[</data>]]></node>\n'
1778 '</root>\n')
1779
1780 def test_cdata_parsing(self):
1781 xml_str = '<?xml version="1.0" ?><root><node><![CDATA[</data>]]></node></root>'
1782 dom1 = parseString(xml_str)
1783 self.checkWholeText(dom1.getElementsByTagName('node')[0].firstChild, '</data>')
1784 dom2 = parseString(dom1.toprettyxml())
1785 self.checkWholeText(dom2.getElementsByTagName('node')[0].firstChild, '</data>')
1786
1787 if __name__ == "__main__":
1788 unittest.main()