Home | Trees | Indices | Help |
|
---|
|
1 # -*- coding: utf-8 -*- 2 3 """ 4 Tests for the ElementTree API 5 6 Only test cases that apply equally well to etree and ElementTree 7 belong here. Note that there is a second test module called test_io.py 8 for IO related test cases. 9 """ 10 11 import unittest 12 import os, re, tempfile, copy, operator, sys 13 14 this_dir = os.path.dirname(__file__) 15 if this_dir not in sys.path: 16 sys.path.insert(0, this_dir) # needed for Py3 17 18 from common_imports import BytesIO, etree 19 from common_imports import ElementTree, cElementTree, ET_VERSION, CET_VERSION 20 from common_imports import filter_by_version, fileInTestDir, canonicalize, HelperTestCase 21 from common_imports import _str, _bytes, unicode, next 22 23 if cElementTree is not None and (CET_VERSION <= (1,0,7) or sys.version_info >= (3,3)): 24 cElementTree = None 25 26 if ElementTree is not None: 27 print("Comparing with ElementTree %s" % getattr(ElementTree, "VERSION", "?")) 28 29 if cElementTree is not None: 30 print("Comparing with cElementTree %s" % getattr(cElementTree, "VERSION", "?"))33 etree = None 34 required_versions_ET = {} 35 required_versions_cET = {} 3622238 try: 39 XMLParser = self.etree.XMLParser 40 except AttributeError: 41 assert 'ElementTree' in self.etree.__name__ 42 XMLParser = self.etree.TreeBuilder 43 return XMLParser(**kwargs)4446 for i in range(10): 47 e = self.etree.Element('foo') 48 self.assertEqual(e.tag, 'foo') 49 self.assertEqual(e.text, None) 50 self.assertEqual(e.tail, None)5153 Element = self.etree.Element 54 55 root = Element('root') 56 root.append(Element('one')) 57 root.append(Element('two')) 58 root.append(Element('three')) 59 self.assertEqual(3, len(root)) 60 self.assertEqual('one', root[0].tag) 61 self.assertEqual('two', root[1].tag) 62 self.assertEqual('three', root[2].tag) 63 self.assertRaises(IndexError, operator.getitem, root, 3)64 65 # test weird dictionary interaction leading to segfault previously67 root = self.etree.Element('root') 68 self.assertEqual(root.tag, "root") 69 add = self.etree.ElementTree(file=BytesIO('<foo>Foo</foo>')) 70 self.assertEqual(add.getroot().tag, "foo") 71 self.assertEqual(add.getroot().text, "Foo") 72 root.append(self.etree.Element('baz')) 73 self.assertEqual(root.tag, "root") 74 self.assertEqual(root[0].tag, "baz")7577 Element = self.etree.Element 78 SubElement = self.etree.SubElement 79 80 root = Element('root') 81 SubElement(root, 'one') 82 SubElement(root, 'two') 83 SubElement(root, 'three') 84 self.assertEqual(3, len(root)) 85 self.assertEqual('one', root[0].tag) 86 self.assertEqual('two', root[1].tag) 87 self.assertEqual('three', root[2].tag)8890 Element = self.etree.Element 91 SubElement = self.etree.SubElement 92 93 root1 = Element('root') 94 SubElement(root1, 'one') 95 self.assertTrue(root1[0] in root1) 96 97 root2 = Element('root') 98 SubElement(root2, 'two') 99 SubElement(root2, 'three') 100 self.assertTrue(root2[0] in root2) 101 self.assertTrue(root2[1] in root2) 102 103 self.assertFalse(root1[0] in root2) 104 self.assertFalse(root2[0] in root1) 105 self.assertFalse(None in root2)106108 ElementTree = self.etree.ElementTree 109 110 f = BytesIO('<doc>Test<one>One</one></doc>') 111 doc = ElementTree(file=f) 112 root = doc.getroot() 113 self.assertEqual(1, len(root)) 114 self.assertEqual('one', root[0].tag) 115 self.assertRaises(IndexError, operator.getitem, root, 1)116118 ElementTree = self.etree.ElementTree 119 120 f = BytesIO('<doc><one>One</one><two>Two</two>hm<three>Three</three></doc>') 121 doc = ElementTree(file=f) 122 root = doc.getroot() 123 self.assertEqual(3, len(root)) 124 self.assertEqual('one', root[0].tag) 125 self.assertEqual('two', root[1].tag) 126 self.assertEqual('three', root[2].tag)127129 ElementTree = self.etree.ElementTree 130 131 f = BytesIO('<doc>Test</doc>') 132 doc = ElementTree(file=f) 133 root = doc.getroot() 134 self.assertEqual(0, len(root))135137 Element = self.etree.Element 138 SubElement = self.etree.SubElement 139 a = Element('a') 140 b = SubElement(a, 'b') 141 c = SubElement(a, 'c') 142 d = SubElement(a, 'd') 143 self.assertEqual(d, a[-1]) 144 self.assertEqual(c, a[-2]) 145 self.assertEqual(b, a[-3]) 146 self.assertRaises(IndexError, operator.getitem, a, -4) 147 a[-1] = e = Element('e') 148 self.assertEqual(e, a[-1]) 149 del a[-1] 150 self.assertEqual(2, len(a))151153 ElementTree = self.etree.ElementTree 154 155 f = BytesIO('<doc><one>One</one><two>Two</two></doc>') 156 doc = ElementTree(file=f) 157 root = doc.getroot() 158 self.assertEqual(2, len(root)) 159 self.assertEqual('one', root[0].tag) 160 self.assertEqual('two', root[1].tag)161163 ElementTree = self.etree.ElementTree 164 165 f = BytesIO('<doc>This is a text</doc>') 166 doc = ElementTree(file=f) 167 root = doc.getroot() 168 self.assertEqual('This is a text', root.text)169171 ElementTree = self.etree.ElementTree 172 173 f = BytesIO('<doc></doc>') 174 doc = ElementTree(file=f) 175 root = doc.getroot() 176 self.assertEqual(None, root.text)177179 ElementTree = self.etree.ElementTree 180 181 f = BytesIO('<doc><one>One</one></doc>') 182 doc = ElementTree(file=f) 183 root = doc.getroot() 184 self.assertEqual(None, root.text) 185 self.assertEqual('One', root[0].text)186188 ElementTree = self.etree.ElementTree 189 190 f = BytesIO('<doc>This is > than a text</doc>') 191 doc = ElementTree(file=f) 192 root = doc.getroot() 193 self.assertEqual('This is > than a text', root.text)194196 Element = self.etree.Element 197 198 a = Element("a") 199 a.text = "<>&" 200 self.assertXML(_bytes('<a><>&</a>'), 201 a)202204 tostring = self.etree.tostring 205 Element = self.etree.Element 206 207 a = Element("a") 208 a.text = "<>&" 209 self.assertEqual(_bytes('<a><>&</a>'), 210 tostring(a))211 217 218 a = Element("a") 219 a.text = strTest("text") 220 self.assertXML(_bytes('<a>text</a>'), 221 a)224 ElementTree = self.etree.ElementTree 225 226 f = BytesIO('<doc>This is <i>mixed</i> content.</doc>') 227 doc = ElementTree(file=f) 228 root = doc.getroot() 229 self.assertEqual(1, len(root)) 230 self.assertEqual('This is ', root.text) 231 self.assertEqual(None, root.tail) 232 self.assertEqual('mixed', root[0].text) 233 self.assertEqual(' content.', root[0].tail)234236 Element = self.etree.Element 237 SubElement = self.etree.SubElement 238 239 class strTest(str): 240 pass241 242 a = Element("a") 243 SubElement(a, "t").tail = strTest("tail") 244 self.assertXML(_bytes('<a><t></t>tail</a>'), 245 a) 246248 # this is discouraged for ET compat, should not be tested... 249 XML = self.etree.XML 250 251 root = XML(_bytes('<doc>This is <i>mixed</i> content.</doc>')) 252 self.assertEqual(1, len(root)) 253 self.assertEqual('This is ', root.text) 254 self.assertEqual(None, root.tail) 255 self.assertEqual('mixed', root[0].text) 256 self.assertEqual(' content.', root[0].tail) 257 258 del root[0].tail 259 260 self.assertEqual(1, len(root)) 261 self.assertEqual('This is ', root.text) 262 self.assertEqual(None, root.tail) 263 self.assertEqual('mixed', root[0].text) 264 self.assertEqual(None, root[0].tail) 265 266 root[0].tail = "TAIL" 267 268 self.assertEqual(1, len(root)) 269 self.assertEqual('This is ', root.text) 270 self.assertEqual(None, root.tail) 271 self.assertEqual('mixed', root[0].text) 272 self.assertEqual('TAIL', root[0].tail)273275 Element = self.etree.Element 276 ElementTree = self.etree.ElementTree 277 278 el = Element('hoi') 279 doc = ElementTree(el) 280 root = doc.getroot() 281 self.assertEqual(None, root.text) 282 self.assertEqual('hoi', root.tag)283285 ElementTree = self.etree.ElementTree 286 287 f = BytesIO('<doc one="One" two="Two"/>') 288 doc = ElementTree(file=f) 289 root = doc.getroot() 290 self.assertEqual('One', root.attrib['one']) 291 self.assertEqual('Two', root.attrib['two']) 292 self.assertRaises(KeyError, operator.getitem, root.attrib, 'three')293295 ElementTree = self.etree.ElementTree 296 297 f = BytesIO('<doc one="One" two="Two"/>') 298 doc = ElementTree(file=f) 299 root = doc.getroot() 300 self.assertEqual('One', root.attrib.get('one')) 301 self.assertEqual('Two', root.attrib.get('two')) 302 self.assertEqual(None, root.attrib.get('three')) 303 self.assertEqual('foo', root.attrib.get('three', 'foo'))304306 ElementTree = self.etree.ElementTree 307 308 f = BytesIO('<doc one="One" two="Two"/>') 309 doc = ElementTree(file=f) 310 root = doc.getroot() 311 attrib = dict(root.attrib) 312 self.assertEqual('One', attrib['one']) 313 self.assertEqual('Two', attrib['two']) 314 self.assertRaises(KeyError, operator.getitem, attrib, 'three')315317 ElementTree = self.etree.ElementTree 318 319 f = BytesIO('<doc one="One" two="Two"/>') 320 doc = ElementTree(file=f) 321 root = doc.getroot() 322 attrib = copy.copy(root.attrib) 323 self.assertEqual('One', attrib['one']) 324 self.assertEqual('Two', attrib['two']) 325 self.assertRaises(KeyError, operator.getitem, attrib, 'three')326328 ElementTree = self.etree.ElementTree 329 330 f = BytesIO('<doc one="One" two="Two"/>') 331 doc = ElementTree(file=f) 332 root = doc.getroot() 333 attrib = copy.deepcopy(root.attrib) 334 self.assertEqual('One', attrib['one']) 335 self.assertEqual('Two', attrib['two']) 336 self.assertRaises(KeyError, operator.getitem, attrib, 'three')337339 ElementTree = self.etree.ElementTree 340 341 f = BytesIO('<doc one="One" two="Two"/>') 342 doc = ElementTree(file=f) 343 root = doc.getroot() 344 self.assertEqual('One', root.get('one')) 345 self.assertEqual('Two', root.get('two')) 346 self.assertEqual(None, root.get('three')) 347 self.assertEqual('foo', root.get('three', 'foo'))348350 XML = self.etree.XML 351 352 root = XML(_bytes('<doc one="One" two="Two"/>')) 353 self.assertEqual('One', root.get('one')) 354 self.assertEqual('Two', root.get('two')) 355 root.attrib.clear() 356 self.assertEqual(None, root.get('one')) 357 self.assertEqual(None, root.get('two'))358360 Element = self.etree.Element 361 362 root = Element("root", one="One") 363 root.set("two", "Two") 364 self.assertEqual('One', root.get('one')) 365 self.assertEqual('Two', root.get('two')) 366 root.attrib.clear() 367 self.assertEqual(None, root.get('one')) 368 self.assertEqual(None, root.get('two'))369371 Element = self.etree.Element 372 SubElement = self.etree.SubElement 373 374 attribNS = '{http://foo/bar}x' 375 376 parent = Element('parent') 377 parent.set(attribNS, 'a') 378 child = SubElement(parent, 'child') 379 child.set(attribNS, 'b') 380 381 self.assertEqual('a', parent.get(attribNS)) 382 self.assertEqual('b', child.get(attribNS)) 383 384 parent.clear() 385 self.assertEqual(None, parent.get(attribNS)) 386 self.assertEqual('b', child.get(attribNS))387389 ElementTree = self.etree.ElementTree 390 391 f = BytesIO('<doc one="One" two="Two"/>') 392 doc = ElementTree(file=f) 393 root = doc.getroot() 394 self.assertEqual('One', root.attrib['one']) 395 self.assertEqual('Two', root.attrib['two']) 396 397 self.assertEqual('One', root.attrib.pop('one')) 398 399 self.assertEqual(None, root.attrib.get('one')) 400 self.assertEqual('Two', root.attrib['two'])401403 root = self.etree.XML(_bytes('<doc one="One" two="Two"/>')) 404 self.assertRaises(KeyError, root.attrib.pop, 'NONE') 405 406 self.assertEqual('One', root.attrib['one']) 407 self.assertEqual('Two', root.attrib['two'])408410 root = self.etree.XML(_bytes('<doc one="One" two="Two"/>')) 411 self.assertEqual('Three', root.attrib.pop('three', 'Three'))412414 root = self.etree.XML(_bytes('<doc/>')) 415 self.assertEqual('Three', root.attrib.pop('three', 'Three'))416418 root = self.etree.XML(_bytes('<doc one="One" two="Two"/>')) 419 self.assertRaises(TypeError, root.attrib.pop, 'One', None, None)420422 XML = self.etree.XML 423 424 root = XML(_bytes('<doc alpha="Alpha" beta="Beta"/>')) 425 items = list(root.attrib.items()) 426 items.sort() 427 self.assertEqual( 428 [('alpha', 'Alpha'), ('beta', 'Beta')], 429 items) 430 431 root.attrib.update({'alpha' : 'test', 'gamma' : 'Gamma'}) 432 433 items = list(root.attrib.items()) 434 items.sort() 435 self.assertEqual( 436 [('alpha', 'test'), ('beta', 'Beta'), ('gamma', 'Gamma')], 437 items)438440 XML = self.etree.XML 441 442 root = XML(_bytes('<doc alpha="Alpha" beta="Beta"/>')) 443 items = list(root.attrib.items()) 444 items.sort() 445 self.assertEqual( 446 [('alpha', 'Alpha'), ('beta', 'Beta')], 447 items) 448 449 root.attrib.update({'alpha' : 'test', 'gamma' : 'Gamma'}.items()) 450 451 items = list(root.attrib.items()) 452 items.sort() 453 self.assertEqual( 454 [('alpha', 'test'), ('beta', 'Beta'), ('gamma', 'Gamma')], 455 items)456458 XML = self.etree.XML 459 460 root = XML(_bytes('<doc alpha="Alpha" beta="Beta"/>')) 461 items = list(root.attrib.items()) 462 items.sort() 463 self.assertEqual( 464 [('alpha', 'Alpha'), ('beta', 'Beta')], 465 items) 466 467 root.attrib.update(iter({'alpha' : 'test', 'gamma' : 'Gamma'}.items())) 468 469 items = list(root.attrib.items()) 470 items.sort() 471 self.assertEqual( 472 [('alpha', 'test'), ('beta', 'Beta'), ('gamma', 'Gamma')], 473 items)474476 XML = self.etree.XML 477 478 root = XML(_bytes('<doc alpha="Alpha" beta="Beta"/>')) 479 items = list(root.attrib.items()) 480 items.sort() 481 self.assertEqual( 482 [('alpha', 'Alpha'), ('beta', 'Beta')], 483 items) 484 485 other = XML(_bytes('<doc alpha="test" gamma="Gamma"/>')) 486 root.attrib.update(other.attrib) 487 488 items = list(root.attrib.items()) 489 items.sort() 490 self.assertEqual( 491 [('alpha', 'test'), ('beta', 'Beta'), ('gamma', 'Gamma')], 492 items)493495 XML = self.etree.XML 496 497 root = XML(_bytes('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')) 498 keys = list(root.attrib.keys()) 499 keys.sort() 500 self.assertEqual(['alpha', 'beta', 'gamma'], keys)501503 XML = self.etree.XML 504 505 root = XML(_bytes('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')) 506 keys = list(root.keys()) 507 keys.sort() 508 self.assertEqual(['alpha', 'beta', 'gamma'], keys)509511 XML = self.etree.XML 512 513 root = XML(_bytes('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')) 514 items = list(root.items()) 515 items.sort() 516 self.assertEqual( 517 [('alpha','Alpha'), ('beta','Beta'), ('gamma','Gamma')], 518 items)519521 XML = self.etree.XML 522 523 root = XML(_bytes('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')) 524 keys = list(root.keys()) 525 keys.sort() 526 self.assertEqual(['bar', '{http://ns.codespeak.net/test}baz'], 527 keys)528530 XML = self.etree.XML 531 532 root = XML(_bytes('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')) 533 values = list(root.attrib.values()) 534 values.sort() 535 self.assertEqual(['Alpha', 'Beta', 'Gamma'], values)536538 XML = self.etree.XML 539 540 root = XML(_bytes('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')) 541 values = list(root.attrib.values()) 542 values.sort() 543 self.assertEqual( 544 ['Bar', 'Baz'], values)545547 XML = self.etree.XML 548 549 root = XML(_bytes('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')) 550 items = list(root.attrib.items()) 551 items.sort() 552 self.assertEqual([ 553 ('alpha', 'Alpha'), 554 ('beta', 'Beta'), 555 ('gamma', 'Gamma'), 556 ], 557 items)558560 XML = self.etree.XML 561 562 root = XML(_bytes('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')) 563 items = list(root.attrib.items()) 564 items.sort() 565 self.assertEqual( 566 [('bar', 'Bar'), ('{http://ns.codespeak.net/test}baz', 'Baz')], 567 items)568570 XML = self.etree.XML 571 572 expected = "{'{http://ns.codespeak.net/test}baz': 'Baz', 'bar': 'Bar'}" 573 alternative = "{'bar': 'Bar', '{http://ns.codespeak.net/test}baz': 'Baz'}" 574 575 root = XML(_bytes('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')) 576 try: 577 self.assertEqual(expected, str(root.attrib)) 578 except AssertionError: 579 self.assertEqual(alternative, str(root.attrib))580582 XML = self.etree.XML 583 584 root = XML(_bytes('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')) 585 self.assertEqual( 586 True, 'bar' in root.attrib) 587 self.assertEqual( 588 False, 'baz' in root.attrib) 589 self.assertEqual( 590 False, 'hah' in root.attrib) 591 self.assertEqual( 592 True, 593 '{http://ns.codespeak.net/test}baz' in root.attrib)594596 Element = self.etree.Element 597 598 root = Element("root") 599 root.set("attr", "TEST") 600 self.assertEqual("TEST", root.get("attr"))601603 Element = self.etree.Element 604 605 root = Element("root") 606 root.set("attr", "TEST") 607 self.assertEqual("TEST", root.attrib["attr"]) 608 609 root2 = Element("root2", root.attrib) 610 self.assertEqual("TEST", root2.attrib["attr"])611613 XML = self.etree.XML 614 615 root = XML(_bytes('<doc alpha="Alpha" beta="Beta" gamma="Gamma" />')) 616 result = [] 617 for key in root.attrib: 618 result.append(key) 619 result.sort() 620 self.assertEqual(['alpha', 'beta', 'gamma'], result)621623 Element = self.etree.Element 624 625 a = Element('a') 626 a.attrib['foo'] = 'Foo' 627 a.attrib['bar'] = 'Bar' 628 self.assertEqual('Foo', a.attrib['foo']) 629 del a.attrib['foo'] 630 self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo')631633 Element = self.etree.Element 634 635 a = Element('a') 636 a.attrib['{http://a/}foo'] = 'Foo' 637 a.attrib['{http://a/}bar'] = 'Bar' 638 self.assertEqual(None, a.get('foo')) 639 self.assertEqual('Foo', a.get('{http://a/}foo')) 640 self.assertEqual('Foo', a.attrib['{http://a/}foo']) 641 642 self.assertRaises(KeyError, operator.delitem, a.attrib, 'foo') 643 self.assertEqual('Foo', a.attrib['{http://a/}foo']) 644 645 del a.attrib['{http://a/}foo'] 646 self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo')647649 XML = self.etree.XML 650 651 a = XML(_bytes('<a xmlns:nsa="http://a/" nsa:foo="FooNS" foo="Foo" />')) 652 653 self.assertEqual('Foo', a.attrib['foo']) 654 self.assertEqual('FooNS', a.attrib['{http://a/}foo']) 655 656 del a.attrib['foo'] 657 self.assertEqual('FooNS', a.attrib['{http://a/}foo']) 658 self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo') 659 self.assertRaises(KeyError, operator.delitem, a.attrib, 'foo') 660 661 del a.attrib['{http://a/}foo'] 662 self.assertRaises(KeyError, operator.getitem, a.attrib, '{http://a/}foo') 663 self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo') 664 665 a = XML(_bytes('<a xmlns:nsa="http://a/" foo="Foo" nsa:foo="FooNS" />')) 666 667 self.assertEqual('Foo', a.attrib['foo']) 668 self.assertEqual('FooNS', a.attrib['{http://a/}foo']) 669 670 del a.attrib['foo'] 671 self.assertEqual('FooNS', a.attrib['{http://a/}foo']) 672 self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo') 673 674 del a.attrib['{http://a/}foo'] 675 self.assertRaises(KeyError, operator.getitem, a.attrib, '{http://a/}foo') 676 self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo')677679 XML = self.etree.XML 680 681 root = XML(_bytes('<doc>This is a text.</doc>')) 682 self.assertEqual(0, len(root)) 683 self.assertEqual('This is a text.', root.text)684686 XMLID = self.etree.XMLID 687 XML = self.etree.XML 688 xml_text = _bytes(''' 689 <document> 690 <h1 id="chapter1">...</h1> 691 <p id="note1" class="note">...</p> 692 <p>Regular paragraph.</p> 693 <p xml:id="xmlid">XML:ID paragraph.</p> 694 <p id="warn1" class="warning">...</p> 695 </document> 696 ''') 697 698 root, dic = XMLID(xml_text) 699 root2 = XML(xml_text) 700 self.assertEqual(self._writeElement(root), 701 self._writeElement(root2)) 702 expected = { 703 "chapter1" : root[0], 704 "note1" : root[1], 705 "warn1" : root[4] 706 } 707 self.assertEqual(dic, expected)708710 fromstring = self.etree.fromstring 711 712 root = fromstring('<doc>This is a text.</doc>') 713 self.assertEqual(0, len(root)) 714 self.assertEqual('This is a text.', root.text)715 716 required_versions_ET['test_fromstringlist'] = (1,3)718 fromstringlist = self.etree.fromstringlist 719 720 root = fromstringlist(["<do", "c>T", "hi", "s is", 721 " a text.<", "/doc", ">"]) 722 self.assertEqual(0, len(root)) 723 self.assertEqual('This is a text.', root.text)724 725 required_versions_ET['test_fromstringlist_characters'] = (1,3)727 fromstringlist = self.etree.fromstringlist 728 729 root = fromstringlist(list('<doc>This is a text.</doc>')) 730 self.assertEqual(0, len(root)) 731 self.assertEqual('This is a text.', root.text)732 733 required_versions_ET['test_fromstringlist_single'] = (1,3)735 fromstringlist = self.etree.fromstringlist 736 737 root = fromstringlist(['<doc>This is a text.</doc>']) 738 self.assertEqual(0, len(root)) 739 self.assertEqual('This is a text.', root.text)740742 iselement = self.etree.iselement 743 Element = self.etree.Element 744 ElementTree = self.etree.ElementTree 745 XML = self.etree.XML 746 Comment = self.etree.Comment 747 ProcessingInstruction = self.etree.ProcessingInstruction 748 749 el = Element('hoi') 750 self.assertTrue(iselement(el)) 751 752 el2 = XML(_bytes('<foo/>')) 753 self.assertTrue(iselement(el2)) 754 755 tree = ElementTree(element=Element('dag')) 756 self.assertTrue(not iselement(tree)) 757 self.assertTrue(iselement(tree.getroot())) 758 759 c = Comment('test') 760 self.assertTrue(iselement(c)) 761 762 p = ProcessingInstruction("test", "some text") 763 self.assertTrue(iselement(p))764766 XML = self.etree.XML 767 768 root = XML(_bytes('<doc><one/><two>Two</two>Hm<three/></doc>')) 769 result = [] 770 for el in root: 771 result.append(el.tag) 772 self.assertEqual(['one', 'two', 'three'], result)773775 XML = self.etree.XML 776 777 root = XML(_bytes('<doc></doc>')) 778 result = [] 779 for el in root: 780 result.append(el.tag) 781 self.assertEqual([], result)782784 XML = self.etree.XML 785 786 root = XML(_bytes('<doc>Text</doc>')) 787 result = [] 788 for el in root: 789 result.append(el.tag) 790 self.assertEqual([], result)791793 # this would cause a crash in the past 794 fromstring = self.etree.fromstring 795 root = etree.fromstring('<html><p></p>x</html>') 796 for elem in root: 797 elem.tail = ''798800 XML = self.etree.XML 801 root = XML(_bytes('<doc><one/><two>Two</two>Hm<three/></doc>')) 802 result = [] 803 for el in reversed(root): 804 result.append(el.tag) 805 self.assertEqual(['three', 'two', 'one'], result)806808 XML = self.etree.XML 809 810 root = XML(_bytes('<doc><one/><two>Two</two>Hm<three/></doc>')) 811 result = [] 812 add = True 813 for el in root: 814 result.append(el.tag) 815 if add: 816 self.etree.SubElement(root, 'four') 817 add = False 818 self.assertEqual(['one', 'two', 'three', 'four'], result)819821 XML = self.etree.XML 822 823 root = XML(_bytes('<doc><one/><two>Two</two>Hm<three/></doc>')) 824 result = [] 825 for el in root: 826 result.append(el.tag) 827 del root[-1] 828 self.assertEqual(['one', 'two'], result)829831 XML = self.etree.XML 832 833 root = XML(_bytes('<doc><one/><two/></doc>')) 834 result = [] 835 for el0 in root: 836 result.append(el0.tag) 837 for el1 in root: 838 result.append(el1.tag) 839 self.assertEqual(['one','one', 'two', 'two', 'one', 'two'], result)840 841 required_versions_ET['test_itertext'] = (1,3)843 # ET 1.3+ 844 XML = self.etree.XML 845 root = XML(_bytes("<root>RTEXT<a></a>ATAIL<b/><c>CTEXT</c>CTAIL</root>")) 846 847 text = list(root.itertext()) 848 self.assertEqual(["RTEXT", "ATAIL", "CTEXT", "CTAIL"], 849 text)850 851 required_versions_ET['test_itertext_child'] = (1,3)853 # ET 1.3+ 854 XML = self.etree.XML 855 root = XML(_bytes("<root>RTEXT<a></a>ATAIL<b/><c>CTEXT</c>CTAIL</root>")) 856 857 text = list(root[2].itertext()) 858 self.assertEqual(["CTEXT"], 859 text)860862 XML = self.etree.XML 863 root = XML(_bytes('<a><b><c/></b><b/><c><b/></c></a>')) 864 self.assertEqual(len(list(root.findall("c"))), 1) 865 self.assertEqual(len(list(root.findall(".//c"))), 2) 866 self.assertEqual(len(list(root.findall(".//b"))), 3) 867 self.assertEqual(len(list(root.findall(".//b"))[0]), 1) 868 self.assertEqual(len(list(root.findall(".//b"))[1]), 0) 869 self.assertEqual(len(list(root.findall(".//b"))[2]), 0)870872 XML = self.etree.XML 873 root = XML(_bytes('<a xmlns:x="X" xmlns:y="Y"><x:b><c/></x:b><b/><c><x:b/><b/></c><b/></a>')) 874 self.assertEqual(len(list(root.findall(".//{X}b"))), 2) 875 self.assertEqual(len(list(root.findall(".//b"))), 3) 876 self.assertEqual(len(list(root.findall("b"))), 2)877879 Element = self.etree.Element 880 881 el = Element('tag', foo='Foo', bar='Bar') 882 self.assertEqual('Foo', el.attrib['foo']) 883 self.assertEqual('Bar', el.attrib['bar'])884886 Element = self.etree.Element 887 888 el = Element('tag', {'foo': 'Foo', 'bar': 'Bar'}) 889 self.assertEqual('Foo', el.attrib['foo']) 890 self.assertEqual('Bar', el.attrib['bar'])891893 Element = self.etree.Element 894 895 el = Element('tag', {'foo': 'Foo', 'bar': 'Bar'}, baz='Baz') 896 self.assertEqual('Foo', el.attrib['foo']) 897 self.assertEqual('Bar', el.attrib['bar']) 898 self.assertEqual('Baz', el.attrib['baz'])899901 Element = self.etree.Element 902 903 el = Element('tag', {'foo': 'Foo', 'bar': 'Bar'}, bar='Baz') 904 self.assertEqual('Foo', el.attrib['foo']) 905 self.assertEqual('Baz', el.attrib['bar'])906908 Element = self.etree.Element 909 910 el = Element('tag', {'{ns1}foo':'Foo', '{ns2}bar':'Bar'}) 911 self.assertEqual('Foo', el.attrib['{ns1}foo']) 912 self.assertEqual('Bar', el.attrib['{ns2}bar'])913915 Element = self.etree.Element 916 SubElement = self.etree.SubElement 917 918 el = Element('tag') 919 SubElement(el, 'foo', {'foo':'Foo'}, baz="Baz") 920 self.assertEqual("Baz", el[0].attrib['baz']) 921 self.assertEqual('Foo', el[0].attrib['foo'])922924 Element = self.etree.Element 925 SubElement = self.etree.SubElement 926 927 el = Element('tag') 928 SubElement(el, 'foo', {'{ns1}foo':'Foo', '{ns2}bar':'Bar'}) 929 self.assertEqual('Foo', el[0].attrib['{ns1}foo']) 930 self.assertEqual('Bar', el[0].attrib['{ns2}bar'])931933 ElementTree = self.etree.ElementTree 934 XML = self.etree.XML 935 936 for i in range(10): 937 f = BytesIO() 938 root = XML(_bytes('<doc%s>This is a test.</doc%s>' % (i, i))) 939 tree = ElementTree(element=root) 940 tree.write(f) 941 data = f.getvalue() 942 self.assertEqual( 943 _bytes('<doc%s>This is a test.</doc%s>' % (i, i)), 944 canonicalize(data))945 946 required_versions_ET['test_write_method_html'] = (1,3)948 ElementTree = self.etree.ElementTree 949 Element = self.etree.Element 950 SubElement = self.etree.SubElement 951 952 html = Element('html') 953 body = SubElement(html, 'body') 954 p = SubElement(body, 'p') 955 p.text = "html" 956 SubElement(p, 'br').tail = "test" 957 958 tree = ElementTree(element=html) 959 f = BytesIO() 960 tree.write(f, method="html") 961 data = f.getvalue().replace(_bytes('\n'),_bytes('')) 962 963 self.assertEqual(_bytes('<html><body><p>html<br>test</p></body></html>'), 964 data)965 966 required_versions_ET['test_write_method_text'] = (1,3)968 ElementTree = self.etree.ElementTree 969 Element = self.etree.Element 970 SubElement = self.etree.SubElement 971 972 a = Element('a') 973 a.text = "A" 974 a.tail = "tail" 975 b = SubElement(a, 'b') 976 b.text = "B" 977 b.tail = "TAIL" 978 c = SubElement(a, 'c') 979 c.text = "C" 980 981 tree = ElementTree(element=a) 982 f = BytesIO() 983 tree.write(f, method="text") 984 data = f.getvalue() 985 986 self.assertEqual(_bytes('ABTAILCtail'), 987 data)988990 ElementTree = self.etree.ElementTree 991 XML = self.etree.XML 992 993 tree = ElementTree( XML(_bytes('<doc>This is a test.</doc>')) ) 994 self.assertRaises(IOError, tree.write, 995 "definitely////\\-\\nonexisting\\-\\////FILE")996 997 # this could trigger a crash, apparently because the document 998 # reference was prematurely garbage collected1000 Element = self.etree.Element 1001 1002 element = Element('tag') 1003 for i in range(10): 1004 element.attrib['key'] = 'value' 1005 value = element.attrib['key'] 1006 self.assertEqual(value, 'value')1007 1008 # from doctest; for some reason this caused crashes too1010 Element = self.etree.Element 1011 ElementTree = self.etree.ElementTree 1012 1013 f = BytesIO() 1014 for i in range(10): 1015 element = Element('tag%s' % i) 1016 self._check_element(element) 1017 tree = ElementTree(element) 1018 tree.write(f) 1019 self._check_element_tree(tree)10201022 Element = self.etree.Element 1023 SubElement = self.etree.SubElement 1024 1025 el = Element('foo') 1026 el2 = SubElement(el, 'bar') 1027 el3 = SubElement(el2, 'baz') 1028 1029 al = Element('foo2') 1030 al2 = SubElement(al, 'bar2') 1031 al3 = SubElement(al2, 'baz2') 1032 1033 # now move al2 into el 1034 el.append(al2) 1035 1036 # now change al3 directly 1037 al3.text = 'baz2-modified' 1038 1039 # it should have changed through this route too 1040 self.assertEqual( 1041 'baz2-modified', 1042 el[1][0].text)10431045 Element = self.etree.Element 1046 SubElement = self.etree.SubElement 1047 1048 a = Element('a') 1049 b = SubElement(a, 'b') 1050 a.text = 'hoi' 1051 self.assertEqual( 1052 'hoi', 1053 a.text) 1054 self.assertEqual( 1055 'b', 1056 a[0].tag)10571059 Element = self.etree.Element 1060 SubElement = self.etree.SubElement 1061 1062 a = Element('a') 1063 a.text = 'hoi' 1064 b = SubElement(a ,'b') 1065 self.assertEqual( 1066 'hoi', 1067 a.text) 1068 self.assertEqual( 1069 'b', 1070 a[0].tag)10711073 Element = self.etree.Element 1074 1075 a = Element('a') 1076 1077 a.text = 'foo' 1078 a.text = None 1079 1080 self.assertEqual( 1081 None, 1082 a.text) 1083 self.assertXML(_bytes('<a></a>'), a)10841086 Element = self.etree.Element 1087 1088 a = Element('a') 1089 self.assertEqual(None, a.text) 1090 1091 a.text = '' 1092 self.assertEqual('', a.text) 1093 self.assertXML(_bytes('<a></a>'), a)10941096 Element = self.etree.Element 1097 SubElement = self.etree.SubElement 1098 1099 a = Element('a') 1100 a.tail = 'dag' 1101 self.assertEqual('dag', 1102 a.tail) 1103 b = SubElement(a, 'b') 1104 b.tail = 'hoi' 1105 self.assertEqual('hoi', 1106 b.tail) 1107 self.assertEqual('dag', 1108 a.tail)11091111 Element = self.etree.Element 1112 1113 a = Element('a') 1114 b = Element('b') 1115 b.tail = 'b_tail' 1116 a.append(b) 1117 self.assertEqual('b_tail', 1118 b.tail)11191121 Element = self.etree.Element 1122 SubElement = self.etree.SubElement 1123 1124 a = Element('a') 1125 b = SubElement(a, 'b') 1126 b.tail = 'foo' 1127 b.tail = 'bar' 1128 self.assertEqual('bar', 1129 b.tail) 1130 self.assertXML(_bytes('<a><b></b>bar</a>'), a)11311133 Element = self.etree.Element 1134 a = Element('a') 1135 a.tail = 'foo' 1136 a.tail = None 1137 self.assertEqual( 1138 None, 1139 a.tail) 1140 self.assertXML(_bytes('<a></a>'), a)1141 1142 required_versions_ET['test_extend'] = (1,3)1144 root = self.etree.Element('foo') 1145 for i in range(3): 1146 element = self.etree.SubElement(root, 'a%s' % i) 1147 element.text = "text%d" % i 1148 element.tail = "tail%d" % i 1149 1150 elements = [] 1151 for i in range(3): 1152 new_element = self.etree.Element("test%s" % i) 1153 new_element.text = "TEXT%s" % i 1154 new_element.tail = "TAIL%s" % i 1155 elements.append(new_element) 1156 1157 root.extend(elements) 1158 1159 self.assertEqual( 1160 ["a0", "a1", "a2", "test0", "test1", "test2"], 1161 [ el.tag for el in root ]) 1162 self.assertEqual( 1163 ["text0", "text1", "text2", "TEXT0", "TEXT1", "TEXT2"], 1164 [ el.text for el in root ]) 1165 self.assertEqual( 1166 ["tail0", "tail1", "tail2", "TAIL0", "TAIL1", "TAIL2"], 1167 [ el.tail for el in root ])11681170 Element = self.etree.Element 1171 SubElement = self.etree.SubElement 1172 Comment = self.etree.Comment 1173 1174 a = Element('a') 1175 a.append(Comment('foo')) 1176 self.assertEqual(a[0].tag, Comment) 1177 self.assertEqual(a[0].text, 'foo')1178 1179 # ElementTree < 1.3 adds whitespace around comments 1180 required_versions_ET['test_comment_text'] = (1,3)1182 Element = self.etree.Element 1183 SubElement = self.etree.SubElement 1184 Comment = self.etree.Comment 1185 tostring = self.etree.tostring 1186 1187 a = Element('a') 1188 a.append(Comment('foo')) 1189 self.assertEqual(a[0].text, 'foo') 1190 1191 self.assertEqual( 1192 _bytes('<a><!--foo--></a>'), 1193 tostring(a)) 1194 1195 a[0].text = "TEST" 1196 self.assertEqual(a[0].text, 'TEST') 1197 1198 self.assertEqual( 1199 _bytes('<a><!--TEST--></a>'), 1200 tostring(a))1201 1202 # ElementTree < 1.3 adds whitespace around comments 1203 required_versions_ET['test_comment_whitespace'] = (1,3)1205 Element = self.etree.Element 1206 SubElement = self.etree.SubElement 1207 Comment = self.etree.Comment 1208 tostring = self.etree.tostring 1209 1210 a = Element('a') 1211 a.append(Comment(' foo ')) 1212 self.assertEqual(a[0].text, ' foo ') 1213 self.assertEqual( 1214 _bytes('<a><!-- foo --></a>'), 1215 tostring(a))12161218 Comment = self.etree.Comment 1219 c = Comment('foo') 1220 self.assertEqual({}, c.attrib) 1221 self.assertEqual([], list(c.keys())) 1222 self.assertEqual([], list(c.items())) 1223 self.assertEqual(None, c.get('hoi')) 1224 self.assertEqual(0, len(c)) 1225 # should not iterate 1226 for i in c: 1227 pass12281230 # lxml.etree separates target and text 1231 Element = self.etree.Element 1232 SubElement = self.etree.SubElement 1233 ProcessingInstruction = self.etree.ProcessingInstruction 1234 1235 a = Element('a') 1236 a.append(ProcessingInstruction('foo', 'some more text')) 1237 self.assertEqual(a[0].tag, ProcessingInstruction) 1238 self.assertXML(_bytes("<a><?foo some more text?></a>"), 1239 a)12401242 # lxml.etree separates target and text 1243 Element = self.etree.Element 1244 SubElement = self.etree.SubElement 1245 ProcessingInstruction = self.etree.PI 1246 1247 a = Element('a') 1248 a.append(ProcessingInstruction('foo', 'some more text')) 1249 self.assertEqual(a[0].tag, ProcessingInstruction) 1250 self.assertXML(_bytes("<a><?foo some more text?></a>"), 1251 a)12521254 ProcessingInstruction = self.etree.ProcessingInstruction 1255 pi = ProcessingInstruction('foo') 1256 self.assertEqual({}, pi.attrib) 1257 self.assertEqual([], list(pi.keys())) 1258 self.assertEqual([], list(pi.items())) 1259 self.assertEqual(None, pi.get('hoi')) 1260 self.assertEqual(0, len(pi)) 1261 # should not iterate 1262 for i in pi: 1263 pass12641266 Element = self.etree.Element 1267 SubElement = self.etree.SubElement 1268 1269 a = Element('a') 1270 b = SubElement(a, 'b') 1271 c = Element('c') 1272 a[0] = c 1273 self.assertEqual( 1274 c, 1275 a[0]) 1276 self.assertXML(_bytes('<a><c></c></a>'), 1277 a) 1278 self.assertXML(_bytes('<b></b>'), 1279 b)12801282 Element = self.etree.Element 1283 SubElement = self.etree.SubElement 1284 1285 a = Element('a') 1286 for i in range(5): 1287 b = SubElement(a, 'b%s' % i) 1288 c = SubElement(b, 'c') 1289 for i in range(5): 1290 d = Element('d') 1291 e = SubElement(d, 'e') 1292 a[i] = d 1293 self.assertXML( 1294 _bytes('<a><d><e></e></d><d><e></e></d><d><e></e></d><d><e></e></d><d><e></e></d></a>'), 1295 a) 1296 self.assertXML(_bytes('<c></c>'), 1297 c)12981300 Element = self.etree.Element 1301 SubElement = self.etree.SubElement 1302 1303 a = Element('a') 1304 SubElement(a, 'b') 1305 d = Element('d') 1306 a[0] = d 1307 self.assertXML(_bytes('<a><d></d></a>'), a)13081310 Element = self.etree.Element 1311 SubElement = self.etree.SubElement 1312 1313 a = Element('a') 1314 b = SubElement(a, 'b') 1315 1316 self.assertRaises(IndexError, operator.setitem, a, 1, Element('c'))13171319 Element = self.etree.Element 1320 SubElement = self.etree.SubElement 1321 1322 a = Element('a') 1323 b = SubElement(a, 'b') 1324 b.tail = 'B2' 1325 c = Element('c') 1326 c.tail = 'C2' 1327 1328 a[0] = c 1329 self.assertXML( 1330 _bytes('<a><c></c>C2</a>'), 1331 a)13321334 Element = self.etree.Element 1335 SubElement = self.etree.SubElement 1336 1337 a = Element('a') 1338 b = SubElement(a, 'b') 1339 1340 a.tag = 'c' 1341 1342 self.assertEqual( 1343 'c', 1344 a.tag) 1345 1346 self.assertXML( 1347 _bytes('<c><b></b></c>'), 1348 a)13491351 Element = self.etree.Element 1352 SubElement = self.etree.SubElement 1353 tostring = self.etree.tostring 1354 1355 a = Element('{a}a') 1356 b1 = SubElement(a, '{a}b') 1357 b2 = SubElement(a, '{b}b') 1358 1359 self.assertEqual('{a}b', b1.tag) 1360 1361 b1.tag = 'c' 1362 1363 # can't use C14N here! 1364 self.assertEqual('c', b1.tag) 1365 self.assertEqual(_bytes('<c'), tostring(b1)[:2]) 1366 self.assertTrue(_bytes('<c') in tostring(a))13671369 Element = self.etree.Element 1370 SubElement = self.etree.SubElement 1371 tostring = self.etree.tostring 1372 1373 a = Element('{a}a') 1374 b1 = SubElement(a, '{a}b') 1375 b2 = SubElement(a, '{b}b') 1376 1377 a.tag = 'c' 1378 1379 self.assertEqual( 1380 'c', 1381 a.tag) 1382 1383 # can't use C14N here! 1384 self.assertEqual('c', a.tag) 1385 self.assertEqual(_bytes('<c'), tostring(a)[:2])1386 1392 1393 a = Element("a") 1394 a.tag = strTest("TAG") 1395 self.assertXML(_bytes('<TAG></TAG>'), 1396 a) 13971399 Element = self.etree.Element 1400 SubElement = self.etree.SubElement 1401 1402 a = Element('a') 1403 b = SubElement(a, 'b') 1404 c = SubElement(a, 'c') 1405 d = SubElement(a, 'd') 1406 1407 del a[1] 1408 self.assertXML( 1409 _bytes('<a><b></b><d></d></a>'), 1410 a) 1411 1412 del a[0] 1413 self.assertXML( 1414 _bytes('<a><d></d></a>'), 1415 a) 1416 1417 del a[0] 1418 self.assertXML( 1419 _bytes('<a></a>'), 1420 a) 1421 # move deleted element into other tree afterwards 1422 other = Element('other') 1423 other.append(c) 1424 self.assertXML( 1425 _bytes('<other><c></c></other>'), 1426 other)14271429 Element = self.etree.Element 1430 SubElement = self.etree.SubElement 1431 1432 a = Element('a') 1433 b = SubElement(a, 'b') 1434 bs = SubElement(b, 'bs') 1435 c = SubElement(a, 'c') 1436 cs = SubElement(c, 'cs') 1437 1438 el = a[0] 1439 self.assertXML( 1440 _bytes('<a><b><bs></bs></b><c><cs></cs></c></a>'), 1441 a) 1442 self.assertXML(_bytes('<b><bs></bs></b>'), b) 1443 self.assertXML(_bytes('<c><cs></cs></c>'), c) 1444 1445 del a[0] 1446 self.assertXML( 1447 _bytes('<a><c><cs></cs></c></a>'), 1448 a) 1449 self.assertXML(_bytes('<b><bs></bs></b>'), b) 1450 self.assertXML(_bytes('<c><cs></cs></c>'), c) 1451 1452 a.insert(0, el) 1453 self.assertXML( 1454 _bytes('<a><b><bs></bs></b><c><cs></cs></c></a>'), 1455 a) 1456 self.assertXML(_bytes('<b><bs></bs></b>'), b) 1457 self.assertXML(_bytes('<c><cs></cs></c>'), c)14581460 Element = self.etree.Element 1461 SubElement = self.etree.SubElement 1462 1463 a = Element('a') 1464 b = SubElement(a, 'b') 1465 bs = SubElement(b, 'bs') 1466 c = SubElement(a, 'c') 1467 cs = SubElement(c, 'cs') 1468 1469 el = a[0] 1470 del a[0] 1471 a[0] = el 1472 self.assertXML( 1473 _bytes('<a><b><bs></bs></b></a>'), 1474 a) 1475 self.assertXML(_bytes('<b><bs></bs></b>'), b) 1476 self.assertXML(_bytes('<c><cs></cs></c>'), c)14771479 Element = self.etree.Element 1480 SubElement = self.etree.SubElement 1481 1482 a = Element('a') 1483 b = SubElement(a, 'b') 1484 bs = SubElement(b, 'bs') 1485 c = SubElement(a, 'c') 1486 cs = SubElement(c, 'cs') 1487 1488 el = a[0] 1489 del a[0] 1490 a[0:0] = [el] 1491 self.assertXML( 1492 _bytes('<a><b><bs></bs></b><c><cs></cs></c></a>'), 1493 a) 1494 self.assertXML(_bytes('<b><bs></bs></b>'), b) 1495 self.assertXML(_bytes('<c><cs></cs></c>'), c)14961498 XML = self.etree.XML 1499 a = XML(_bytes('<a><b></b>B2<c></c>C2</a>')) 1500 b, c = a 1501 1502 a[:] = [] 1503 1504 self.assertEqual("B2", b.tail) 1505 self.assertEqual("C2", c.tail)15061508 XML = self.etree.XML 1509 root = XML(_bytes( 1510 '<foo><bar xmlns:baz="http://huhu"><puh><baz:bump1 /><baz:bump2 /></puh></bar></foo>')) 1511 root[:] = root.findall('.//puh') # delete bar from hierarchy 1512 1513 # previously, this lost a namespace declaration on bump2 1514 result = self.etree.tostring(root) 1515 foo = self.etree.fromstring(result) 1516 1517 self.assertEqual('puh', foo[0].tag) 1518 self.assertEqual('{http://huhu}bump1', foo[0][0].tag) 1519 self.assertEqual('{http://huhu}bump2', foo[0][1].tag)15201522 ElementTree = self.etree.ElementTree 1523 f = BytesIO('<a><b></b>B2<c></c>C2</a>') 1524 doc = ElementTree(file=f) 1525 a = doc.getroot() 1526 del a[0] 1527 self.assertXML( 1528 _bytes('<a><c></c>C2</a>'), 1529 a)15301532 Element = self.etree.Element 1533 1534 a = Element('a') 1535 a.text = 'foo' 1536 a.tail = 'bar' 1537 a.set('hoi', 'dag') 1538 a.clear() 1539 self.assertEqual(None, a.text) 1540 self.assertEqual(None, a.tail) 1541 self.assertEqual(None, a.get('hoi')) 1542 self.assertEqual('a', a.tag)15431545 Element = self.etree.Element 1546 SubElement = self.etree.SubElement 1547 1548 a = Element('a') 1549 a.text = 'foo' 1550 a.tail = 'bar' 1551 a.set('hoi', 'dag') 1552 b = SubElement(a, 'b') 1553 c = SubElement(b, 'c') 1554 a.clear() 1555 self.assertEqual(None, a.text) 1556 self.assertEqual(None, a.tail) 1557 self.assertEqual(None, a.get('hoi')) 1558 self.assertEqual('a', a.tag) 1559 self.assertEqual(0, len(a)) 1560 self.assertXML(_bytes('<a></a>'), 1561 a) 1562 self.assertXML(_bytes('<b><c></c></b>'), 1563 b)15641566 ElementTree = self.etree.ElementTree 1567 f = BytesIO('<a><b></b>B2<c></c>C2</a>') 1568 doc = ElementTree(file=f) 1569 a = doc.getroot() 1570 a.clear() 1571 self.assertXML( 1572 _bytes('<a></a>'), 1573 a)15741576 Element = self.etree.Element 1577 SubElement = self.etree.SubElement 1578 1579 a = Element('a') 1580 b = SubElement(a, 'b') 1581 c = SubElement(a, 'c') 1582 d = Element('d') 1583 a.insert(0, d) 1584 1585 self.assertEqual( 1586 d, 1587 a[0]) 1588 1589 self.assertXML( 1590 _bytes('<a><d></d><b></b><c></c></a>'), 1591 a) 1592 1593 e = Element('e') 1594 a.insert(2, e) 1595 self.assertEqual( 1596 e, 1597 a[2]) 1598 self.assertXML( 1599 _bytes('<a><d></d><b></b><e></e><c></c></a>'), 1600 a)16011603 Element = self.etree.Element 1604 SubElement = self.etree.SubElement 1605 1606 a = Element('a') 1607 b = SubElement(a, 'b') 1608 c = Element('c') 1609 1610 a.insert(2, c) 1611 self.assertEqual( 1612 c, 1613 a[1]) 1614 self.assertXML( 1615 _bytes('<a><b></b><c></c></a>'), 1616 a)16171619 Element = self.etree.Element 1620 SubElement = self.etree.SubElement 1621 1622 a = Element('a') 1623 b = SubElement(a, 'b') 1624 c = SubElement(a, 'c') 1625 1626 d = Element('d') 1627 a.insert(-1, d) 1628 self.assertEqual( 1629 d, 1630 a[-2]) 1631 self.assertXML( 1632 _bytes('<a><b></b><d></d><c></c></a>'), 1633 a)16341636 Element = self.etree.Element 1637 SubElement = self.etree.SubElement 1638 1639 a = Element('a') 1640 b = SubElement(a, 'b') 1641 1642 c = Element('c') 1643 c.tail = 'C2' 1644 1645 a.insert(0, c) 1646 self.assertXML( 1647 _bytes('<a><c></c>C2<b></b></a>'), 1648 a)16491651 Element = self.etree.Element 1652 SubElement = self.etree.SubElement 1653 1654 a = Element('a') 1655 b = SubElement(a, 'b') 1656 c = SubElement(a, 'c') 1657 1658 a.remove(b) 1659 self.assertEqual( 1660 c, 1661 a[0]) 1662 self.assertXML( 1663 _bytes('<a><c></c></a>'), 1664 a)16651667 Element = self.etree.Element 1668 SubElement = self.etree.SubElement 1669 1670 a = Element('{http://test}a') 1671 b = SubElement(a, '{http://test}b') 1672 c = SubElement(a, '{http://test}c') 1673 1674 a.remove(b) 1675 self.assertXML( 1676 _bytes('<ns0:a xmlns:ns0="http://test"><ns0:c></ns0:c></ns0:a>'), 1677 a) 1678 self.assertXML( 1679 _bytes('<ns0:b xmlns:ns0="http://test"></ns0:b>'), 1680 b)16811683 Element = self.etree.Element 1684 SubElement = self.etree.SubElement 1685 1686 a = Element('a') 1687 b = SubElement(a, 'b') 1688 c = SubElement(a, 'c') 1689 d = Element('d') 1690 self.assertRaises( 1691 ValueError, a.remove, d)16921694 Element = self.etree.Element 1695 SubElement = self.etree.SubElement 1696 1697 a = Element('a') 1698 b = SubElement(a, 'b') 1699 b.tail = 'b2' 1700 a.remove(b) 1701 self.assertXML( 1702 _bytes('<a></a>'), 1703 a) 1704 self.assertEqual('b2', b.tail)17051707 Element = self.etree.Element 1708 SubElement = self.etree.SubElement 1709 1710 a = Element('a') 1711 b = SubElement(a, 'b') 1712 c = SubElement(a, 'c') 1713 d = SubElement(b, 'd') 1714 e = SubElement(c, 'e') 1715 self.assertXML( 1716 _bytes('<a><b><d></d></b><c><e></e></c></a>'), 1717 a) 1718 self.assertEqual( 1719 [b, c], 1720 a.getchildren()) 1721 self.assertEqual( 1722 [d], 1723 b.getchildren()) 1724 self.assertEqual( 1725 [], 1726 d.getchildren())17271729 Element = self.etree.Element 1730 1731 a = Element('a') 1732 b = a.makeelement('c', {'hoi':'dag'}) 1733 self.assertXML( 1734 _bytes('<c hoi="dag"></c>'), 1735 b)1736 1737 required_versions_ET['test_iter'] = (1,3)1739 Element = self.etree.Element 1740 SubElement = self.etree.SubElement 1741 1742 a = Element('a') 1743 b = SubElement(a, 'b') 1744 c = SubElement(a, 'c') 1745 d = SubElement(b, 'd') 1746 e = SubElement(c, 'e') 1747 1748 self.assertEqual( 1749 [a, b, d, c, e], 1750 list(a.iter())) 1751 self.assertEqual( 1752 [d], 1753 list(d.iter()))17541756 Element = self.etree.Element 1757 SubElement = self.etree.SubElement 1758 1759 a = Element('a') 1760 b = SubElement(a, 'b') 1761 c = SubElement(a, 'c') 1762 d = SubElement(b, 'd') 1763 e = SubElement(c, 'e') 1764 1765 self.assertEqual( 1766 [a, b, d, c, e], 1767 list(a.getiterator())) 1768 self.assertEqual( 1769 [d], 1770 list(d.getiterator()))17711773 Element = self.etree.Element 1774 SubElement = self.etree.SubElement 1775 1776 a = Element('a') 1777 b = SubElement(a, 'b') 1778 c = SubElement(a, 'c') 1779 d = SubElement(b, 'd') 1780 e = SubElement(c, 'e') 1781 1782 self.assertEqual( 1783 [], 1784 list(a.getiterator('none'))) 1785 self.assertEqual( 1786 [], 1787 list(e.getiterator('none'))) 1788 self.assertEqual( 1789 [e], 1790 list(e.getiterator()))17911793 Element = self.etree.Element 1794 SubElement = self.etree.SubElement 1795 1796 a = Element('a') 1797 b = SubElement(a, 'b') 1798 c = SubElement(a, 'c') 1799 d = SubElement(b, 'd') 1800 e = SubElement(c, 'e') 1801 1802 self.assertEqual( 1803 [a], 1804 list(a.getiterator('a'))) 1805 a2 = SubElement(e, 'a') 1806 self.assertEqual( 1807 [a, a2], 1808 list(a.getiterator('a'))) 1809 self.assertEqual( 1810 [a2], 1811 list(c.getiterator('a')))18121814 Element = self.etree.Element 1815 SubElement = self.etree.SubElement 1816 1817 a = Element('a') 1818 b = SubElement(a, 'b') 1819 c = SubElement(a, 'c') 1820 d = SubElement(b, 'd') 1821 e = SubElement(c, 'e') 1822 1823 self.assertEqual( 1824 [a, b, d, c, e], 1825 list(a.getiterator('*')))18261828 Element = self.etree.Element 1829 Comment = self.etree.Comment 1830 SubElement = self.etree.SubElement 1831 1832 a = Element('a') 1833 b = SubElement(a, 'b') 1834 comment_b = Comment("TEST-b") 1835 b.append(comment_b) 1836 1837 self.assertEqual( 1838 [comment_b], 1839 list(a.getiterator(Comment))) 1840 1841 comment_a = Comment("TEST-a") 1842 a.append(comment_a) 1843 1844 self.assertEqual( 1845 [comment_b, comment_a], 1846 list(a.getiterator(Comment))) 1847 1848 self.assertEqual( 1849 [comment_b], 1850 list(b.getiterator(Comment)))18511853 Element = self.etree.Element 1854 PI = self.etree.ProcessingInstruction 1855 SubElement = self.etree.SubElement 1856 1857 a = Element('a') 1858 b = SubElement(a, 'b') 1859 pi_b = PI("TEST-b") 1860 b.append(pi_b) 1861 1862 self.assertEqual( 1863 [pi_b], 1864 list(a.getiterator(PI))) 1865 1866 pi_a = PI("TEST-a") 1867 a.append(pi_a) 1868 1869 self.assertEqual( 1870 [pi_b, pi_a], 1871 list(a.getiterator(PI))) 1872 1873 self.assertEqual( 1874 [pi_b], 1875 list(b.getiterator(PI)))18761878 Element = self.etree.Element 1879 SubElement = self.etree.SubElement 1880 1881 a = Element('a') 1882 a.text = 'a' 1883 b = SubElement(a, 'b') 1884 b.text = 'b' 1885 b.tail = 'b1' 1886 c = SubElement(a, 'c') 1887 c.text = 'c' 1888 c.tail = 'c1' 1889 d = SubElement(b, 'd') 1890 c.text = 'd' 1891 c.tail = 'd1' 1892 e = SubElement(c, 'e') 1893 e.text = 'e' 1894 e.tail = 'e1' 1895 1896 self.assertEqual( 1897 [a, b, d, c, e], 1898 list(a.getiterator()))1899 #self.assertEqual( 1900 # [d], 1901 # list(d.getiterator())) 19021904 Element = self.etree.Element 1905 SubElement = self.etree.SubElement 1906 1907 a = Element('a') 1908 a.text = 'a' 1909 b = SubElement(a, 'b') 1910 b.text = 'b' 1911 b.tail = 'b1' 1912 c = SubElement(a, 'c') 1913 c.text = 'c' 1914 c.tail = 'c1' 1915 d = SubElement(b, 'd') 1916 c.text = 'd' 1917 c.tail = 'd1' 1918 e = SubElement(c, 'e') 1919 e.text = 'e' 1920 e.tail = 'e1' 1921 1922 self.assertEqual( 1923 [a], 1924 list(a.getiterator('a'))) 1925 a2 = SubElement(e, 'a') 1926 self.assertEqual( 1927 [a, a2], 1928 list(a.getiterator('a'))) 1929 self.assertEqual( 1930 [a2], 1931 list(e.getiterator('a')))19321934 Element = self.etree.Element 1935 SubElement = self.etree.SubElement 1936 1937 a = Element('a') 1938 b = SubElement(a, 'b') 1939 c = SubElement(a, 'c') 1940 d = SubElement(a, 'd') 1941 1942 self.assertEqual( 1943 [b, c], 1944 a[0:2]) 1945 self.assertEqual( 1946 [b, c, d], 1947 a[:]) 1948 self.assertEqual( 1949 [b, c, d], 1950 a[:10]) 1951 self.assertEqual( 1952 [b], 1953 a[0:1]) 1954 self.assertEqual( 1955 [], 1956 a[10:12])19571959 Element = self.etree.Element 1960 SubElement = self.etree.SubElement 1961 1962 a = Element('a') 1963 b = SubElement(a, 'b') 1964 c = SubElement(a, 'c') 1965 d = SubElement(a, 'd') 1966 1967 self.assertEqual( 1968 [d], 1969 a[-1:]) 1970 self.assertEqual( 1971 [c, d], 1972 a[-2:]) 1973 self.assertEqual( 1974 [c], 1975 a[-2:-1]) 1976 self.assertEqual( 1977 [b, c], 1978 a[-3:-1]) 1979 self.assertEqual( 1980 [b, c], 1981 a[-3:2])19821984 Element = self.etree.Element 1985 SubElement = self.etree.SubElement 1986 1987 a = Element('a') 1988 b = SubElement(a, 'b') 1989 c = SubElement(a, 'c') 1990 d = SubElement(a, 'd') 1991 e = SubElement(a, 'e') 1992 1993 self.assertEqual( 1994 [e,d,c,b], 1995 a[::-1]) 1996 self.assertEqual( 1997 [b,d], 1998 a[::2]) 1999 self.assertEqual( 2000 [e,c], 2001 a[::-2]) 2002 self.assertEqual( 2003 [d,c], 2004 a[-2:0:-1]) 2005 self.assertEqual( 2006 [e], 2007 a[:1:-2])20082010 ElementTree = self.etree.ElementTree 2011 2012 f = BytesIO('<a><b>B</b>B1<c>C</c>C1</a>') 2013 doc = ElementTree(file=f) 2014 a = doc.getroot() 2015 b = a[0] 2016 c = a[1] 2017 self.assertEqual( 2018 [b, c], 2019 a[:]) 2020 self.assertEqual( 2021 [b], 2022 a[0:1]) 2023 self.assertEqual( 2024 [c], 2025 a[1:])20262028 Element = self.etree.Element 2029 Comment = self.etree.Comment 2030 SubElement = self.etree.SubElement 2031 2032 a = Element('a') 2033 b = SubElement(a, 'b') 2034 foo = Comment('foo') 2035 a.append(foo) 2036 c = SubElement(a, 'c') 2037 self.assertEqual( 2038 [b, foo, c], 2039 a[:]) 2040 self.assertEqual( 2041 foo, 2042 a[1]) 2043 a[1] = new = Element('new') 2044 self.assertEqual( 2045 new, 2046 a[1]) 2047 self.assertXML( 2048 _bytes('<a><b></b><new></new><c></c></a>'), 2049 a)20502052 Element = self.etree.Element 2053 SubElement = self.etree.SubElement 2054 2055 a = Element('a') 2056 b = SubElement(a, 'b') 2057 c = SubElement(a, 'c') 2058 d = SubElement(a, 'd') 2059 e = SubElement(a, 'e') 2060 2061 del a[1:3] 2062 self.assertEqual( 2063 [b, e], 2064 list(a))20652067 Element = self.etree.Element 2068 SubElement = self.etree.SubElement 2069 2070 a = Element('a') 2071 b = SubElement(a, 'b') 2072 c = SubElement(a, 'c') 2073 d = SubElement(a, 'd') 2074 e = SubElement(a, 'e') 2075 2076 del a[1:-1] 2077 self.assertEqual( 2078 [b, e], 2079 list(a))20802082 Element = self.etree.Element 2083 SubElement = self.etree.SubElement 2084 2085 a = Element('a') 2086 b = SubElement(a, 'b') 2087 c = SubElement(a, 'c') 2088 d = SubElement(a, 'd') 2089 e = SubElement(a, 'e') 2090 2091 del a[-3:-1] 2092 self.assertEqual( 2093 [b, e], 2094 list(a))20952097 Element = self.etree.Element 2098 SubElement = self.etree.SubElement 2099 2100 a = Element('a') 2101 b = SubElement(a, 'b') 2102 c = SubElement(a, 'c') 2103 d = SubElement(a, 'd') 2104 e = SubElement(a, 'e') 2105 2106 del a[1::2] 2107 self.assertEqual( 2108 [b, d], 2109 list(a))21102112 Element = self.etree.Element 2113 SubElement = self.etree.SubElement 2114 2115 a = Element('a') 2116 b = SubElement(a, 'b') 2117 c = SubElement(a, 'c') 2118 d = SubElement(a, 'd') 2119 e = SubElement(a, 'e') 2120 2121 del a[::-1] 2122 self.assertEqual( 2123 [], 2124 list(a))21252127 Element = self.etree.Element 2128 SubElement = self.etree.SubElement 2129 2130 a = Element('a') 2131 b = SubElement(a, 'b') 2132 c = SubElement(a, 'c') 2133 d = SubElement(a, 'd') 2134 e = SubElement(a, 'e') 2135 2136 del a[::-2] 2137 self.assertEqual( 2138 [b, d], 2139 list(a))21402142 ElementTree = self.etree.ElementTree 2143 f = BytesIO('<a><b></b>B2<c></c>C2<d></d>D2<e></e>E2</a>') 2144 doc = ElementTree(file=f) 2145 a = doc.getroot() 2146 del a[1:3] 2147 self.assertXML( 2148 _bytes('<a><b></b>B2<e></e>E2</a>'), 2149 a)21502152 XML = self.etree.XML 2153 a = XML(_bytes('<a><b></b>B2<c></c>C2</a>')) 2154 b, c = a 2155 2156 del a[:] 2157 2158 self.assertEqual("B2", b.tail) 2159 self.assertEqual("C2", c.tail)21602162 # this could trigger a crash 2163 Element = self.etree.Element 2164 SubElement = self.etree.SubElement 2165 a = Element('a') 2166 b = SubElement(a, 'b') 2167 c = SubElement(b, 'c') 2168 del b # no more reference to b 2169 del a[:] 2170 self.assertEqual('c', c.tag)21712173 Element = self.etree.Element 2174 SubElement = self.etree.SubElement 2175 2176 a = Element('a') 2177 b = SubElement(a, 'b') 2178 c = SubElement(a, 'c') 2179 d = SubElement(a, 'd') 2180 2181 e = Element('e') 2182 f = Element('f') 2183 g = Element('g') 2184 2185 s = [e, f, g] 2186 a[1:2] = s 2187 self.assertEqual( 2188 [b, e, f, g, d], 2189 list(a))21902192 Element = self.etree.Element 2193 SubElement = self.etree.SubElement 2194 2195 a = Element('a') 2196 b = SubElement(a, 'b') 2197 c = SubElement(a, 'c') 2198 2199 e = Element('e') 2200 f = Element('f') 2201 g = Element('g') 2202 2203 s = [e, f, g] 2204 a[:] = s 2205 self.assertEqual( 2206 [e, f, g], 2207 list(a))22082210 Element = self.etree.Element 2211 SubElement = self.etree.SubElement 2212 2213 a = Element('a') 2214 2215 e = Element('e') 2216 f = Element('f') 2217 g = Element('g') 2218 2219 s = [e, f, g] 2220 a[:] = s 2221 self.assertEqual( 2222 [e, f, g], 2223 list(a))22242226 Element = self.etree.Element 2227 SubElement = self.etree.SubElement 2228 2229 a = Element('a') 2230 b = SubElement(a, 'b') 2231 c = SubElement(a, 'c') 2232 d = SubElement(a, 'd') 2233 2234 s = [b, c, d] 2235 a[:] = s 2236 self.assertEqual( 2237 [b, c, d], 2238 list(a))22392241 Element = self.etree.Element 2242 SubElement = self.etree.SubElement 2243 2244 a = Element('a') 2245 b = SubElement(a, 'b') 2246 c = SubElement(a, 'c') 2247 d = SubElement(a, 'd') 2248 2249 s = [d, c, b] 2250 a[:] = s 2251 self.assertEqual( 2252 [d, c, b], 2253 list(a))22542256 Element = self.etree.Element 2257 SubElement = self.etree.SubElement 2258 2259 a = Element('{ns}a') 2260 b = SubElement(a, '{ns}b', {'{ns1}a1': 'test'}) 2261 c = SubElement(a, '{ns}c', {'{ns2}a2': 'test'}) 2262 d = SubElement(a, '{ns}d', {'{ns3}a3': 'test'}) 2263 2264 s = [d, c, b] 2265 a[:] = s 2266 self.assertEqual( 2267 [d, c, b], 2268 list(a)) 2269 self.assertEqual( 2270 ['{ns}d', '{ns}c', '{ns}b'], 2271 [ child.tag for child in a ]) 2272 2273 self.assertEqual( 2274 [['{ns3}a3'], ['{ns2}a2'], ['{ns1}a1']], 2275 [ list(child.attrib.keys()) for child in a ])22762278 Element = self.etree.Element 2279 SubElement = self.etree.SubElement 2280 2281 a = Element('{ns}a') 2282 b = SubElement(a, '{ns1}b', {'{ns}a1': 'test'}) 2283 c = SubElement(a, '{ns2}c', {'{ns}a2': 'test'}) 2284 d = SubElement(a, '{ns3}d', {'{ns}a3': 'test'}) 2285 2286 s = [d, c, b] 2287 a[:] = s 2288 self.assertEqual( 2289 [d, c, b], 2290 list(a)) 2291 self.assertEqual( 2292 ['{ns3}d', '{ns2}c', '{ns1}b'], 2293 [ child.tag for child in a ]) 2294 2295 self.assertEqual( 2296 [['{ns}a3'], ['{ns}a2'], ['{ns}a1']], 2297 [ list(child.attrib.keys()) for child in a ])22982300 Element = self.etree.Element 2301 SubElement = self.etree.SubElement 2302 2303 a = Element('a') 2304 b = SubElement(a, 'b') 2305 c = SubElement(a, 'c') 2306 2307 e = Element('e') 2308 f = Element('f') 2309 g = Element('g') 2310 h = Element('h') 2311 2312 s = [e, f] 2313 a[99:] = s 2314 self.assertEqual( 2315 [b, c, e, f], 2316 list(a)) 2317 2318 s = [g, h] 2319 a[:0] = s 2320 self.assertEqual( 2321 [g, h, b, c, e, f], 2322 list(a))23232325 Element = self.etree.Element 2326 SubElement = self.etree.SubElement 2327 2328 a = Element('a') 2329 b = SubElement(a, 'b') 2330 c = SubElement(a, 'c') 2331 d = SubElement(a, 'd') 2332 2333 e = Element('e') 2334 f = Element('f') 2335 g = Element('g') 2336 2337 s = [e, f, g] 2338 a[3:] = s 2339 self.assertEqual( 2340 [b, c, d, e, f, g], 2341 list(a))23422344 Element = self.etree.Element 2345 SubElement = self.etree.SubElement 2346 2347 a = Element('a') 2348 b = SubElement(a, 'b') 2349 c = SubElement(a, 'c') 2350 2351 e = Element('e') 2352 f = Element('f') 2353 2354 s = [e] 2355 a[0:1] = s 2356 self.assertEqual( 2357 [e, c], 2358 list(a)) 2359 2360 s = [f] 2361 a[1:2] = s 2362 self.assertEqual( 2363 [e, f], 2364 list(a))23652367 ElementTree = self.etree.ElementTree 2368 Element = self.etree.Element 2369 f = BytesIO('<a><b></b>B2<c></c>C2<d></d>D2<e></e>E2</a>') 2370 doc = ElementTree(file=f) 2371 a = doc.getroot() 2372 x = Element('x') 2373 y = Element('y') 2374 z = Element('z') 2375 x.tail = 'X2' 2376 y.tail = 'Y2' 2377 z.tail = 'Z2' 2378 a[1:3] = [x, y, z] 2379 self.assertXML( 2380 _bytes('<a><b></b>B2<x></x>X2<y></y>Y2<z></z>Z2<e></e>E2</a>'), 2381 a)23822384 Element = self.etree.Element 2385 SubElement = self.etree.SubElement 2386 2387 a = Element('a') 2388 b = SubElement(a, 'b') 2389 c = SubElement(a, 'c') 2390 d = SubElement(a, 'd') 2391 2392 x = Element('x') 2393 y = Element('y') 2394 2395 a[1:-1] = [x, y] 2396 self.assertEqual( 2397 [b, x, y, d], 2398 list(a))23992401 Element = self.etree.Element 2402 SubElement = self.etree.SubElement 2403 2404 a = Element('a') 2405 b = SubElement(a, 'b') 2406 c = SubElement(a, 'c') 2407 d = SubElement(a, 'd') 2408 2409 x = Element('x') 2410 y = Element('y') 2411 2412 a[1:-2] = [x, y] 2413 self.assertEqual( 2414 [b, x, y, c, d], 2415 list(a))24162418 Element = self.etree.Element 2419 2420 a = Element('a') 2421 2422 b = Element('b') 2423 c = Element('c') 2424 2425 a[:] = [b, c] 2426 self.assertEqual( 2427 [b, c], 2428 list(a))24292431 Element = self.etree.Element 2432 ElementTree = self.etree.ElementTree 2433 2434 a = Element('a') 2435 a.tail = 'A2' 2436 t = ElementTree(element=a) 2437 self.assertEqual('A2', 2438 a.tail)24392441 Element = self.etree.Element 2442 SubElement = self.etree.SubElement 2443 ElementTree = self.etree.ElementTree 2444 2445 a = Element('a') 2446 b = SubElement(a, 'b') 2447 c = SubElement(a, 'c') 2448 d = SubElement(b, 'd') 2449 e = SubElement(c, 'e') 2450 t = ElementTree(element=a) 2451 2452 self.assertEqual( 2453 [a, b, d, c, e], 2454 list(t.getiterator()))24552457 Element = self.etree.Element 2458 SubElement = self.etree.SubElement 2459 ElementTree = self.etree.ElementTree 2460 a = Element('a') 2461 b = SubElement(a, 'b') 2462 c = SubElement(a, 'c') 2463 d = SubElement(b, 'd') 2464 e = SubElement(c, 'e') 2465 t = ElementTree(element=a) 2466 2467 self.assertEqual( 2468 [a], 2469 list(t.getiterator('a'))) 2470 a2 = SubElement(e, 'a') 2471 self.assertEqual( 2472 [a, a2], 2473 list(t.getiterator('a')))24742476 ElementTree = self.etree.ElementTree 2477 ns = 'http://xml.infrae.com/1' 2478 f = BytesIO('<x:a xmlns:x="%s"><x:b></x:b></x:a>' % ns) 2479 t = ElementTree(file=f) 2480 a = t.getroot() 2481 self.assertEqual('{%s}a' % ns, 2482 a.tag) 2483 self.assertEqual('{%s}b' % ns, 2484 a[0].tag)24852487 ElementTree = self.etree.ElementTree 2488 ns = 'http://xml.infrae.com/1' 2489 ns2 = 'http://xml.infrae.com/2' 2490 f = BytesIO('<x:a xmlns:x="%s" xmlns:y="%s"><x:b></x:b><y:b></y:b></x:a>' % (ns, ns2)) 2491 t = ElementTree(file=f) 2492 a = t.getroot() 2493 self.assertEqual('{%s}a' % ns, 2494 a.tag) 2495 self.assertEqual('{%s}b' % ns, 2496 a[0].tag) 2497 self.assertEqual('{%s}b' % ns2, 2498 a[1].tag)24992501 Element = self.etree.Element 2502 SubElement = self.etree.SubElement 2503 ns = 'http://xml.infrae.com/1' 2504 ns2 = 'http://xml.infrae.com/2' 2505 a = Element('{%s}a' % ns) 2506 b = SubElement(a, '{%s}b' % ns2) 2507 c = SubElement(a, '{%s}c' % ns) 2508 self.assertEqual('{%s}a' % ns, 2509 a.tag) 2510 self.assertEqual('{%s}b' % ns2, 2511 b.tag) 2512 self.assertEqual('{%s}c' % ns, 2513 c.tag) 2514 self.assertEqual('{%s}a' % ns, 2515 a.tag) 2516 self.assertEqual('{%s}b' % ns2, 2517 b.tag) 2518 self.assertEqual('{%s}c' % ns, 2519 c.tag)25202522 Element = self.etree.Element 2523 SubElement = self.etree.SubElement 2524 ElementTree = self.etree.ElementTree 2525 2526 ns = 'http://xml.infrae.com/1' 2527 ns2 = 'http://xml.infrae.com/2' 2528 f = BytesIO('<a xmlns="%s" xmlns:x="%s"><x:b></x:b><b></b></a>' % (ns, ns2)) 2529 t = ElementTree(file=f) 2530 2531 a = t.getroot() 2532 self.assertEqual('{%s}a' % ns, 2533 a.tag) 2534 self.assertEqual('{%s}b' % ns2, 2535 a[0].tag) 2536 self.assertEqual('{%s}b' % ns, 2537 a[1].tag)25382540 Element = self.etree.Element 2541 ns = 'http://xml.infrae.com/1' 2542 ns2 = 'http://xml.infrae.com/2' 2543 a = Element('a') 2544 a.set('{%s}foo' % ns, 'Foo') 2545 a.set('{%s}bar' % ns2, 'Bar') 2546 self.assertEqual( 2547 'Foo', 2548 a.get('{%s}foo' % ns)) 2549 self.assertEqual( 2550 'Bar', 2551 a.get('{%s}bar' % ns2)) 2552 try: 2553 self.assertXML( 2554 _bytes('<a xmlns:ns0="%s" xmlns:ns1="%s" ns0:foo="Foo" ns1:bar="Bar"></a>' % (ns, ns2)), 2555 a) 2556 except AssertionError: 2557 self.assertXML( 2558 _bytes('<a xmlns:ns0="%s" xmlns:ns1="%s" ns1:foo="Foo" ns0:bar="Bar"></a>' % (ns2, ns)), 2559 a)25602562 Element = self.etree.Element 2563 one = self.etree.fromstring( 2564 _bytes('<foo><bar xmlns:ns="http://a.b.c"><ns:baz/></bar></foo>')) 2565 baz = one[0][0] 2566 2567 two = Element('root') 2568 two.append(baz) 2569 # removing the originating document could cause a crash/error before 2570 # as namespace is not moved along with it 2571 del one, baz 2572 self.assertEqual('{http://a.b.c}baz', two[0].tag)25732575 tostring = self.etree.tostring 2576 root = self.etree.XML( 2577 _bytes('<foo><bar xmlns:ns="http://a.b.c"><ns:baz/></bar></foo>')) 2578 baz = root[0][0] 2579 2580 nsdecl = re.findall(_bytes("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']"), 2581 tostring(baz)) 2582 self.assertEqual([_bytes("http://a.b.c")], nsdecl)25832585 tostring = self.etree.tostring 2586 root = self.etree.XML( 2587 _bytes('<foo><bar xmlns="http://a.b.c"><baz/></bar></foo>')) 2588 baz = root[0][0] 2589 2590 nsdecl = re.findall(_bytes("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']"), 2591 tostring(baz)) 2592 self.assertEqual([_bytes("http://a.b.c")], nsdecl)25932595 tostring = self.etree.tostring 2596 root = self.etree.XML( 2597 _bytes('<foo xmlns:ns="http://a.b.c"><bar><ns:baz/></bar></foo>')) 2598 baz = root[0][0] 2599 2600 nsdecl = re.findall(_bytes("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']"), 2601 tostring(baz)) 2602 2603 self.assertEqual([_bytes("http://a.b.c")], nsdecl)26042606 Element = self.etree.Element 2607 SubElement = self.etree.SubElement 2608 2609 root = Element("foo") 2610 bar = SubElement(root, "{http://a.b.c}bar") 2611 baz = SubElement(bar, "{http://a.b.c}baz") 2612 2613 nsdecl = re.findall(_bytes("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']"), 2614 self.etree.tostring(baz)) 2615 2616 self.assertEqual([_bytes("http://a.b.c")], nsdecl)26172619 Element = self.etree.Element 2620 2621 root = Element('element') 2622 2623 subelement = Element('subelement', 2624 {"{http://www.w3.org/XML/1998/namespace}id": "foo"}) 2625 self.assertEqual(1, len(subelement.attrib)) 2626 self.assertEqual( 2627 "foo", 2628 subelement.get("{http://www.w3.org/XML/1998/namespace}id")) 2629 2630 root.append(subelement) 2631 self.assertEqual(1, len(subelement.attrib)) 2632 self.assertEqual( 2633 list({"{http://www.w3.org/XML/1998/namespace}id" : "foo"}.items()), 2634 list(subelement.attrib.items())) 2635 self.assertEqual( 2636 "foo", 2637 subelement.get("{http://www.w3.org/XML/1998/namespace}id"))26382640 parse = self.etree.parse 2641 tostring = self.etree.tostring 2642 2643 ns_href = "http://a.b.c" 2644 one = parse( 2645 BytesIO('<foo><bar xmlns:ns="%s"><ns:baz/></bar></foo>' % ns_href)) 2646 baz = one.getroot()[0][0] 2647 2648 parsed = parse(BytesIO( tostring(baz) )).getroot() 2649 self.assertEqual('{%s}baz' % ns_href, parsed.tag)26502652 fromstring = self.etree.fromstring 2653 tostring = self.etree.tostring 2654 2655 ns_href = "http://a.b.c" 2656 xml = _bytes('<root xmlns="%s" xmlns:x="%s"><el x:a="test" /></root>' % ( 2657 ns_href,ns_href)) 2658 root = fromstring(xml) 2659 self.assertEqual('test', root[0].get('{%s}a' % ns_href)) 2660 2661 xml2 = tostring(root) 2662 self.assertTrue(_bytes(':a=') in xml2, xml2) 2663 2664 root2 = fromstring(xml2) 2665 self.assertEqual('test', root2[0].get('{%s}a' % ns_href))26662668 fromstring = self.etree.fromstring 2669 tostring = self.etree.tostring 2670 2671 ns_href = "http://a.b.c" 2672 xml = _bytes('<root xmlns="%s" xmlns:x="%s"><el x:a="test" /></root>' % ( 2673 ns_href,ns_href)) 2674 root = fromstring(xml) 2675 self.assertEqual('test', root[0].get('{%s}a' % ns_href)) 2676 2677 root[0].set('{%s}a' % ns_href, 'TEST') 2678 2679 xml2 = tostring(root) 2680 self.assertTrue(_bytes(':a=') in xml2, xml2) 2681 2682 root2 = fromstring(xml2) 2683 self.assertEqual('TEST', root2[0].get('{%s}a' % ns_href))2684 2685 required_versions_ET['test_register_namespace'] = (1,3)2687 # ET 1.3+ 2688 Element = self.etree.Element 2689 prefix = 'TESTPREFIX' 2690 namespace = 'http://seriously.unknown/namespace/URI' 2691 2692 el = Element('{%s}test' % namespace) 2693 self.assertEqual(_bytes('<ns0:test xmlns:ns0="%s"></ns0:test>' % namespace), 2694 self._writeElement(el)) 2695 2696 self.etree.register_namespace(prefix, namespace) 2697 el = Element('{%s}test' % namespace) 2698 self.assertEqual(_bytes('<%s:test xmlns:%s="%s"></%s:test>' % ( 2699 prefix, prefix, namespace, prefix)), 2700 self._writeElement(el)) 2701 2702 self.assertRaises(ValueError, self.etree.register_namespace, 'ns25', namespace)27032705 tostring = self.etree.tostring 2706 Element = self.etree.Element 2707 SubElement = self.etree.SubElement 2708 2709 a = Element('a') 2710 b = SubElement(a, 'b') 2711 c = SubElement(a, 'c') 2712 2713 self.assertEqual(_bytes('<a><b></b><c></c></a>'), 2714 canonicalize(tostring(a)))27152717 tostring = self.etree.tostring 2718 Element = self.etree.Element 2719 SubElement = self.etree.SubElement 2720 2721 a = Element('a') 2722 b = SubElement(a, 'b') 2723 c = SubElement(a, 'c') 2724 d = SubElement(c, 'd') 2725 self.assertEqual(_bytes('<b></b>'), 2726 canonicalize(tostring(b))) 2727 self.assertEqual(_bytes('<c><d></d></c>'), 2728 canonicalize(tostring(c)))27292731 tostring = self.etree.tostring 2732 Element = self.etree.Element 2733 SubElement = self.etree.SubElement 2734 2735 a = Element('a') 2736 b = SubElement(a, 'b') 2737 c = SubElement(a, 'c') 2738 d = SubElement(c, 'd') 2739 b.tail = 'Foo' 2740 2741 self.assertTrue(tostring(b) == _bytes('<b/>Foo') or 2742 tostring(b) == _bytes('<b />Foo'))2743 2744 required_versions_ET['test_tostring_method_html'] = (1,3)2746 tostring = self.etree.tostring 2747 Element = self.etree.Element 2748 SubElement = self.etree.SubElement 2749 2750 html = Element('html') 2751 body = SubElement(html, 'body') 2752 p = SubElement(body, 'p') 2753 p.text = "html" 2754 SubElement(p, 'br').tail = "test" 2755 2756 self.assertEqual(_bytes('<html><body><p>html<br>test</p></body></html>'), 2757 tostring(html, method="html"))2758 2759 required_versions_ET['test_tostring_method_text'] = (1,3)2761 tostring = self.etree.tostring 2762 Element = self.etree.Element 2763 SubElement = self.etree.SubElement 2764 2765 a = Element('a') 2766 a.text = "A" 2767 a.tail = "tail" 2768 b = SubElement(a, 'b') 2769 b.text = "B" 2770 b.tail = "TAIL" 2771 c = SubElement(a, 'c') 2772 c.text = "C" 2773 2774 self.assertEqual(_bytes('ABTAILCtail'), 2775 tostring(a, method="text"))27762778 iterparse = self.etree.iterparse 2779 f = BytesIO('<a><b></b><c/></a>') 2780 2781 iterator = iterparse(f) 2782 self.assertEqual(None, 2783 iterator.root) 2784 events = list(iterator) 2785 root = iterator.root 2786 self.assertEqual( 2787 [('end', root[0]), ('end', root[1]), ('end', root)], 2788 events)27892791 iterparse = self.etree.iterparse 2792 iterator = iterparse(fileInTestDir("test.xml")) 2793 self.assertEqual(None, 2794 iterator.root) 2795 events = list(iterator) 2796 root = iterator.root 2797 self.assertEqual( 2798 [('end', root[0]), ('end', root)], 2799 events)28002802 iterparse = self.etree.iterparse 2803 f = BytesIO('<a><b></b><c/></a>') 2804 2805 iterator = iterparse(f, events=('start',)) 2806 events = list(iterator) 2807 root = iterator.root 2808 self.assertEqual( 2809 [('start', root), ('start', root[0]), ('start', root[1])], 2810 events)28112813 iterparse = self.etree.iterparse 2814 f = BytesIO('<a><b></b><c/></a>') 2815 2816 iterator = iterparse(f, events=('start','end')) 2817 events = list(iterator) 2818 root = iterator.root 2819 self.assertEqual( 2820 [('start', root), ('start', root[0]), ('end', root[0]), 2821 ('start', root[1]), ('end', root[1]), ('end', root)], 2822 events)28232825 iterparse = self.etree.iterparse 2826 f = BytesIO('<a><b></b><c/></a>') 2827 2828 iterator = iterparse(f) 2829 for event, elem in iterator: 2830 elem.clear() 2831 2832 root = iterator.root 2833 self.assertEqual(0, 2834 len(root))28352837 iterparse = self.etree.iterparse 2838 CHILD_COUNT = 12345 2839 f = BytesIO('<a>%s</a>' % ('<b>test</b>'*CHILD_COUNT)) 2840 2841 i = 0 2842 for key in iterparse(f): 2843 event, element = key 2844 i += 1 2845 self.assertEqual(i, CHILD_COUNT + 1)28462848 iterparse = self.etree.iterparse 2849 f = BytesIO('<a xmlns="http://ns1/"><b><c xmlns="http://ns2/"/></b></a>') 2850 2851 attr_name = '{http://testns/}bla' 2852 events = [] 2853 iterator = iterparse(f, events=('start','end','start-ns','end-ns')) 2854 for event, elem in iterator: 2855 events.append(event) 2856 if event == 'start': 2857 if elem.tag != '{http://ns1/}a': 2858 elem.set(attr_name, 'value') 2859 2860 self.assertEqual( 2861 ['start-ns', 'start', 'start', 'start-ns', 'start', 2862 'end', 'end-ns', 'end', 'end', 'end-ns'], 2863 events) 2864 2865 root = iterator.root 2866 self.assertEqual( 2867 None, 2868 root.get(attr_name)) 2869 self.assertEqual( 2870 'value', 2871 root[0].get(attr_name))28722874 iterparse = self.etree.iterparse 2875 f = BytesIO('<a><b><d/></b><c/></a>') 2876 2877 counts = [] 2878 for event, elem in iterparse(f): 2879 counts.append(len(list(elem.getiterator()))) 2880 self.assertEqual( 2881 [1,2,1,4], 2882 counts)28832885 iterparse = self.etree.iterparse 2886 f = BytesIO('<a><b><d/></b><c/></a>') 2887 2888 for event, node in etree.iterparse(f): pass 2889 2890 root = etree.Element('new_root', {}) 2891 root[:] = node[:] 2892 2893 self.assertEqual( 2894 ['b', 'c'], 2895 [ el.tag for el in root ])28962898 tostring = self.etree.tostring 2899 f = BytesIO('<root><![CDATA[test]]></root>') 2900 context = self.etree.iterparse(f) 2901 content = [ el.text for event,el in context ] 2902 2903 self.assertEqual(['test'], content) 2904 self.assertEqual(_bytes('<root>test</root>'), 2905 tostring(context.root))29062908 parse = self.etree.parse 2909 # from file 2910 tree = parse(fileInTestDir('test.xml')) 2911 self.assertXML( 2912 _bytes('<a><b></b></a>'), 2913 tree.getroot())2914 2918 2922 2923 required_versions_ET['test_parse_error'] = (1,3)2925 # ET < 1.3 raises ExpatError 2926 parse = self.etree.parse 2927 f = BytesIO('<a><b></c></b></a>') 2928 self.assertRaises(SyntaxError, parse, f) 2929 f.close()2930 2931 required_versions_ET['test_parse_error_from_file'] = (1,3)2933 parse = self.etree.parse 2934 # from file 2935 f = open(fileInTestDir('test_broken.xml'), 'rb') 2936 self.assertRaises(SyntaxError, parse, f) 2937 f.close()29382940 parse = self.etree.parse 2941 # from file object 2942 f = open(fileInTestDir('test.xml'), 'rb') 2943 tree = parse(f) 2944 f.close() 2945 self.assertXML( 2946 _bytes('<a><b></b></a>'), 2947 tree.getroot())29482950 parse = self.etree.parse 2951 f = BytesIO('<a><b></b></a>') 2952 tree = parse(f) 2953 f.close() 2954 self.assertXML( 2955 _bytes('<a><b></b></a>'), 2956 tree.getroot() 2957 )29582960 tostring = self.etree.tostring 2961 root = self.etree.XML(_bytes('<root><![CDATA[test]]></root>')) 2962 2963 self.assertEqual('test', root.text) 2964 self.assertEqual(_bytes('<root>test</root>'), 2965 tostring(root))29662968 # this can fail in libxml2 <= 2.6.22 2969 parse = self.etree.parse 2970 tree = parse(BytesIO('<?xml version="1.0" encoding="ascii"?><html/>')) 2971 self.assertXML(_bytes('<html></html>'), 2972 tree.getroot())29732975 Element = self.etree.Element 2976 2977 a = Element('a') 2978 a.text = _str('Søk på nettet') 2979 self.assertXML( 2980 _str('<a>Søk på nettet</a>').encode('UTF-8'), 2981 a, 'utf-8')29822984 ElementTree = self.etree.ElementTree 2985 Element = self.etree.Element 2986 2987 a = Element('a') 2988 a.text = _str('Søk på nettet') 2989 2990 f = BytesIO() 2991 tree = ElementTree(element=a) 2992 tree.write(f, encoding='utf-8') 2993 self.assertEqual(_str('<a>Søk på nettet</a>').encode('UTF-8'), 2994 f.getvalue().replace(_bytes('\n'),_bytes('')))29952997 parse = self.etree.parse 2998 # from file 2999 tree = parse(fileInTestDir('test-string.xml')) 3000 self.assertXML( 3001 _str('<a>Søk på nettet</a>').encode('UTF-8'), 3002 tree.getroot(), 'UTF-8')30033005 parse = self.etree.parse 3006 # from file object 3007 f = open(fileInTestDir('test-string.xml'), 'rb') 3008 tree = parse(f) 3009 f.close() 3010 self.assertXML( 3011 _str('<a>Søk på nettet</a>').encode('UTF-8'), 3012 tree.getroot(), 'UTF-8')30133015 ElementTree = self.etree.ElementTree 3016 Element = self.etree.Element 3017 3018 a = Element('a') 3019 a.text = _str('Søk på nettet') 3020 3021 f = BytesIO() 3022 tree = ElementTree(element=a) 3023 tree.write(f, encoding='iso-8859-1') 3024 result = f.getvalue() 3025 declaration = _bytes("<?xml version=\'1.0\' encoding=\'iso-8859-1\'?>") 3026 self.assertEncodingDeclaration(result, _bytes('iso-8859-1')) 3027 result = result.split(_bytes('?>'), 1)[-1].replace(_bytes('\n'),_bytes('')) 3028 self.assertEqual(_str('<a>Søk på nettet</a>').encode('iso-8859-1'), 3029 result)3030 3031 required_versions_ET['test_parse_encoding_8bit_explicit'] = (1,3)3033 XMLParser = self.XMLParser 3034 3035 text = _str('Søk på nettet') 3036 xml_latin1 = (_str('<a>%s</a>') % text).encode('iso-8859-1') 3037 3038 self.assertRaises(self.etree.ParseError, 3039 self.etree.parse, 3040 BytesIO(xml_latin1)) 3041 3042 tree = self.etree.parse(BytesIO(xml_latin1), 3043 XMLParser(encoding="iso-8859-1")) 3044 a = tree.getroot() 3045 self.assertEqual(a.text, text)3046 3047 required_versions_ET['test_parse_encoding_8bit_override'] = (1,3)3049 XMLParser = self.XMLParser 3050 3051 text = _str('Søk på nettet') 3052 wrong_declaration = _str("<?xml version='1.0' encoding='UTF-8'?>") 3053 xml_latin1 = (_str('%s<a>%s</a>') % (wrong_declaration, text) 3054 ).encode('iso-8859-1') 3055 3056 self.assertRaises(self.etree.ParseError, 3057 self.etree.parse, 3058 BytesIO(xml_latin1)) 3059 3060 tree = self.etree.parse(BytesIO(xml_latin1), 3061 XMLParser(encoding="iso-8859-1")) 3062 a = tree.getroot() 3063 self.assertEqual(a.text, text)30643066 # raise error on wrong encoding declaration in unicode strings 3067 XML = self.etree.XML 3068 test_utf = (_str('<?xml version="1.0" encoding="iso-8859-1"?>') + 3069 _str('<a>Søk på nettet</a>')) 3070 self.assertRaises(SyntaxError, XML, test_utf)30713073 ElementTree = self.etree.ElementTree 3074 Element = self.etree.Element 3075 3076 a = Element('a') 3077 a.text = _str('Søk på nettet') 3078 3079 f = BytesIO() 3080 tree = ElementTree(element=a) 3081 tree.write(f) 3082 data = f.getvalue().replace(_bytes('\n'),_bytes('')) 3083 self.assertEqual( 3084 _str('<a>Søk på nettet</a>').encode('ASCII', 'xmlcharrefreplace'), 3085 data)30863088 Element = self.etree.Element 3089 tostring = self.etree.tostring 3090 3091 a = Element('a') 3092 a.text = _str('Søk på nettet') 3093 self.assertEqual(_str('<a>Søk på nettet</a>').encode('UTF-8'), 3094 tostring(a, encoding='utf-8'))30953097 Element = self.etree.Element 3098 tostring = self.etree.tostring 3099 3100 a = Element('a') 3101 a.text = _str('Søk på nettet') 3102 self.assertRaises(LookupError, tostring, a, 3103 encoding='Invalid Encoding')31043106 Element = self.etree.Element 3107 SubElement = self.etree.SubElement 3108 tostring = self.etree.tostring 3109 3110 a = Element('a') 3111 b = SubElement(a, 'b') 3112 b.text = _str('Søk på nettet') 3113 self.assertEqual(_str('<b>Søk på nettet</b>').encode('UTF-8'), 3114 tostring(b, encoding='utf-8'))31153117 Element = self.etree.Element 3118 SubElement = self.etree.SubElement 3119 tostring = self.etree.tostring 3120 3121 a = Element('a') 3122 b = SubElement(a, 'b') 3123 b.text = _str('Søk på nettet') 3124 b.tail = _str('Søk') 3125 self.assertEqual(_str('<b>Søk på nettet</b>Søk').encode('UTF-8'), 3126 tostring(b, encoding='utf-8'))31273129 Element = self.etree.Element 3130 SubElement = self.etree.SubElement 3131 tostring = self.etree.tostring 3132 3133 a = Element('a') 3134 a.text = _str('Søk på nettet') 3135 3136 expected = _bytes('<a>Søk på nettet</a>') 3137 self.assertEqual( 3138 expected, 3139 tostring(a))31403142 Element = self.etree.Element 3143 SubElement = self.etree.SubElement 3144 tostring = self.etree.tostring 3145 3146 a = Element('a') 3147 b = SubElement(a, 'b') 3148 b.text = _str('Søk på nettet') 3149 3150 expected = _bytes('<b>Søk på nettet</b>') 3151 self.assertEqual( 3152 expected, 3153 tostring(b))31543156 utext = _str('Søk på nettet') 3157 uxml = _str('<p>%s</p>') % utext 3158 prologue = _bytes('<?xml version="1.0" encoding="iso-8859-1" ?>') 3159 isoxml = prologue + uxml.encode('iso-8859-1') 3160 tree = self.etree.XML(isoxml) 3161 self.assertEqual(utext, tree.text)31623164 utext = _str('Søk på nettet') 3165 uxml = (_str('<?xml version="1.0" encoding="UTF-8"?>') + 3166 _str('<p>%s</p>') % utext) 3167 bom = _bytes('\\xEF\\xBB\\xBF').decode("unicode_escape").encode("latin1") 3168 xml = bom + uxml.encode("utf-8") 3169 tree = etree.XML(xml) 3170 self.assertEqual(utext, tree.text)31713173 utext = _str('Søk på nettet') 3174 uxml = _str('<p>%s</p>') % utext 3175 prologue = _bytes('<?xml version="1.0" encoding="iso-8859-1" ?>') 3176 isoxml = prologue + uxml.encode('iso-8859-1') 3177 el = self.etree.parse(BytesIO(isoxml)).getroot() 3178 self.assertEqual(utext, el.text)31793181 Element = self.etree.Element 3182 ElementTree = self.etree.ElementTree 3183 3184 a = Element('a') 3185 a.text = "Foo" 3186 atree = ElementTree(a) 3187 3188 btree = copy.deepcopy(atree) 3189 self.assertEqual("Foo", atree.getroot().text) 3190 self.assertEqual("Foo", btree.getroot().text) 3191 self.assertFalse(btree is atree) 3192 self.assertFalse(btree.getroot() is atree.getroot())31933195 Element = self.etree.Element 3196 3197 a = Element('a') 3198 a.text = 'Foo' 3199 3200 b = copy.deepcopy(a) 3201 self.assertEqual('Foo', b.text) 3202 3203 b.text = 'Bar' 3204 self.assertEqual('Bar', b.text) 3205 self.assertEqual('Foo', a.text) 3206 3207 del a 3208 self.assertEqual('Bar', b.text)32093211 Element = self.etree.Element 3212 3213 a = Element('a') 3214 a.tail = 'Foo' 3215 3216 b = copy.deepcopy(a) 3217 self.assertEqual('Foo', b.tail) 3218 3219 b.tail = 'Bar' 3220 self.assertEqual('Bar', b.tail) 3221 self.assertEqual('Foo', a.tail) 3222 3223 del a 3224 self.assertEqual('Bar', b.tail)32253227 Element = self.etree.Element 3228 SubElement = self.etree.SubElement 3229 3230 root = Element('root') 3231 a = SubElement(root, 'a') 3232 a.text = 'FooText' 3233 a.tail = 'FooTail' 3234 3235 b = copy.deepcopy(a) 3236 self.assertEqual('FooText', b.text) 3237 self.assertEqual('FooTail', b.tail) 3238 3239 b.text = 'BarText' 3240 b.tail = 'BarTail' 3241 self.assertEqual('BarTail', b.tail) 3242 self.assertEqual('FooTail', a.tail) 3243 self.assertEqual('BarText', b.text) 3244 self.assertEqual('FooText', a.text) 3245 3246 del a 3247 self.assertEqual('BarTail', b.tail) 3248 self.assertEqual('BarText', b.text)32493251 root = self.etree.XML(_bytes('''<doc xmlns="dns" xmlns:t="tns"> 3252 <parent><node t:foo="bar" /></parent> 3253 </doc>''')) 3254 self.assertEqual( 3255 root[0][0].get('{tns}foo'), 3256 copy.deepcopy(root[0])[0].get('{tns}foo') ) 3257 self.assertEqual( 3258 root[0][0].get('{tns}foo'), 3259 copy.deepcopy(root[0][0]).get('{tns}foo') )32603262 # previously caused a crash 3263 Element = self.etree.Element 3264 tostring = self.etree.tostring 3265 3266 a = Element('a') 3267 b = copy.deepcopy(a) 3268 a.append( Element('C') ) 3269 b.append( Element('X') ) 3270 3271 self.assertEqual(_bytes('<a><C/></a>'), 3272 tostring(a).replace(_bytes(' '), _bytes(''))) 3273 self.assertEqual(_bytes('<a><X/></a>'), 3274 tostring(b).replace(_bytes(' '), _bytes('')))32753277 # previously caused a crash 3278 # not supported by ET < 1.3! 3279 Comment = self.etree.Comment 3280 3281 a = Comment("ONE") 3282 b = copy.deepcopy(a) 3283 b.text = "ANOTHER" 3284 3285 self.assertEqual('ONE', a.text) 3286 self.assertEqual('ANOTHER', b.text)32873289 Element = self.etree.Element 3290 3291 a = Element('a') 3292 a.text = 'Foo' 3293 3294 b = copy.copy(a) 3295 self.assertEqual('Foo', b.text) 3296 3297 b.text = 'Bar' 3298 self.assertEqual('Bar', b.text) 3299 self.assertEqual('Foo', a.text)3300 # XXX ElementTree will share nodes, but lxml.etree won't.. 33013303 Element = self.etree.Element 3304 ElementTree = self.etree.ElementTree 3305 3306 a = Element('a') 3307 a.text = 'Foo' 3308 atree = ElementTree(a) 3309 3310 btree = copy.copy(atree) 3311 self.assertFalse(btree is atree) 3312 self.assertTrue(btree.getroot() is atree.getroot()) 3313 self.assertEqual('Foo', atree.getroot().text)33143316 # deprecated as of ET 1.3/lxml 2.0 3317 etree = self.etree 3318 e = etree.Element('foo') 3319 self.assertEqual(False, bool(e)) 3320 etree.SubElement(e, 'bar') 3321 self.assertEqual(True, bool(e)) 3322 e = etree.Element('foo') 3323 e.text = 'hey' 3324 self.assertEqual(False, bool(e)) 3325 e = etree.Element('foo') 3326 e.tail = 'bar' 3327 self.assertEqual(False, bool(e)) 3328 e = etree.Element('foo') 3329 e.set('bar', 'Bar') 3330 self.assertEqual(False, bool(e))33313333 etree = self.etree 3334 3335 a = etree.Element('a') 3336 b = etree.SubElement(a, 'b') 3337 3338 t = etree.ElementTree(a) 3339 self.assertEqual(self._rootstring(t), _bytes('<a><b/></a>')) 3340 3341 t1 = etree.ElementTree(a) 3342 self.assertEqual(self._rootstring(t1), _bytes('<a><b/></a>')) 3343 self.assertEqual(self._rootstring(t), _bytes('<a><b/></a>')) 3344 3345 t2 = etree.ElementTree(b) 3346 self.assertEqual(self._rootstring(t2), _bytes('<b/>')) 3347 self.assertEqual(self._rootstring(t1), _bytes('<a><b/></a>')) 3348 self.assertEqual(self._rootstring(t), _bytes('<a><b/></a>'))33493351 etree = self.etree 3352 qname = etree.QName('myns', 'a') 3353 a1 = etree.Element(qname) 3354 a2 = etree.SubElement(a1, qname) 3355 self.assertEqual(a1.tag, "{myns}a") 3356 self.assertEqual(a2.tag, "{myns}a")33573359 etree = self.etree 3360 qname1 = etree.QName('myns', 'a') 3361 qname2 = etree.QName('myns', 'a') 3362 self.assertEqual(qname1, "{myns}a") 3363 self.assertEqual("{myns}a", qname2) 3364 self.assertEqual(qname1, qname1) 3365 self.assertEqual(qname1, qname2)33663368 etree = self.etree 3369 qname = etree.QName('myns', 'a') 3370 3371 a = etree.Element(qname) 3372 a.set(qname, "value") 3373 3374 self.assertEqual(a.get(qname), "value") 3375 self.assertEqual(a.get("{myns}a"), "value")33763378 etree = self.etree 3379 qname = etree.QName('myns', 'a') 3380 3381 a = etree.Element(qname) 3382 a.attrib[qname] = "value" 3383 3384 self.assertEqual(a.attrib[qname], "value") 3385 self.assertEqual(a.attrib.get(qname), "value") 3386 3387 self.assertEqual(a.attrib["{myns}a"], "value") 3388 self.assertEqual(a.attrib.get("{myns}a"), "value")33893391 etree = self.etree 3392 qname = etree.QName('http://myns', 'a') 3393 a = etree.Element(qname) 3394 a.set(qname, qname) 3395 3396 self.assertXML( 3397 _bytes('<ns0:a xmlns:ns0="http://myns" ns0:a="ns0:a"></ns0:a>'), 3398 a)33993401 etree = self.etree 3402 qname = etree.QName('http://myns', 'a') 3403 a = etree.Element('a') 3404 a.set('a', qname) 3405 3406 self.assertXML( 3407 _bytes('<a xmlns:ns0="http://myns" a="ns0:a"></a>'), 3408 a)34093411 etree = self.etree 3412 qname = etree.QName('http://myns', 'a') 3413 a = etree.Element(qname) 3414 a.attrib[qname] = qname 3415 3416 self.assertXML( 3417 _bytes('<ns0:a xmlns:ns0="http://myns" ns0:a="ns0:a"></ns0:a>'), 3418 a)34193421 etree = self.etree 3422 parser = etree.XMLParser() 3423 if hasattr(parser, "version"): 3424 # ElementTree 1.3+, cET 3425 self.assertTrue(re.match("[^ ]+ [0-9.]+", parser.version))3426 3427 # feed parser interface 34283430 parser = self.XMLParser() 3431 3432 parser.feed(_bytes('<?xml version=')) 3433 parser.feed(_bytes('"1.0"?><ro')) 3434 parser.feed(_bytes('ot><')) 3435 parser.feed(_bytes('a test="works"/')) 3436 parser.feed(_bytes('></root')) 3437 parser.feed(_bytes('>')) 3438 3439 root = parser.close() 3440 3441 self.assertEqual(root.tag, "root") 3442 self.assertEqual(root[0].tag, "a") 3443 self.assertEqual(root[0].get("test"), "works")34443446 parser = self.XMLParser() 3447 3448 parser.feed(_str('<ro')) 3449 parser.feed(_str('ot><')) 3450 parser.feed(_str('a test="works"/')) 3451 parser.feed(_str('></root')) 3452 parser.feed(_str('>')) 3453 3454 root = parser.close() 3455 3456 self.assertEqual(root.tag, "root") 3457 self.assertEqual(root[0].tag, "a") 3458 self.assertEqual(root[0].get("test"), "works")3459 3460 required_versions_ET['test_feed_parser_error_close_empty'] = (1,3)3462 ParseError = self.etree.ParseError 3463 parser = self.XMLParser() 3464 self.assertRaises(ParseError, parser.close)3465 3466 required_versions_ET['test_feed_parser_error_close_incomplete'] = (1,3)3468 ParseError = self.etree.ParseError 3469 parser = self.XMLParser() 3470 3471 parser.feed('<?xml version=') 3472 parser.feed('"1.0"?><ro') 3473 3474 self.assertRaises(ParseError, parser.close)3475 3476 required_versions_ET['test_feed_parser_error_broken'] = (1,3)3478 ParseError = self.etree.ParseError 3479 parser = self.XMLParser() 3480 3481 parser.feed('<?xml version=') 3482 parser.feed('"1.0"?><ro') 3483 try: 3484 parser.feed('<><><><><><><') 3485 except ParseError: 3486 # can raise, but not required before close() 3487 pass 3488 3489 self.assertRaises(ParseError, parser.close)3490 3491 required_versions_ET['test_feed_parser_error_position'] = (1,3)3493 ParseError = self.etree.ParseError 3494 parser = self.XMLParser() 3495 try: 3496 parser.close() 3497 except ParseError: 3498 e = sys.exc_info()[1] 3499 self.assertNotEqual(None, e.code) 3500 self.assertNotEqual(0, e.code) 3501 self.assertTrue(isinstance(e.position, tuple)) 3502 self.assertTrue(e.position >= (0, 0))3503 3504 # parser target interface 3505 3506 required_versions_ET['test_parser_target_property'] = (1,3) 3510 3511 target = Target() 3512 parser = self.XMLParser(target=target) 3513 3514 self.assertEqual(target, parser.target) 35153517 assertEqual = self.assertEqual 3518 assertFalse = self.assertFalse 3519 3520 events = [] 3521 class Target(object): 3522 def start(self, tag, attrib): 3523 events.append("start") 3524 assertFalse(attrib) 3525 assertEqual("TAG", tag)3526 def end(self, tag): 3527 events.append("end") 3528 assertEqual("TAG", tag) 3529 def close(self): 3530 return "DONE" 3531 3532 parser = self.XMLParser(target=Target()) 3533 3534 parser.feed("<TAG/>") 3535 done = parser.close() 3536 3537 self.assertEqual("DONE", done) 3538 self.assertEqual(["start", "end"], events) 35393541 assertEqual = self.assertEqual 3542 3543 events = [] 3544 class Target(object): 3545 def start(self, tag, attrib): 3546 events.append("start") 3547 assertEqual("TAG", tag) 3548 raise ValueError("TEST")3549 def end(self, tag): 3550 events.append("end") 3551 assertEqual("TAG", tag) 3552 def close(self): 3553 return "DONE" 3554 3555 parser = self.XMLParser(target=Target()) 3556 3557 try: 3558 parser.feed("<TAG/>") 3559 except ValueError: 3560 self.assertTrue('TEST' in str(sys.exc_info()[1])) 3561 else: 3562 self.assertTrue(False) 3563 if 'lxml' in self.etree.__name__: 3564 self.assertEqual(["start"], events) 3565 else: 3566 # cElementTree calls end() as well 3567 self.assertTrue("start" in events) 35683570 assertEqual = self.assertEqual 3571 3572 events = [] 3573 class Target(object): 3574 def start(self, tag, attrib): 3575 events.append("start") 3576 assertEqual("TAG", tag)3577 def end(self, tag): 3578 events.append("end") 3579 assertEqual("TAG", tag) 3580 raise ValueError("TEST") 3581 def close(self): 3582 return "DONE" 3583 3584 parser = self.XMLParser(target=Target()) 3585 3586 try: 3587 parser.feed("<TAG/>") 3588 except ValueError: 3589 self.assertTrue('TEST' in str(sys.exc_info()[1])) 3590 else: 3591 self.assertTrue(False) 3592 self.assertEqual(["start", "end"], events) 35933595 assertEqual = self.assertEqual 3596 3597 events = [] 3598 class Target(object): 3599 def start(self, tag, attrib): 3600 events.append("start") 3601 assertEqual("TAG", tag)3602 def end(self, tag): 3603 events.append("end") 3604 assertEqual("TAG", tag) 3605 def close(self): 3606 raise ValueError("TEST") 3607 3608 parser = self.XMLParser(target=Target()) 3609 3610 try: 3611 parser.feed("<TAG/>") 3612 parser.close() 3613 except ValueError: 3614 self.assertTrue('TEST' in str(sys.exc_info()[1])) 3615 else: 3616 self.assertTrue(False) 3617 self.assertEqual(["start", "end"], events) 36183620 assertEqual = self.assertEqual 3621 3622 events = [] 3623 class Target(object): 3624 def start(self, tag, attrib): 3625 events.append("start") 3626 assertEqual("TAG", tag) 3627 raise IndexError("TEST-IE")3628 def end(self, tag): 3629 events.append("end") 3630 assertEqual("TAG", tag) 3631 def close(self): 3632 raise ValueError("TEST-VE") 3633 3634 parser = self.XMLParser(target=Target()) 3635 3636 try: 3637 parser.feed("<TAG/>") 3638 parser.close() 3639 except IndexError: 3640 if 'lxml' in self.etree.__name__: 3641 # we try not to swallow the initial exception in Py2 3642 self.assertTrue(sys.version_info[0] < 3) 3643 self.assertTrue('TEST-IE' in str(sys.exc_info()[1])) 3644 except ValueError: 3645 if 'lxml' in self.etree.__name__: 3646 self.assertTrue(sys.version_info[0] >= 3) 3647 self.assertTrue('TEST-VE' in str(sys.exc_info()[1])) 3648 else: 3649 self.assertTrue(False) 3650 3651 if 'lxml' in self.etree.__name__: 3652 self.assertEqual(["start"], events) 3653 else: 3654 # cElementTree calls end() as well 3655 self.assertTrue("start" in events) 36563658 assertEqual = self.assertEqual 3659 assertFalse = self.assertFalse 3660 Element = self.etree.Element 3661 3662 events = [] 3663 class Target(object): 3664 def start(self, tag, attrib): 3665 events.append("start") 3666 assertFalse(attrib) 3667 assertEqual("TAG", tag)3668 def end(self, tag): 3669 events.append("end") 3670 assertEqual("TAG", tag) 3671 def close(self): 3672 return Element("DONE") 3673 3674 parser = self.XMLParser(target=Target()) 3675 tree = self.etree.ElementTree() 3676 tree.parse(BytesIO("<TAG/>"), parser=parser) 3677 3678 self.assertEqual("DONE", tree.getroot().tag) 3679 self.assertEqual(["start", "end"], events) 36803682 assertEqual = self.assertEqual 3683 3684 events = [] 3685 class Target(object): 3686 def start(self, tag, attrib): 3687 events.append("start-" + tag) 3688 for name, value in attrib.items(): 3689 assertEqual(tag + name, value)3690 def end(self, tag): 3691 events.append("end-" + tag) 3692 def close(self): 3693 return "DONE" 3694 3695 parser = self.XMLParser(target=Target()) 3696 3697 parser.feed('<root a="roota" b="rootb"><sub c="subc"/></root>') 3698 done = parser.close() 3699 3700 self.assertEqual("DONE", done) 3701 self.assertEqual(["start-root", "start-sub", "end-sub", "end-root"], 3702 events) 37033705 events = [] 3706 class Target(object): 3707 def start(self, tag, attrib): 3708 events.append("start-" + tag)3709 def end(self, tag): 3710 events.append("end-" + tag) 3711 def data(self, data): 3712 events.append("data-" + data) 3713 def close(self): 3714 return "DONE" 3715 3716 parser = self.XMLParser(target=Target()) 3717 3718 parser.feed('<root>A<sub/>B</root>') 3719 done = parser.close() 3720 3721 self.assertEqual("DONE", done) 3722 self.assertEqual(["start-root", "data-A", "start-sub", 3723 "end-sub", "data-B", "end-root"], 3724 events) 3725 3731 def _flush_data(self): 3732 if self._data: 3733 events.append("data-" + ''.join(self._data)) 3734 del self._data[:] 3735 def start(self, tag, attrib): 3736 self._flush_data() 3737 events.append("start-" + tag) 3738 def end(self, tag): 3739 self._flush_data() 3740 events.append("end-" + tag) 3741 def data(self, data): 3742 self._data.append(data) 3743 def close(self): 3744 self._flush_data() 3745 return "DONE" 3746 3747 parser = self.XMLParser(target=Target()) 3748 3749 dtd = ''' 3750 <!DOCTYPE root [ 3751 <!ELEMENT root (sub*)> 3752 <!ELEMENT sub (#PCDATA)> 3753 <!ENTITY ent "an entity"> 3754 ]> 3755 ''' 3756 parser.feed(dtd+'<root><sub/><sub>this is &ent;</sub><sub/></root>') 3757 done = parser.close() 3758 3759 self.assertEqual("DONE", done) 3760 self.assertEqual(["start-root", "start-sub", "end-sub", "start-sub", 3761 "data-this is an entity", 3762 "end-sub", "start-sub", "end-sub", "end-root"], 3763 events) 3764 3765 required_versions_ET['test_parser_target_entity_unknown'] = (1,3) 3771 def _flush_data(self): 3772 if self._data: 3773 events.append("data-" + ''.join(self._data)) 3774 del self._data[:] 3775 def start(self, tag, attrib): 3776 self._flush_data() 3777 events.append("start-" + tag) 3778 def end(self, tag): 3779 self._flush_data() 3780 events.append("end-" + tag) 3781 def data(self, data): 3782 self._data.append(data) 3783 def close(self): 3784 self._flush_data() 3785 return "DONE" 3786 3787 parser = self.XMLParser(target=Target()) 3788 3789 def feed(): 3790 parser.feed('<root><sub/><sub>some &ent;</sub><sub/></root>') 3791 parser.close() 3792 3793 self.assertRaises(self.etree.ParseError, feed) 37943796 builder = self.etree.TreeBuilder() 3797 el = builder.start("root", {'a':'A', 'b':'B'}) 3798 self.assertEqual("root", el.tag) 3799 self.assertEqual({'a':'A', 'b':'B'}, el.attrib) 3800 builder.data("ROOTTEXT") 3801 el = builder.start("child", {'x':'X', 'y':'Y'}) 3802 self.assertEqual("child", el.tag) 3803 self.assertEqual({'x':'X', 'y':'Y'}, el.attrib) 3804 builder.data("CHILDTEXT") 3805 el = builder.end("child") 3806 self.assertEqual("child", el.tag) 3807 self.assertEqual({'x':'X', 'y':'Y'}, el.attrib) 3808 self.assertEqual("CHILDTEXT", el.text) 3809 self.assertEqual(None, el.tail) 3810 builder.data("CHILDTAIL") 3811 root = builder.end("root") 3812 3813 self.assertEqual("root", root.tag) 3814 self.assertEqual("ROOTTEXT", root.text) 3815 self.assertEqual("CHILDTEXT", root[0].text) 3816 self.assertEqual("CHILDTAIL", root[0].tail)38173819 parser = self.XMLParser(target=self.etree.TreeBuilder()) 3820 parser.feed('<root>ROOTTEXT<child>CHILDTEXT</child>CHILDTAIL</root>') 3821 root = parser.close() 3822 3823 self.assertEqual("root", root.tag) 3824 self.assertEqual("ROOTTEXT", root.text) 3825 self.assertEqual("CHILDTEXT", root[0].text) 3826 self.assertEqual("CHILDTAIL", root[0].tail)3827 3828 # helper methods 38293831 """Write out element for comparison. 3832 """ 3833 data = self.etree.tostring(element, encoding=encoding) 3834 return canonicalize(data)38353837 """Write out element for comparison, using real file. 3838 """ 3839 ElementTree = self.etree.ElementTree 3840 handle, filename = tempfile.mkstemp() 3841 try: 3842 f = open(filename, 'wb') 3843 tree = ElementTree(element=element) 3844 tree.write(f, encoding=encoding) 3845 f.close() 3846 f = open(filename, 'rb') 3847 data = f.read() 3848 f.close() 3849 finally: 3850 os.close(handle) 3851 os.remove(filename) 3852 return canonicalize(data)38533855 """Writes element out and checks whether it is expected. 3856 3857 Does this two ways; once using BytesIO, once using a real file. 3858 """ 3859 if isinstance(expected, unicode): 3860 expected = expected.encode(encoding) 3861 self.assertEqual(expected, self._writeElement(element, encoding)) 3862 self.assertEqual(expected, self._writeElementFile(element, encoding))38633865 "Checks if the result XML byte string specifies the encoding." 3866 enc_re = r"<\?xml[^>]+ encoding=[\"']([^\"']+)[\"']" 3867 if isinstance(result, str): 3868 has_encoding = re.compile(enc_re).match 3869 else: 3870 has_encoding = re.compile(_bytes(enc_re)).match 3871 self.assertTrue(has_encoding(result)) 3872 result_encoding = has_encoding(result).group(1) 3873 self.assertEqual(result_encoding.upper(), encoding.upper())38743876 return self.etree.tostring(tree.getroot()).replace( 3877 _bytes(' '), _bytes('')).replace(_bytes('\n'), _bytes(''))3878 38813883 self.assertTrue(hasattr(element, 'tag')) 3884 self.assertTrue(hasattr(element, 'attrib')) 3885 self.assertTrue(hasattr(element, 'text')) 3886 self.assertTrue(hasattr(element, 'tail')) 3887 self._check_string(element.tag) 3888 self._check_mapping(element.attrib) 3889 if element.text != None: 3890 self._check_string(element.text) 3891 if element.tail != None: 3892 self._check_string(element.tail)38933895 len(string) 3896 for char in string: 3897 self.assertEqual(1, len(char)) 3898 new_string = string + "" 3899 new_string = string + " " 3900 string[:0]39013903 len(mapping) 3904 keys = mapping.keys() 3905 values = mapping.values() 3906 items = mapping.items() 3907 for key in keys: 3908 item = mapping[key] 3909 mapping["key"] = "value" 3910 self.assertEqual("value", mapping["key"])39113914 etree = None 39154071 def __next__(self): 4072 return next(self.events) 4073 next = __next__ 4074 4075 parser = self.etree.XMLPullParser(events=DummyIter()) 4076 self._feed(parser, "<foo>bar</foo>") 4077 self.assert_event_tags(parser, [('start', 'foo'), ('end', 'foo')]) 40783917 if chunk_size is None: 3918 parser.feed(data) 3919 else: 3920 for i in range(0, len(data), chunk_size): 3921 parser.feed(data[i:i+chunk_size])39223924 if 'ElementTree' in self.etree.__name__: 3925 # ElementTree's API is a bit unwieldy in Py3.4 3926 root = parser._close_and_return_root() 3927 else: 3928 root = parser.close() 3929 return root3930 39353937 for chunk_size in (None, 1, 5): 3938 #with self.subTest(chunk_size=chunk_size): 3939 parser = self.etree.XMLPullParser() 3940 self.assert_event_tags(parser, []) 3941 self._feed(parser, "<!-- comment -->\n", chunk_size) 3942 self.assert_event_tags(parser, []) 3943 self._feed(parser, 3944 "<root>\n <element key='value'>text</element", 3945 chunk_size) 3946 self.assert_event_tags(parser, []) 3947 self._feed(parser, ">\n", chunk_size) 3948 self.assert_event_tags(parser, [('end', 'element')]) 3949 self._feed(parser, "<element>text</element>tail\n", chunk_size) 3950 self._feed(parser, "<empty-element/>\n", chunk_size) 3951 self.assert_event_tags(parser, [ 3952 ('end', 'element'), 3953 ('end', 'empty-element'), 3954 ]) 3955 self._feed(parser, "</root>\n", chunk_size) 3956 self.assert_event_tags(parser, [('end', 'root')]) 3957 root = self._close_and_return_root(parser) 3958 self.assertEqual(root.tag, 'root')39593961 parser = self.etree.XMLPullParser() 3962 it = parser.read_events() 3963 self._feed(parser, "<root>\n <element key='value'>text</element>\n") 3964 action, elem = next(it) 3965 self.assertEqual((action, elem.tag), ('end', 'element')) 3966 self._feed(parser, "</root>\n") 3967 action, elem = next(it) 3968 self.assertEqual((action, elem.tag), ('end', 'root')) 3969 try: 3970 next(it) 3971 except StopIteration: 3972 self.assertTrue(True) 3973 else: 3974 self.assertTrue(False)39753977 parser = self.etree.XMLPullParser() 3978 self.assert_event_tags(parser, []) 3979 self._feed(parser, "<!-- comment -->\n") 3980 self.assert_event_tags(parser, []) 3981 self._feed(parser, "<root xmlns='namespace'>\n") 3982 self.assert_event_tags(parser, []) 3983 self._feed(parser, "<element key='value'>text</element") 3984 self.assert_event_tags(parser, []) 3985 self._feed(parser, ">\n") 3986 self.assert_event_tags(parser, [('end', '{namespace}element')]) 3987 self._feed(parser, "<element>text</element>tail\n") 3988 self._feed(parser, "<empty-element/>\n") 3989 self.assert_event_tags(parser, [ 3990 ('end', '{namespace}element'), 3991 ('end', '{namespace}empty-element'), 3992 ]) 3993 self._feed(parser, "</root>\n") 3994 self.assert_event_tags(parser, [('end', '{namespace}root')]) 3995 root = self._close_and_return_root(parser) 3996 self.assertEqual(root.tag, '{namespace}root')39973999 parser = self.etree.XMLPullParser(events=('start-ns', 'end-ns')) 4000 self._feed(parser, "<!-- comment -->\n") 4001 self._feed(parser, "<root xmlns='namespace'>\n") 4002 self.assertEqual( 4003 list(parser.read_events()), 4004 [('start-ns', ('', 'namespace'))]) 4005 self._feed(parser, "<element key='value'>text</element") 4006 self._feed(parser, ">\n") 4007 self._feed(parser, "<element>text</element>tail\n") 4008 self._feed(parser, "<empty-element/>\n") 4009 self._feed(parser, "</root>\n") 4010 self.assertEqual(list(parser.read_events()), [('end-ns', None)]) 4011 parser.close()40124014 parser = self.etree.XMLPullParser(events=()) 4015 self._feed(parser, "<root/>\n") 4016 self.assert_event_tags(parser, []) 4017 4018 parser = self.etree.XMLPullParser(events=('start', 'end')) 4019 self._feed(parser, "<!-- comment -->\n") 4020 self.assert_event_tags(parser, []) 4021 self._feed(parser, "<root>\n") 4022 self.assert_event_tags(parser, [('start', 'root')]) 4023 self._feed(parser, "<element key='value'>text</element") 4024 self.assert_event_tags(parser, [('start', 'element')]) 4025 self._feed(parser, ">\n") 4026 self.assert_event_tags(parser, [('end', 'element')]) 4027 self._feed(parser, 4028 "<element xmlns='foo'>text<empty-element/></element>tail\n") 4029 self.assert_event_tags(parser, [ 4030 ('start', '{foo}element'), 4031 ('start', '{foo}empty-element'), 4032 ('end', '{foo}empty-element'), 4033 ('end', '{foo}element'), 4034 ]) 4035 self._feed(parser, "</root>") 4036 root = self._close_and_return_root(parser) 4037 self.assert_event_tags(parser, [('end', 'root')]) 4038 self.assertEqual(root.tag, 'root') 4039 4040 parser = self.etree.XMLPullParser(events=('start',)) 4041 self._feed(parser, "<!-- comment -->\n") 4042 self.assert_event_tags(parser, []) 4043 self._feed(parser, "<root>\n") 4044 self.assert_event_tags(parser, [('start', 'root')]) 4045 self._feed(parser, "<element key='value'>text</element") 4046 self.assert_event_tags(parser, [('start', 'element')]) 4047 self._feed(parser, ">\n") 4048 self.assert_event_tags(parser, []) 4049 self._feed(parser, 4050 "<element xmlns='foo'>text<empty-element/></element>tail\n") 4051 self.assert_event_tags(parser, [ 4052 ('start', '{foo}element'), 4053 ('start', '{foo}empty-element'), 4054 ]) 4055 self._feed(parser, "</root>") 4056 root = self._close_and_return_root(parser) 4057 self.assertEqual(root.tag, 'root')40584060 # Test that events can be some sequence that's not just a tuple or list 4061 eventset = set(['end', 'start']) 4062 parser = self.etree.XMLPullParser(events=eventset) 4063 self._feed(parser, "<foo>bar</foo>") 4064 self.assert_event_tags(parser, [('start', 'foo'), ('end', 'foo')]) 4065 4066 class DummyIter: 4067 def __init__(self): 4068 self.events = iter(['start', 'end', 'start-ns'])4069 def __iter__(self): 4070 return self4080 try: 4081 self.etree.XMLPullParser(events=('start', 'end', 'bogus')) 4082 except ValueError: 4083 self.assertTrue(True) 4084 else: 4085 self.assertTrue(False)4086 4087 4088 if etree: 4091 4094 4095 4096 if ElementTree: 4108 4109 filter_by_version( 4110 ElementTreeTestCase, 4111 ElementTreeTestCase.required_versions_ET, ET_VERSION) 4112 4113 if hasattr(ElementTree, 'XMLPullParser'): 4116 else: 4117 ElementTreePullTestCase = None 4118 4119 4120 if cElementTree: 4123 4124 filter_by_version( 4125 CElementTreeTestCase, 4126 CElementTreeTestCase.required_versions_cET, CET_VERSION)4130 suite = unittest.TestSuite() 4131 if etree: 4132 suite.addTests([unittest.makeSuite(ETreeTestCase)]) 4133 suite.addTests([unittest.makeSuite(ETreePullTestCase)]) 4134 if ElementTree: 4135 suite.addTests([unittest.makeSuite(ElementTreeTestCase)]) 4136 if ElementTreePullTestCase: 4137 suite.addTests([unittest.makeSuite(ElementTreePullTestCase)]) 4138 if cElementTree: 4139 suite.addTests([unittest.makeSuite(CElementTreeTestCase)]) 4140 return suite4141 4142 if __name__ == '__main__': 4143 print('to test use test.py %s' % __file__) 4144
Home | Trees | Indices | Help |
|
---|
Generated by Epydoc 3.0.1 on Fri Oct 13 15:46:58 2017 | http://epydoc.sourceforge.net |