Package lxml :: Package tests :: Module test_elementtree
[hide private]
[frames] | no frames]

Source Code for Module lxml.tests.test_elementtree

   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, gc, 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 StringIO, 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 
  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", "?")) 
  31   
  32  try: 
  33      reversed 
  34  except NameError: 
  35      # Python 2.3 
36 - def reversed(seq):
37 seq = list(seq)[::-1] 38 return seq
39
40 -class _ETreeTestCaseBase(HelperTestCase):
41 etree = None 42 required_versions_ET = {} 43 required_versions_cET = {} 44
45 - def test_element(self):
46 for i in range(10): 47 e = self.etree.Element('foo') 48 self.assertEquals(e.tag, 'foo') 49 self.assertEquals(e.text, None) 50 self.assertEquals(e.tail, None)
51
52 - def test_simple(self):
53 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.assertEquals(3, len(root)) 60 self.assertEquals('one', root[0].tag) 61 self.assertEquals('two', root[1].tag) 62 self.assertEquals('three', root[2].tag) 63 self.assertRaises(IndexError, operator.getitem, root, 3)
64 65 # test weird dictionary interaction leading to segfault previously
67 root = self.etree.Element('root') 68 self.assertEquals(root.tag, "root") 69 add = self.etree.ElementTree(file=BytesIO('<foo>Foo</foo>')) 70 self.assertEquals(add.getroot().tag, "foo") 71 self.assertEquals(add.getroot().text, "Foo") 72 root.append(self.etree.Element('baz')) 73 self.assertEquals(root.tag, "root") 74 self.assertEquals(root[0].tag, "baz")
75
76 - def test_subelement(self):
77 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.assertEquals(3, len(root)) 85 self.assertEquals('one', root[0].tag) 86 self.assertEquals('two', root[1].tag) 87 self.assertEquals('three', root[2].tag)
88
89 - def test_element_contains(self):
90 Element = self.etree.Element 91 SubElement = self.etree.SubElement 92 93 root1 = Element('root') 94 SubElement(root1, 'one') 95 self.assert_(root1[0] in root1) 96 97 root2 = Element('root') 98 SubElement(root2, 'two') 99 SubElement(root2, 'three') 100 self.assert_(root2[0] in root2) 101 self.assert_(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)
106
108 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.assertEquals(1, len(root)) 114 self.assertEquals('one', root[0].tag) 115 self.assertRaises(IndexError, operator.getitem, root, 1)
116
118 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.assertEquals(3, len(root)) 124 self.assertEquals('one', root[0].tag) 125 self.assertEquals('two', root[1].tag) 126 self.assertEquals('three', root[2].tag)
127
129 ElementTree = self.etree.ElementTree 130 131 f = BytesIO('<doc>Test</doc>') 132 doc = ElementTree(file=f) 133 root = doc.getroot() 134 self.assertEquals(0, len(root))
135
137 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.assertEquals(d, a[-1]) 144 self.assertEquals(c, a[-2]) 145 self.assertEquals(b, a[-3]) 146 self.assertRaises(IndexError, operator.getitem, a, -4) 147 a[-1] = e = Element('e') 148 self.assertEquals(e, a[-1]) 149 del a[-1] 150 self.assertEquals(2, len(a))
151
152 - def test_elementtree(self):
153 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.assertEquals(2, len(root)) 159 self.assertEquals('one', root[0].tag) 160 self.assertEquals('two', root[1].tag)
161
162 - def test_text(self):
163 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.assertEquals('This is a text', root.text)
169
170 - def test_text_empty(self):
171 ElementTree = self.etree.ElementTree 172 173 f = BytesIO('<doc></doc>') 174 doc = ElementTree(file=f) 175 root = doc.getroot() 176 self.assertEquals(None, root.text)
177
178 - def test_text_other(self):
179 ElementTree = self.etree.ElementTree 180 181 f = BytesIO('<doc><one>One</one></doc>') 182 doc = ElementTree(file=f) 183 root = doc.getroot() 184 self.assertEquals(None, root.text) 185 self.assertEquals('One', root[0].text)
186
187 - def test_text_escape_in(self):
188 ElementTree = self.etree.ElementTree 189 190 f = BytesIO('<doc>This is &gt; than a text</doc>') 191 doc = ElementTree(file=f) 192 root = doc.getroot() 193 self.assertEquals('This is > than a text', root.text)
194
195 - def test_text_escape_out(self):
196 Element = self.etree.Element 197 198 a = Element("a") 199 a.text = "<>&" 200 self.assertXML(_bytes('<a>&lt;&gt;&amp;</a>'), 201 a)
202
203 - def test_text_escape_tostring(self):
204 tostring = self.etree.tostring 205 Element = self.etree.Element 206 207 a = Element("a") 208 a.text = "<>&" 209 self.assertEquals(_bytes('<a>&lt;&gt;&amp;</a>'), 210 tostring(a))
211
212 - def test_text_str_subclass(self):
213 Element = self.etree.Element 214 215 class strTest(str): 216 pass
217 218 a = Element("a") 219 a.text = strTest("text") 220 self.assertXML(_bytes('<a>text</a>'), 221 a)
222
223 - def test_tail(self):
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.assertEquals(1, len(root)) 230 self.assertEquals('This is ', root.text) 231 self.assertEquals(None, root.tail) 232 self.assertEquals('mixed', root[0].text) 233 self.assertEquals(' content.', root[0].tail)
234
235 - def test_tail_str_subclass(self):
236 Element = self.etree.Element 237 SubElement = self.etree.SubElement 238 239 class strTest(str): 240 pass
241 242 a = Element("a") 243 SubElement(a, "t").tail = strTest("tail") 244 self.assertXML(_bytes('<a><t></t>tail</a>'), 245 a) 246
247 - def _test_del_tail(self):
248 # 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.assertEquals(1, len(root)) 253 self.assertEquals('This is ', root.text) 254 self.assertEquals(None, root.tail) 255 self.assertEquals('mixed', root[0].text) 256 self.assertEquals(' content.', root[0].tail) 257 258 del root[0].tail 259 260 self.assertEquals(1, len(root)) 261 self.assertEquals('This is ', root.text) 262 self.assertEquals(None, root.tail) 263 self.assertEquals('mixed', root[0].text) 264 self.assertEquals(None, root[0].tail) 265 266 root[0].tail = "TAIL" 267 268 self.assertEquals(1, len(root)) 269 self.assertEquals('This is ', root.text) 270 self.assertEquals(None, root.tail) 271 self.assertEquals('mixed', root[0].text) 272 self.assertEquals('TAIL', root[0].tail)
273
274 - def test_ElementTree(self):
275 Element = self.etree.Element 276 ElementTree = self.etree.ElementTree 277 278 el = Element('hoi') 279 doc = ElementTree(el) 280 root = doc.getroot() 281 self.assertEquals(None, root.text) 282 self.assertEquals('hoi', root.tag)
283
284 - def test_attributes(self):
285 ElementTree = self.etree.ElementTree 286 287 f = BytesIO('<doc one="One" two="Two"/>') 288 doc = ElementTree(file=f) 289 root = doc.getroot() 290 self.assertEquals('One', root.attrib['one']) 291 self.assertEquals('Two', root.attrib['two']) 292 self.assertRaises(KeyError, operator.getitem, root.attrib, 'three')
293
294 - def test_attributes2(self):
295 ElementTree = self.etree.ElementTree 296 297 f = BytesIO('<doc one="One" two="Two"/>') 298 doc = ElementTree(file=f) 299 root = doc.getroot() 300 self.assertEquals('One', root.attrib.get('one')) 301 self.assertEquals('Two', root.attrib.get('two')) 302 self.assertEquals(None, root.attrib.get('three')) 303 self.assertEquals('foo', root.attrib.get('three', 'foo'))
304
305 - def test_attributes3(self):
306 ElementTree = self.etree.ElementTree 307 308 f = BytesIO('<doc one="One" two="Two"/>') 309 doc = ElementTree(file=f) 310 root = doc.getroot() 311 self.assertEquals('One', root.get('one')) 312 self.assertEquals('Two', root.get('two')) 313 self.assertEquals(None, root.get('three')) 314 self.assertEquals('foo', root.get('three', 'foo'))
315
316 - def test_attrib_clear(self):
317 XML = self.etree.XML 318 319 root = XML(_bytes('<doc one="One" two="Two"/>')) 320 self.assertEquals('One', root.get('one')) 321 self.assertEquals('Two', root.get('two')) 322 root.attrib.clear() 323 self.assertEquals(None, root.get('one')) 324 self.assertEquals(None, root.get('two'))
325
326 - def test_attrib_set_clear(self):
327 Element = self.etree.Element 328 329 root = Element("root", one="One") 330 root.set("two", "Two") 331 self.assertEquals('One', root.get('one')) 332 self.assertEquals('Two', root.get('two')) 333 root.attrib.clear() 334 self.assertEquals(None, root.get('one')) 335 self.assertEquals(None, root.get('two'))
336
337 - def test_attrib_ns_clear(self):
338 Element = self.etree.Element 339 SubElement = self.etree.SubElement 340 341 attribNS = '{http://foo/bar}x' 342 343 parent = Element('parent') 344 parent.set(attribNS, 'a') 345 child = SubElement(parent, 'child') 346 child.set(attribNS, 'b') 347 348 self.assertEquals('a', parent.get(attribNS)) 349 self.assertEquals('b', child.get(attribNS)) 350 351 parent.clear() 352 self.assertEquals(None, parent.get(attribNS)) 353 self.assertEquals('b', child.get(attribNS))
354
355 - def test_attrib_pop(self):
356 ElementTree = self.etree.ElementTree 357 358 f = BytesIO('<doc one="One" two="Two"/>') 359 doc = ElementTree(file=f) 360 root = doc.getroot() 361 self.assertEquals('One', root.attrib['one']) 362 self.assertEquals('Two', root.attrib['two']) 363 364 self.assertEquals('One', root.attrib.pop('one')) 365 366 self.assertEquals(None, root.attrib.get('one')) 367 self.assertEquals('Two', root.attrib['two'])
368
369 - def test_attrib_pop_unknown(self):
370 root = self.etree.XML(_bytes('<doc one="One" two="Two"/>')) 371 self.assertRaises(KeyError, root.attrib.pop, 'NONE') 372 373 self.assertEquals('One', root.attrib['one']) 374 self.assertEquals('Two', root.attrib['two'])
375
376 - def test_attrib_pop_default(self):
377 root = self.etree.XML(_bytes('<doc one="One" two="Two"/>')) 378 self.assertEquals('Three', root.attrib.pop('three', 'Three'))
379
380 - def test_attrib_pop_empty_default(self):
381 root = self.etree.XML(_bytes('<doc/>')) 382 self.assertEquals('Three', root.attrib.pop('three', 'Three'))
383
384 - def test_attrib_pop_invalid_args(self):
385 root = self.etree.XML(_bytes('<doc one="One" two="Two"/>')) 386 self.assertRaises(TypeError, root.attrib.pop, 'One', None, None)
387
388 - def test_attribute_update_dict(self):
389 XML = self.etree.XML 390 391 root = XML(_bytes('<doc alpha="Alpha" beta="Beta"/>')) 392 items = list(root.attrib.items()) 393 items.sort() 394 self.assertEquals( 395 [('alpha', 'Alpha'), ('beta', 'Beta')], 396 items) 397 398 root.attrib.update({'alpha' : 'test', 'gamma' : 'Gamma'}) 399 400 items = list(root.attrib.items()) 401 items.sort() 402 self.assertEquals( 403 [('alpha', 'test'), ('beta', 'Beta'), ('gamma', 'Gamma')], 404 items)
405
406 - def test_attribute_update_sequence(self):
407 XML = self.etree.XML 408 409 root = XML(_bytes('<doc alpha="Alpha" beta="Beta"/>')) 410 items = list(root.attrib.items()) 411 items.sort() 412 self.assertEquals( 413 [('alpha', 'Alpha'), ('beta', 'Beta')], 414 items) 415 416 root.attrib.update({'alpha' : 'test', 'gamma' : 'Gamma'}.items()) 417 418 items = list(root.attrib.items()) 419 items.sort() 420 self.assertEquals( 421 [('alpha', 'test'), ('beta', 'Beta'), ('gamma', 'Gamma')], 422 items)
423
424 - def test_attribute_update_iter(self):
425 XML = self.etree.XML 426 427 root = XML(_bytes('<doc alpha="Alpha" beta="Beta"/>')) 428 items = list(root.attrib.items()) 429 items.sort() 430 self.assertEquals( 431 [('alpha', 'Alpha'), ('beta', 'Beta')], 432 items) 433 434 root.attrib.update(iter({'alpha' : 'test', 'gamma' : 'Gamma'}.items())) 435 436 items = list(root.attrib.items()) 437 items.sort() 438 self.assertEquals( 439 [('alpha', 'test'), ('beta', 'Beta'), ('gamma', 'Gamma')], 440 items)
441
442 - def test_attribute_update_attrib(self):
443 XML = self.etree.XML 444 445 root = XML(_bytes('<doc alpha="Alpha" beta="Beta"/>')) 446 items = list(root.attrib.items()) 447 items.sort() 448 self.assertEquals( 449 [('alpha', 'Alpha'), ('beta', 'Beta')], 450 items) 451 452 other = XML(_bytes('<doc alpha="test" gamma="Gamma"/>')) 453 root.attrib.update(other.attrib) 454 455 items = list(root.attrib.items()) 456 items.sort() 457 self.assertEquals( 458 [('alpha', 'test'), ('beta', 'Beta'), ('gamma', 'Gamma')], 459 items)
460
461 - def test_attribute_keys(self):
462 XML = self.etree.XML 463 464 root = XML(_bytes('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')) 465 keys = list(root.attrib.keys()) 466 keys.sort() 467 self.assertEquals(['alpha', 'beta', 'gamma'], keys)
468
469 - def test_attribute_keys2(self):
470 XML = self.etree.XML 471 472 root = XML(_bytes('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')) 473 keys = list(root.keys()) 474 keys.sort() 475 self.assertEquals(['alpha', 'beta', 'gamma'], keys)
476
477 - def test_attribute_items2(self):
478 XML = self.etree.XML 479 480 root = XML(_bytes('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')) 481 items = list(root.items()) 482 items.sort() 483 self.assertEquals( 484 [('alpha','Alpha'), ('beta','Beta'), ('gamma','Gamma')], 485 items)
486
487 - def test_attribute_keys_ns(self):
488 XML = self.etree.XML 489 490 root = XML(_bytes('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')) 491 keys = list(root.keys()) 492 keys.sort() 493 self.assertEquals(['bar', '{http://ns.codespeak.net/test}baz'], 494 keys)
495
496 - def test_attribute_values(self):
497 XML = self.etree.XML 498 499 root = XML(_bytes('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')) 500 values = list(root.attrib.values()) 501 values.sort() 502 self.assertEquals(['Alpha', 'Beta', 'Gamma'], values)
503
504 - def test_attribute_values_ns(self):
505 XML = self.etree.XML 506 507 root = XML(_bytes('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')) 508 values = list(root.attrib.values()) 509 values.sort() 510 self.assertEquals( 511 ['Bar', 'Baz'], values)
512
513 - def test_attribute_items(self):
514 XML = self.etree.XML 515 516 root = XML(_bytes('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')) 517 items = list(root.attrib.items()) 518 items.sort() 519 self.assertEquals([ 520 ('alpha', 'Alpha'), 521 ('beta', 'Beta'), 522 ('gamma', 'Gamma'), 523 ], 524 items)
525
526 - def test_attribute_items_ns(self):
527 XML = self.etree.XML 528 529 root = XML(_bytes('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')) 530 items = list(root.attrib.items()) 531 items.sort() 532 self.assertEquals( 533 [('bar', 'Bar'), ('{http://ns.codespeak.net/test}baz', 'Baz')], 534 items)
535
536 - def test_attribute_str(self):
537 XML = self.etree.XML 538 539 expected = "{'{http://ns.codespeak.net/test}baz': 'Baz', 'bar': 'Bar'}" 540 alternative = "{'bar': 'Bar', '{http://ns.codespeak.net/test}baz': 'Baz'}" 541 542 root = XML(_bytes('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')) 543 try: 544 self.assertEquals(expected, str(root.attrib)) 545 except AssertionError: 546 self.assertEquals(alternative, str(root.attrib))
547
548 - def test_attribute_contains(self):
549 XML = self.etree.XML 550 551 root = XML(_bytes('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')) 552 self.assertEquals( 553 True, 'bar' in root.attrib) 554 self.assertEquals( 555 False, 'baz' in root.attrib) 556 self.assertEquals( 557 False, 'hah' in root.attrib) 558 self.assertEquals( 559 True, 560 '{http://ns.codespeak.net/test}baz' in root.attrib)
561
562 - def test_attribute_set(self):
563 Element = self.etree.Element 564 565 root = Element("root") 566 root.set("attr", "TEST") 567 self.assertEquals("TEST", root.get("attr"))
568
569 - def test_attribute_iterator(self):
570 XML = self.etree.XML 571 572 root = XML(_bytes('<doc alpha="Alpha" beta="Beta" gamma="Gamma" />')) 573 result = [] 574 for key in root.attrib: 575 result.append(key) 576 result.sort() 577 self.assertEquals(['alpha', 'beta', 'gamma'], result)
578
579 - def test_attribute_manipulation(self):
580 Element = self.etree.Element 581 582 a = Element('a') 583 a.attrib['foo'] = 'Foo' 584 a.attrib['bar'] = 'Bar' 585 self.assertEquals('Foo', a.attrib['foo']) 586 del a.attrib['foo'] 587 self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo')
588
589 - def test_del_attribute_ns(self):
590 Element = self.etree.Element 591 592 a = Element('a') 593 a.attrib['{http://a/}foo'] = 'Foo' 594 a.attrib['{http://a/}bar'] = 'Bar' 595 self.assertEquals(None, a.get('foo')) 596 self.assertEquals('Foo', a.get('{http://a/}foo')) 597 self.assertEquals('Foo', a.attrib['{http://a/}foo']) 598 599 self.assertRaises(KeyError, operator.delitem, a.attrib, 'foo') 600 self.assertEquals('Foo', a.attrib['{http://a/}foo']) 601 602 del a.attrib['{http://a/}foo'] 603 self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo')
604
605 - def test_del_attribute_ns_parsed(self):
606 XML = self.etree.XML 607 608 a = XML(_bytes('<a xmlns:nsa="http://a/" nsa:foo="FooNS" foo="Foo" />')) 609 610 self.assertEquals('Foo', a.attrib['foo']) 611 self.assertEquals('FooNS', a.attrib['{http://a/}foo']) 612 613 del a.attrib['foo'] 614 self.assertEquals('FooNS', a.attrib['{http://a/}foo']) 615 self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo') 616 self.assertRaises(KeyError, operator.delitem, a.attrib, 'foo') 617 618 del a.attrib['{http://a/}foo'] 619 self.assertRaises(KeyError, operator.getitem, a.attrib, '{http://a/}foo') 620 self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo') 621 622 a = XML(_bytes('<a xmlns:nsa="http://a/" foo="Foo" nsa:foo="FooNS" />')) 623 624 self.assertEquals('Foo', a.attrib['foo']) 625 self.assertEquals('FooNS', a.attrib['{http://a/}foo']) 626 627 del a.attrib['foo'] 628 self.assertEquals('FooNS', a.attrib['{http://a/}foo']) 629 self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo') 630 631 del a.attrib['{http://a/}foo'] 632 self.assertRaises(KeyError, operator.getitem, a.attrib, '{http://a/}foo') 633 self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo')
634
635 - def test_XML(self):
636 XML = self.etree.XML 637 638 root = XML(_bytes('<doc>This is a text.</doc>')) 639 self.assertEquals(0, len(root)) 640 self.assertEquals('This is a text.', root.text)
641
642 - def test_XMLID(self):
643 XMLID = self.etree.XMLID 644 XML = self.etree.XML 645 xml_text = _bytes(''' 646 <document> 647 <h1 id="chapter1">...</h1> 648 <p id="note1" class="note">...</p> 649 <p>Regular paragraph.</p> 650 <p xml:id="xmlid">XML:ID paragraph.</p> 651 <p id="warn1" class="warning">...</p> 652 </document> 653 ''') 654 655 root, dic = XMLID(xml_text) 656 root2 = XML(xml_text) 657 self.assertEquals(self._writeElement(root), 658 self._writeElement(root2)) 659 expected = { 660 "chapter1" : root[0], 661 "note1" : root[1], 662 "warn1" : root[4] 663 } 664 self.assertEquals(dic, expected)
665
666 - def test_fromstring(self):
667 fromstring = self.etree.fromstring 668 669 root = fromstring('<doc>This is a text.</doc>') 670 self.assertEquals(0, len(root)) 671 self.assertEquals('This is a text.', root.text)
672 673 required_versions_ET['test_fromstringlist'] = (1,3)
674 - def test_fromstringlist(self):
675 fromstringlist = self.etree.fromstringlist 676 677 root = fromstringlist(["<do", "c>T", "hi", "s is", 678 " a text.<", "/doc", ">"]) 679 self.assertEquals(0, len(root)) 680 self.assertEquals('This is a text.', root.text)
681 682 required_versions_ET['test_fromstringlist_characters'] = (1,3)
683 - def test_fromstringlist_characters(self):
684 fromstringlist = self.etree.fromstringlist 685 686 root = fromstringlist(list('<doc>This is a text.</doc>')) 687 self.assertEquals(0, len(root)) 688 self.assertEquals('This is a text.', root.text)
689 690 required_versions_ET['test_fromstringlist_single'] = (1,3)
691 - def test_fromstringlist_single(self):
692 fromstringlist = self.etree.fromstringlist 693 694 root = fromstringlist(['<doc>This is a text.</doc>']) 695 self.assertEquals(0, len(root)) 696 self.assertEquals('This is a text.', root.text)
697
698 - def test_iselement(self):
699 iselement = self.etree.iselement 700 Element = self.etree.Element 701 ElementTree = self.etree.ElementTree 702 XML = self.etree.XML 703 Comment = self.etree.Comment 704 ProcessingInstruction = self.etree.ProcessingInstruction 705 706 el = Element('hoi') 707 self.assert_(iselement(el)) 708 709 el2 = XML(_bytes('<foo/>')) 710 self.assert_(iselement(el2)) 711 712 tree = ElementTree(element=Element('dag')) 713 self.assert_(not iselement(tree)) 714 self.assert_(iselement(tree.getroot())) 715 716 c = Comment('test') 717 self.assert_(iselement(c)) 718 719 p = ProcessingInstruction("test", "some text") 720 self.assert_(iselement(p))
721
722 - def test_iteration(self):
723 XML = self.etree.XML 724 725 root = XML(_bytes('<doc><one/><two>Two</two>Hm<three/></doc>')) 726 result = [] 727 for el in root: 728 result.append(el.tag) 729 self.assertEquals(['one', 'two', 'three'], result)
730
731 - def test_iteration_empty(self):
732 XML = self.etree.XML 733 734 root = XML(_bytes('<doc></doc>')) 735 result = [] 736 for el in root: 737 result.append(el.tag) 738 self.assertEquals([], result)
739
740 - def test_iteration_text_only(self):
741 XML = self.etree.XML 742 743 root = XML(_bytes('<doc>Text</doc>')) 744 result = [] 745 for el in root: 746 result.append(el.tag) 747 self.assertEquals([], result)
748
749 - def test_iteration_crash(self):
750 # this would cause a crash in the past 751 fromstring = self.etree.fromstring 752 root = etree.fromstring('<html><p></p>x</html>') 753 for elem in root: 754 elem.tail = ''
755
756 - def test_iteration_reversed(self):
757 XML = self.etree.XML 758 root = XML(_bytes('<doc><one/><two>Two</two>Hm<three/></doc>')) 759 result = [] 760 for el in reversed(root): 761 result.append(el.tag) 762 self.assertEquals(['three', 'two', 'one'], result)
763
764 - def test_iteration_subelement(self):
765 XML = self.etree.XML 766 767 root = XML(_bytes('<doc><one/><two>Two</two>Hm<three/></doc>')) 768 result = [] 769 add = True 770 for el in root: 771 result.append(el.tag) 772 if add: 773 self.etree.SubElement(root, 'four') 774 add = False 775 self.assertEquals(['one', 'two', 'three', 'four'], result)
776
777 - def test_iteration_del_child(self):
778 XML = self.etree.XML 779 780 root = XML(_bytes('<doc><one/><two>Two</two>Hm<three/></doc>')) 781 result = [] 782 for el in root: 783 result.append(el.tag) 784 del root[-1] 785 self.assertEquals(['one', 'two'], result)
786
787 - def test_iteration_double(self):
788 XML = self.etree.XML 789 790 root = XML(_bytes('<doc><one/><two/></doc>')) 791 result = [] 792 for el0 in root: 793 result.append(el0.tag) 794 for el1 in root: 795 result.append(el1.tag) 796 self.assertEquals(['one','one', 'two', 'two', 'one', 'two'], result)
797 798 required_versions_ET['test_itertext'] = (1,3)
799 - def test_itertext(self):
800 # ET 1.3+ 801 XML = self.etree.XML 802 root = XML(_bytes("<root>RTEXT<a></a>ATAIL<b/><c>CTEXT</c>CTAIL</root>")) 803 804 text = list(root.itertext()) 805 self.assertEquals(["RTEXT", "ATAIL", "CTEXT", "CTAIL"], 806 text)
807 808 required_versions_ET['test_itertext_child'] = (1,3)
809 - def test_itertext_child(self):
810 # ET 1.3+ 811 XML = self.etree.XML 812 root = XML(_bytes("<root>RTEXT<a></a>ATAIL<b/><c>CTEXT</c>CTAIL</root>")) 813 814 text = list(root[2].itertext()) 815 self.assertEquals(["CTEXT"], 816 text)
817
818 - def test_findall(self):
819 XML = self.etree.XML 820 root = XML(_bytes('<a><b><c/></b><b/><c><b/></c></a>')) 821 self.assertEquals(len(list(root.findall("c"))), 1) 822 self.assertEquals(len(list(root.findall(".//c"))), 2) 823 self.assertEquals(len(list(root.findall(".//b"))), 3) 824 self.assertEquals(len(list(root.findall(".//b"))[0]), 1) 825 self.assertEquals(len(list(root.findall(".//b"))[1]), 0) 826 self.assertEquals(len(list(root.findall(".//b"))[2]), 0)
827
828 - def test_findall_ns(self):
829 XML = self.etree.XML 830 root = XML(_bytes('<a xmlns:x="X" xmlns:y="Y"><x:b><c/></x:b><b/><c><x:b/><b/></c><b/></a>')) 831 self.assertEquals(len(list(root.findall(".//{X}b"))), 2) 832 self.assertEquals(len(list(root.findall(".//b"))), 3) 833 self.assertEquals(len(list(root.findall("b"))), 2)
834
835 - def test_element_with_attributes_keywords(self):
836 Element = self.etree.Element 837 838 el = Element('tag', foo='Foo', bar='Bar') 839 self.assertEquals('Foo', el.attrib['foo']) 840 self.assertEquals('Bar', el.attrib['bar'])
841
842 - def test_element_with_attributes(self):
843 Element = self.etree.Element 844 845 el = Element('tag', {'foo':'Foo', 'bar':'Bar'}) 846 self.assertEquals('Foo', el.attrib['foo']) 847 self.assertEquals('Bar', el.attrib['bar'])
848
849 - def test_element_with_attributes_ns(self):
850 Element = self.etree.Element 851 852 el = Element('tag', {'{ns1}foo':'Foo', '{ns2}bar':'Bar'}) 853 self.assertEquals('Foo', el.attrib['{ns1}foo']) 854 self.assertEquals('Bar', el.attrib['{ns2}bar'])
855
856 - def test_subelement_with_attributes(self):
857 Element = self.etree.Element 858 SubElement = self.etree.SubElement 859 860 el = Element('tag') 861 SubElement(el, 'foo', {'foo':'Foo'}, baz="Baz") 862 self.assertEquals("Baz", el[0].attrib['baz']) 863 self.assertEquals('Foo', el[0].attrib['foo'])
864
865 - def test_subelement_with_attributes_ns(self):
866 Element = self.etree.Element 867 SubElement = self.etree.SubElement 868 869 el = Element('tag') 870 SubElement(el, 'foo', {'{ns1}foo':'Foo', '{ns2}bar':'Bar'}) 871 self.assertEquals('Foo', el[0].attrib['{ns1}foo']) 872 self.assertEquals('Bar', el[0].attrib['{ns2}bar'])
873
874 - def test_write(self):
875 ElementTree = self.etree.ElementTree 876 XML = self.etree.XML 877 878 for i in range(10): 879 f = BytesIO() 880 root = XML(_bytes('<doc%s>This is a test.</doc%s>' % (i, i))) 881 tree = ElementTree(element=root) 882 tree.write(f) 883 data = f.getvalue() 884 self.assertEquals( 885 _bytes('<doc%s>This is a test.</doc%s>' % (i, i)), 886 canonicalize(data))
887 888 required_versions_ET['test_write_method_html'] = (1,3)
889 - def test_write_method_html(self):
890 ElementTree = self.etree.ElementTree 891 Element = self.etree.Element 892 SubElement = self.etree.SubElement 893 894 html = Element('html') 895 body = SubElement(html, 'body') 896 p = SubElement(body, 'p') 897 p.text = "html" 898 SubElement(p, 'br').tail = "test" 899 900 tree = ElementTree(element=html) 901 f = BytesIO() 902 tree.write(f, method="html") 903 data = f.getvalue().replace(_bytes('\n'),_bytes('')) 904 905 self.assertEquals(_bytes('<html><body><p>html<br>test</p></body></html>'), 906 data)
907 908 required_versions_ET['test_write_method_text'] = (1,3)
909 - def test_write_method_text(self):
910 ElementTree = self.etree.ElementTree 911 Element = self.etree.Element 912 SubElement = self.etree.SubElement 913 914 a = Element('a') 915 a.text = "A" 916 a.tail = "tail" 917 b = SubElement(a, 'b') 918 b.text = "B" 919 b.tail = "TAIL" 920 c = SubElement(a, 'c') 921 c.text = "C" 922 923 tree = ElementTree(element=a) 924 f = BytesIO() 925 tree.write(f, method="text") 926 data = f.getvalue() 927 928 self.assertEquals(_bytes('ABTAILCtail'), 929 data)
930
931 - def test_write_fail(self):
932 ElementTree = self.etree.ElementTree 933 XML = self.etree.XML 934 935 tree = ElementTree( XML(_bytes('<doc>This is a test.</doc>')) ) 936 self.assertRaises(IOError, tree.write, 937 "definitely////\\-\\nonexisting\\-\\////FILE")
938 939 # this could trigger a crash, apparently because the document 940 # reference was prematurely garbage collected
941 - def test_crash(self):
942 Element = self.etree.Element 943 944 element = Element('tag') 945 for i in range(10): 946 element.attrib['key'] = 'value' 947 value = element.attrib['key'] 948 self.assertEquals(value, 'value')
949 950 # from doctest; for some reason this caused crashes too
951 - def test_write_ElementTreeDoctest(self):
952 Element = self.etree.Element 953 ElementTree = self.etree.ElementTree 954 955 f = BytesIO() 956 for i in range(10): 957 element = Element('tag%s' % i) 958 self._check_element(element) 959 tree = ElementTree(element) 960 tree.write(f) 961 self._check_element_tree(tree)
962
963 - def test_subelement_reference(self):
964 Element = self.etree.Element 965 SubElement = self.etree.SubElement 966 967 el = Element('foo') 968 el2 = SubElement(el, 'bar') 969 el3 = SubElement(el2, 'baz') 970 971 al = Element('foo2') 972 al2 = SubElement(al, 'bar2') 973 al3 = SubElement(al2, 'baz2') 974 975 # now move al2 into el 976 el.append(al2) 977 978 # now change al3 directly 979 al3.text = 'baz2-modified' 980 981 # it should have changed through this route too 982 self.assertEquals( 983 'baz2-modified', 984 el[1][0].text)
985
986 - def test_set_text(self):
987 Element = self.etree.Element 988 SubElement = self.etree.SubElement 989 990 a = Element('a') 991 b = SubElement(a, 'b') 992 a.text = 'hoi' 993 self.assertEquals( 994 'hoi', 995 a.text) 996 self.assertEquals( 997 'b', 998 a[0].tag)
999
1000 - def test_set_text2(self):
1001 Element = self.etree.Element 1002 SubElement = self.etree.SubElement 1003 1004 a = Element('a') 1005 a.text = 'hoi' 1006 b = SubElement(a ,'b') 1007 self.assertEquals( 1008 'hoi', 1009 a.text) 1010 self.assertEquals( 1011 'b', 1012 a[0].tag)
1013
1014 - def test_set_text_none(self):
1015 Element = self.etree.Element 1016 1017 a = Element('a') 1018 1019 a.text = 'foo' 1020 a.text = None 1021 1022 self.assertEquals( 1023 None, 1024 a.text) 1025 self.assertXML(_bytes('<a></a>'), a)
1026
1027 - def test_set_text_empty(self):
1028 Element = self.etree.Element 1029 1030 a = Element('a') 1031 self.assertEquals(None, a.text) 1032 1033 a.text = '' 1034 self.assertEquals('', a.text) 1035 self.assertXML(_bytes('<a></a>'), a)
1036
1037 - def test_tail1(self):
1038 Element = self.etree.Element 1039 SubElement = self.etree.SubElement 1040 1041 a = Element('a') 1042 a.tail = 'dag' 1043 self.assertEquals('dag', 1044 a.tail) 1045 b = SubElement(a, 'b') 1046 b.tail = 'hoi' 1047 self.assertEquals('hoi', 1048 b.tail) 1049 self.assertEquals('dag', 1050 a.tail)
1051
1052 - def test_tail_append(self):
1053 Element = self.etree.Element 1054 1055 a = Element('a') 1056 b = Element('b') 1057 b.tail = 'b_tail' 1058 a.append(b) 1059 self.assertEquals('b_tail', 1060 b.tail)
1061
1062 - def test_tail_set_twice(self):
1063 Element = self.etree.Element 1064 SubElement = self.etree.SubElement 1065 1066 a = Element('a') 1067 b = SubElement(a, 'b') 1068 b.tail = 'foo' 1069 b.tail = 'bar' 1070 self.assertEquals('bar', 1071 b.tail) 1072 self.assertXML(_bytes('<a><b></b>bar</a>'), a)
1073
1074 - def test_tail_set_none(self):
1075 Element = self.etree.Element 1076 a = Element('a') 1077 a.tail = 'foo' 1078 a.tail = None 1079 self.assertEquals( 1080 None, 1081 a.tail) 1082 self.assertXML(_bytes('<a></a>'), a)
1083 1084 required_versions_ET['test_extend'] = (1,3)
1085 - def test_extend(self):
1086 root = self.etree.Element('foo') 1087 for i in range(3): 1088 element = self.etree.SubElement(root, 'a%s' % i) 1089 element.text = "text%d" % i 1090 element.tail = "tail%d" % i 1091 1092 elements = [] 1093 for i in range(3): 1094 new_element = self.etree.Element("test%s" % i) 1095 new_element.text = "TEXT%s" % i 1096 new_element.tail = "TAIL%s" % i 1097 elements.append(new_element) 1098 1099 root.extend(elements) 1100 1101 self.assertEquals( 1102 ["a0", "a1", "a2", "test0", "test1", "test2"], 1103 [ el.tag for el in root ]) 1104 self.assertEquals( 1105 ["text0", "text1", "text2", "TEXT0", "TEXT1", "TEXT2"], 1106 [ el.text for el in root ]) 1107 self.assertEquals( 1108 ["tail0", "tail1", "tail2", "TAIL0", "TAIL1", "TAIL2"], 1109 [ el.tail for el in root ])
1110
1111 - def test_comment(self):
1112 Element = self.etree.Element 1113 SubElement = self.etree.SubElement 1114 Comment = self.etree.Comment 1115 1116 a = Element('a') 1117 a.append(Comment('foo')) 1118 self.assertEquals(a[0].tag, Comment) 1119 self.assertEquals(a[0].text, 'foo')
1120 1121 # ElementTree < 1.3 adds whitespace around comments 1122 required_versions_ET['test_comment_text'] = (1,3)
1123 - def test_comment_text(self):
1124 Element = self.etree.Element 1125 SubElement = self.etree.SubElement 1126 Comment = self.etree.Comment 1127 tostring = self.etree.tostring 1128 1129 a = Element('a') 1130 a.append(Comment('foo')) 1131 self.assertEquals(a[0].text, 'foo') 1132 1133 self.assertEquals( 1134 _bytes('<a><!--foo--></a>'), 1135 tostring(a)) 1136 1137 a[0].text = "TEST" 1138 self.assertEquals(a[0].text, 'TEST') 1139 1140 self.assertEquals( 1141 _bytes('<a><!--TEST--></a>'), 1142 tostring(a))
1143 1144 # ElementTree < 1.3 adds whitespace around comments 1145 required_versions_ET['test_comment_whitespace'] = (1,3)
1146 - def test_comment_whitespace(self):
1147 Element = self.etree.Element 1148 SubElement = self.etree.SubElement 1149 Comment = self.etree.Comment 1150 tostring = self.etree.tostring 1151 1152 a = Element('a') 1153 a.append(Comment(' foo ')) 1154 self.assertEquals(a[0].text, ' foo ') 1155 self.assertEquals( 1156 _bytes('<a><!-- foo --></a>'), 1157 tostring(a))
1158
1159 - def test_comment_nonsense(self):
1160 Comment = self.etree.Comment 1161 c = Comment('foo') 1162 self.assertEquals({}, c.attrib) 1163 self.assertEquals([], list(c.keys())) 1164 self.assertEquals([], list(c.items())) 1165 self.assertEquals(None, c.get('hoi')) 1166 self.assertEquals(0, len(c)) 1167 # should not iterate 1168 for i in c: 1169 pass
1170
1171 - def test_pi(self):
1172 # lxml.etree separates target and text 1173 Element = self.etree.Element 1174 SubElement = self.etree.SubElement 1175 ProcessingInstruction = self.etree.ProcessingInstruction 1176 1177 a = Element('a') 1178 a.append(ProcessingInstruction('foo', 'some more text')) 1179 self.assertEquals(a[0].tag, ProcessingInstruction) 1180 self.assertXML(_bytes("<a><?foo some more text?></a>"), 1181 a)
1182
1183 - def test_processinginstruction(self):
1184 # lxml.etree separates target and text 1185 Element = self.etree.Element 1186 SubElement = self.etree.SubElement 1187 ProcessingInstruction = self.etree.PI 1188 1189 a = Element('a') 1190 a.append(ProcessingInstruction('foo', 'some more text')) 1191 self.assertEquals(a[0].tag, ProcessingInstruction) 1192 self.assertXML(_bytes("<a><?foo some more text?></a>"), 1193 a)
1194
1195 - def test_pi_nonsense(self):
1196 ProcessingInstruction = self.etree.ProcessingInstruction 1197 pi = ProcessingInstruction('foo') 1198 self.assertEquals({}, pi.attrib) 1199 self.assertEquals([], list(pi.keys())) 1200 self.assertEquals([], list(pi.items())) 1201 self.assertEquals(None, pi.get('hoi')) 1202 self.assertEquals(0, len(pi)) 1203 # should not iterate 1204 for i in pi: 1205 pass
1206
1207 - def test_setitem(self):
1208 Element = self.etree.Element 1209 SubElement = self.etree.SubElement 1210 1211 a = Element('a') 1212 b = SubElement(a, 'b') 1213 c = Element('c') 1214 a[0] = c 1215 self.assertEquals( 1216 c, 1217 a[0]) 1218 self.assertXML(_bytes('<a><c></c></a>'), 1219 a) 1220 self.assertXML(_bytes('<b></b>'), 1221 b)
1222
1223 - def test_setitem2(self):
1224 Element = self.etree.Element 1225 SubElement = self.etree.SubElement 1226 1227 a = Element('a') 1228 for i in range(5): 1229 b = SubElement(a, 'b%s' % i) 1230 c = SubElement(b, 'c') 1231 for i in range(5): 1232 d = Element('d') 1233 e = SubElement(d, 'e') 1234 a[i] = d 1235 self.assertXML( 1236 _bytes('<a><d><e></e></d><d><e></e></d><d><e></e></d><d><e></e></d><d><e></e></d></a>'), 1237 a) 1238 self.assertXML(_bytes('<c></c>'), 1239 c)
1240
1241 - def test_setitem_replace(self):
1242 Element = self.etree.Element 1243 SubElement = self.etree.SubElement 1244 1245 a = Element('a') 1246 SubElement(a, 'b') 1247 d = Element('d') 1248 a[0] = d 1249 self.assertXML(_bytes('<a><d></d></a>'), a)
1250
1251 - def test_setitem_indexerror(self):
1252 Element = self.etree.Element 1253 SubElement = self.etree.SubElement 1254 1255 a = Element('a') 1256 b = SubElement(a, 'b') 1257 1258 self.assertRaises(IndexError, operator.setitem, a, 1, Element('c'))
1259
1260 - def test_setitem_tail(self):
1261 Element = self.etree.Element 1262 SubElement = self.etree.SubElement 1263 1264 a = Element('a') 1265 b = SubElement(a, 'b') 1266 b.tail = 'B2' 1267 c = Element('c') 1268 c.tail = 'C2' 1269 1270 a[0] = c 1271 self.assertXML( 1272 _bytes('<a><c></c>C2</a>'), 1273 a)
1274
1275 - def test_tag_write(self):
1276 Element = self.etree.Element 1277 SubElement = self.etree.SubElement 1278 1279 a = Element('a') 1280 b = SubElement(a, 'b') 1281 1282 a.tag = 'c' 1283 1284 self.assertEquals( 1285 'c', 1286 a.tag) 1287 1288 self.assertXML( 1289 _bytes('<c><b></b></c>'), 1290 a)
1291
1292 - def test_tag_reset_ns(self):
1293 Element = self.etree.Element 1294 SubElement = self.etree.SubElement 1295 tostring = self.etree.tostring 1296 1297 a = Element('{a}a') 1298 b1 = SubElement(a, '{a}b') 1299 b2 = SubElement(a, '{b}b') 1300 1301 self.assertEquals('{a}b', b1.tag) 1302 1303 b1.tag = 'c' 1304 1305 # can't use C14N here! 1306 self.assertEquals('c', b1.tag) 1307 self.assertEquals(_bytes('<c'), tostring(b1)[:2]) 1308 self.assert_(_bytes('<c') in tostring(a))
1309
1310 - def test_tag_reset_root_ns(self):
1311 Element = self.etree.Element 1312 SubElement = self.etree.SubElement 1313 tostring = self.etree.tostring 1314 1315 a = Element('{a}a') 1316 b1 = SubElement(a, '{a}b') 1317 b2 = SubElement(a, '{b}b') 1318 1319 a.tag = 'c' 1320 1321 self.assertEquals( 1322 'c', 1323 a.tag) 1324 1325 # can't use C14N here! 1326 self.assertEquals('c', a.tag) 1327 self.assertEquals(_bytes('<c'), tostring(a)[:2])
1328
1329 - def test_tag_str_subclass(self):
1330 Element = self.etree.Element 1331 1332 class strTest(str): 1333 pass
1334 1335 a = Element("a") 1336 a.tag = strTest("TAG") 1337 self.assertXML(_bytes('<TAG></TAG>'), 1338 a) 1339
1340 - def test_delitem(self):
1341 Element = self.etree.Element 1342 SubElement = self.etree.SubElement 1343 1344 a = Element('a') 1345 b = SubElement(a, 'b') 1346 c = SubElement(a, 'c') 1347 d = SubElement(a, 'd') 1348 1349 del a[1] 1350 self.assertXML( 1351 _bytes('<a><b></b><d></d></a>'), 1352 a) 1353 1354 del a[0] 1355 self.assertXML( 1356 _bytes('<a><d></d></a>'), 1357 a) 1358 1359 del a[0] 1360 self.assertXML( 1361 _bytes('<a></a>'), 1362 a) 1363 # move deleted element into other tree afterwards 1364 other = Element('other') 1365 other.append(c) 1366 self.assertXML( 1367 _bytes('<other><c></c></other>'), 1368 other)
1369
1370 - def test_del_insert(self):
1371 Element = self.etree.Element 1372 SubElement = self.etree.SubElement 1373 1374 a = Element('a') 1375 b = SubElement(a, 'b') 1376 bs = SubElement(b, 'bs') 1377 c = SubElement(a, 'c') 1378 cs = SubElement(c, 'cs') 1379 1380 el = a[0] 1381 self.assertXML( 1382 _bytes('<a><b><bs></bs></b><c><cs></cs></c></a>'), 1383 a) 1384 self.assertXML(_bytes('<b><bs></bs></b>'), b) 1385 self.assertXML(_bytes('<c><cs></cs></c>'), c) 1386 1387 del a[0] 1388 self.assertXML( 1389 _bytes('<a><c><cs></cs></c></a>'), 1390 a) 1391 self.assertXML(_bytes('<b><bs></bs></b>'), b) 1392 self.assertXML(_bytes('<c><cs></cs></c>'), c) 1393 1394 a.insert(0, el) 1395 self.assertXML( 1396 _bytes('<a><b><bs></bs></b><c><cs></cs></c></a>'), 1397 a) 1398 self.assertXML(_bytes('<b><bs></bs></b>'), b) 1399 self.assertXML(_bytes('<c><cs></cs></c>'), c)
1400
1401 - def test_del_setitem(self):
1402 Element = self.etree.Element 1403 SubElement = self.etree.SubElement 1404 1405 a = Element('a') 1406 b = SubElement(a, 'b') 1407 bs = SubElement(b, 'bs') 1408 c = SubElement(a, 'c') 1409 cs = SubElement(c, 'cs') 1410 1411 el = a[0] 1412 del a[0] 1413 a[0] = el 1414 self.assertXML( 1415 _bytes('<a><b><bs></bs></b></a>'), 1416 a) 1417 self.assertXML(_bytes('<b><bs></bs></b>'), b) 1418 self.assertXML(_bytes('<c><cs></cs></c>'), c)
1419
1420 - def test_del_setslice(self):
1421 Element = self.etree.Element 1422 SubElement = self.etree.SubElement 1423 1424 a = Element('a') 1425 b = SubElement(a, 'b') 1426 bs = SubElement(b, 'bs') 1427 c = SubElement(a, 'c') 1428 cs = SubElement(c, 'cs') 1429 1430 el = a[0] 1431 del a[0] 1432 a[0:0] = [el] 1433 self.assertXML( 1434 _bytes('<a><b><bs></bs></b><c><cs></cs></c></a>'), 1435 a) 1436 self.assertXML(_bytes('<b><bs></bs></b>'), b) 1437 self.assertXML(_bytes('<c><cs></cs></c>'), c)
1438
1439 - def test_replace_slice_tail(self):
1440 XML = self.etree.XML 1441 a = XML(_bytes('<a><b></b>B2<c></c>C2</a>')) 1442 b, c = a 1443 1444 a[:] = [] 1445 1446 self.assertEquals("B2", b.tail) 1447 self.assertEquals("C2", c.tail)
1448
1449 - def test_merge_namespaced_subtree_as_slice(self):
1450 XML = self.etree.XML 1451 root = XML(_bytes( 1452 '<foo><bar xmlns:baz="http://huhu"><puh><baz:bump1 /><baz:bump2 /></puh></bar></foo>')) 1453 root[:] = root.findall('.//puh') # delete bar from hierarchy 1454 1455 # previously, this lost a namespace declaration on bump2 1456 result = self.etree.tostring(root) 1457 foo = self.etree.fromstring(result) 1458 1459 self.assertEquals('puh', foo[0].tag) 1460 self.assertEquals('{http://huhu}bump1', foo[0][0].tag) 1461 self.assertEquals('{http://huhu}bump2', foo[0][1].tag)
1462
1463 - def test_delitem_tail(self):
1464 ElementTree = self.etree.ElementTree 1465 f = BytesIO('<a><b></b>B2<c></c>C2</a>') 1466 doc = ElementTree(file=f) 1467 a = doc.getroot() 1468 del a[0] 1469 self.assertXML( 1470 _bytes('<a><c></c>C2</a>'), 1471 a)
1472
1473 - def test_clear(self):
1474 Element = self.etree.Element 1475 1476 a = Element('a') 1477 a.text = 'foo' 1478 a.tail = 'bar' 1479 a.set('hoi', 'dag') 1480 a.clear() 1481 self.assertEquals(None, a.text) 1482 self.assertEquals(None, a.tail) 1483 self.assertEquals(None, a.get('hoi')) 1484 self.assertEquals('a', a.tag)
1485
1486 - def test_clear_sub(self):
1487 Element = self.etree.Element 1488 SubElement = self.etree.SubElement 1489 1490 a = Element('a') 1491 a.text = 'foo' 1492 a.tail = 'bar' 1493 a.set('hoi', 'dag') 1494 b = SubElement(a, 'b') 1495 c = SubElement(b, 'c') 1496 a.clear() 1497 self.assertEquals(None, a.text) 1498 self.assertEquals(None, a.tail) 1499 self.assertEquals(None, a.get('hoi')) 1500 self.assertEquals('a', a.tag) 1501 self.assertEquals(0, len(a)) 1502 self.assertXML(_bytes('<a></a>'), 1503 a) 1504 self.assertXML(_bytes('<b><c></c></b>'), 1505 b)
1506
1507 - def test_clear_tail(self):
1508 ElementTree = self.etree.ElementTree 1509 f = BytesIO('<a><b></b>B2<c></c>C2</a>') 1510 doc = ElementTree(file=f) 1511 a = doc.getroot() 1512 a.clear() 1513 self.assertXML( 1514 _bytes('<a></a>'), 1515 a)
1516
1517 - def test_insert(self):
1518 Element = self.etree.Element 1519 SubElement = self.etree.SubElement 1520 1521 a = Element('a') 1522 b = SubElement(a, 'b') 1523 c = SubElement(a, 'c') 1524 d = Element('d') 1525 a.insert(0, d) 1526 1527 self.assertEquals( 1528 d, 1529 a[0]) 1530 1531 self.assertXML( 1532 _bytes('<a><d></d><b></b><c></c></a>'), 1533 a) 1534 1535 e = Element('e') 1536 a.insert(2, e) 1537 self.assertEquals( 1538 e, 1539 a[2]) 1540 self.assertXML( 1541 _bytes('<a><d></d><b></b><e></e><c></c></a>'), 1542 a)
1543
1544 - def test_insert_beyond_index(self):
1545 Element = self.etree.Element 1546 SubElement = self.etree.SubElement 1547 1548 a = Element('a') 1549 b = SubElement(a, 'b') 1550 c = Element('c') 1551 1552 a.insert(2, c) 1553 self.assertEquals( 1554 c, 1555 a[1]) 1556 self.assertXML( 1557 _bytes('<a><b></b><c></c></a>'), 1558 a)
1559
1560 - def test_insert_negative(self):
1561 Element = self.etree.Element 1562 SubElement = self.etree.SubElement 1563 1564 a = Element('a') 1565 b = SubElement(a, 'b') 1566 c = SubElement(a, 'c') 1567 1568 d = Element('d') 1569 a.insert(-1, d) 1570 self.assertEquals( 1571 d, 1572 a[-2]) 1573 self.assertXML( 1574 _bytes('<a><b></b><d></d><c></c></a>'), 1575 a)
1576
1577 - def test_insert_tail(self):
1578 Element = self.etree.Element 1579 SubElement = self.etree.SubElement 1580 1581 a = Element('a') 1582 b = SubElement(a, 'b') 1583 1584 c = Element('c') 1585 c.tail = 'C2' 1586 1587 a.insert(0, c) 1588 self.assertXML( 1589 _bytes('<a><c></c>C2<b></b></a>'), 1590 a)
1591
1592 - def test_remove(self):
1593 Element = self.etree.Element 1594 SubElement = self.etree.SubElement 1595 1596 a = Element('a') 1597 b = SubElement(a, 'b') 1598 c = SubElement(a, 'c') 1599 1600 a.remove(b) 1601 self.assertEquals( 1602 c, 1603 a[0]) 1604 self.assertXML( 1605 _bytes('<a><c></c></a>'), 1606 a)
1607
1608 - def test_remove_ns(self):
1609 Element = self.etree.Element 1610 SubElement = self.etree.SubElement 1611 1612 a = Element('{http://test}a') 1613 b = SubElement(a, '{http://test}b') 1614 c = SubElement(a, '{http://test}c') 1615 1616 a.remove(b) 1617 self.assertXML( 1618 _bytes('<ns0:a xmlns:ns0="http://test"><ns0:c></ns0:c></ns0:a>'), 1619 a) 1620 self.assertXML( 1621 _bytes('<ns0:b xmlns:ns0="http://test"></ns0:b>'), 1622 b)
1623
1624 - def test_remove_nonexisting(self):
1625 Element = self.etree.Element 1626 SubElement = self.etree.SubElement 1627 1628 a = Element('a') 1629 b = SubElement(a, 'b') 1630 c = SubElement(a, 'c') 1631 d = Element('d') 1632 self.assertRaises( 1633 ValueError, a.remove, d)
1634
1635 - def test_remove_tail(self):
1636 Element = self.etree.Element 1637 SubElement = self.etree.SubElement 1638 1639 a = Element('a') 1640 b = SubElement(a, 'b') 1641 b.tail = 'b2' 1642 a.remove(b) 1643 self.assertXML( 1644 _bytes('<a></a>'), 1645 a) 1646 self.assertEquals('b2', b.tail)
1647
1648 - def _test_getchildren(self):
1649 Element = self.etree.Element 1650 SubElement = self.etree.SubElement 1651 1652 a = Element('a') 1653 b = SubElement(a, 'b') 1654 c = SubElement(a, 'c') 1655 d = SubElement(b, 'd') 1656 e = SubElement(c, 'e') 1657 self.assertXML( 1658 _bytes('<a><b><d></d></b><c><e></e></c></a>'), 1659 a) 1660 self.assertEquals( 1661 [b, c], 1662 a.getchildren()) 1663 self.assertEquals( 1664 [d], 1665 b.getchildren()) 1666 self.assertEquals( 1667 [], 1668 d.getchildren())
1669
1670 - def test_makeelement(self):
1671 Element = self.etree.Element 1672 1673 a = Element('a') 1674 b = a.makeelement('c', {'hoi':'dag'}) 1675 self.assertXML( 1676 _bytes('<c hoi="dag"></c>'), 1677 b)
1678 1679 required_versions_ET['test_iter'] = (1,3)
1680 - def test_iter(self):
1681 Element = self.etree.Element 1682 SubElement = self.etree.SubElement 1683 1684 a = Element('a') 1685 b = SubElement(a, 'b') 1686 c = SubElement(a, 'c') 1687 d = SubElement(b, 'd') 1688 e = SubElement(c, 'e') 1689 1690 self.assertEquals( 1691 [a, b, d, c, e], 1692 list(a.iter())) 1693 self.assertEquals( 1694 [d], 1695 list(d.iter()))
1696
1697 - def test_getiterator(self):
1698 Element = self.etree.Element 1699 SubElement = self.etree.SubElement 1700 1701 a = Element('a') 1702 b = SubElement(a, 'b') 1703 c = SubElement(a, 'c') 1704 d = SubElement(b, 'd') 1705 e = SubElement(c, 'e') 1706 1707 self.assertEquals( 1708 [a, b, d, c, e], 1709 list(a.getiterator())) 1710 self.assertEquals( 1711 [d], 1712 list(d.getiterator()))
1713
1714 - def test_getiterator_empty(self):
1715 Element = self.etree.Element 1716 SubElement = self.etree.SubElement 1717 1718 a = Element('a') 1719 b = SubElement(a, 'b') 1720 c = SubElement(a, 'c') 1721 d = SubElement(b, 'd') 1722 e = SubElement(c, 'e') 1723 1724 self.assertEquals( 1725 [], 1726 list(a.getiterator('none'))) 1727 self.assertEquals( 1728 [], 1729 list(e.getiterator('none'))) 1730 self.assertEquals( 1731 [e], 1732 list(e.getiterator()))
1733
1734 - def test_getiterator_filter(self):
1735 Element = self.etree.Element 1736 SubElement = self.etree.SubElement 1737 1738 a = Element('a') 1739 b = SubElement(a, 'b') 1740 c = SubElement(a, 'c') 1741 d = SubElement(b, 'd') 1742 e = SubElement(c, 'e') 1743 1744 self.assertEquals( 1745 [a], 1746 list(a.getiterator('a'))) 1747 a2 = SubElement(e, 'a') 1748 self.assertEquals( 1749 [a, a2], 1750 list(a.getiterator('a'))) 1751 self.assertEquals( 1752 [a2], 1753 list(c.getiterator('a')))
1754
1755 - def test_getiterator_filter_all(self):
1756 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.assertEquals( 1766 [a, b, d, c, e], 1767 list(a.getiterator('*')))
1768
1769 - def test_getiterator_filter_comment(self):
1770 Element = self.etree.Element 1771 Comment = self.etree.Comment 1772 SubElement = self.etree.SubElement 1773 1774 a = Element('a') 1775 b = SubElement(a, 'b') 1776 comment_b = Comment("TEST-b") 1777 b.append(comment_b) 1778 1779 self.assertEquals( 1780 [comment_b], 1781 list(a.getiterator(Comment))) 1782 1783 comment_a = Comment("TEST-a") 1784 a.append(comment_a) 1785 1786 self.assertEquals( 1787 [comment_b, comment_a], 1788 list(a.getiterator(Comment))) 1789 1790 self.assertEquals( 1791 [comment_b], 1792 list(b.getiterator(Comment)))
1793
1794 - def test_getiterator_filter_pi(self):
1795 Element = self.etree.Element 1796 PI = self.etree.ProcessingInstruction 1797 SubElement = self.etree.SubElement 1798 1799 a = Element('a') 1800 b = SubElement(a, 'b') 1801 pi_b = PI("TEST-b") 1802 b.append(pi_b) 1803 1804 self.assertEquals( 1805 [pi_b], 1806 list(a.getiterator(PI))) 1807 1808 pi_a = PI("TEST-a") 1809 a.append(pi_a) 1810 1811 self.assertEquals( 1812 [pi_b, pi_a], 1813 list(a.getiterator(PI))) 1814 1815 self.assertEquals( 1816 [pi_b], 1817 list(b.getiterator(PI)))
1818
1819 - def test_getiterator_with_text(self):
1820 Element = self.etree.Element 1821 SubElement = self.etree.SubElement 1822 1823 a = Element('a') 1824 a.text = 'a' 1825 b = SubElement(a, 'b') 1826 b.text = 'b' 1827 b.tail = 'b1' 1828 c = SubElement(a, 'c') 1829 c.text = 'c' 1830 c.tail = 'c1' 1831 d = SubElement(b, 'd') 1832 c.text = 'd' 1833 c.tail = 'd1' 1834 e = SubElement(c, 'e') 1835 e.text = 'e' 1836 e.tail = 'e1' 1837 1838 self.assertEquals( 1839 [a, b, d, c, e], 1840 list(a.getiterator()))
1841 #self.assertEquals( 1842 # [d], 1843 # list(d.getiterator())) 1844
1845 - def test_getiterator_filter_with_text(self):
1846 Element = self.etree.Element 1847 SubElement = self.etree.SubElement 1848 1849 a = Element('a') 1850 a.text = 'a' 1851 b = SubElement(a, 'b') 1852 b.text = 'b' 1853 b.tail = 'b1' 1854 c = SubElement(a, 'c') 1855 c.text = 'c' 1856 c.tail = 'c1' 1857 d = SubElement(b, 'd') 1858 c.text = 'd' 1859 c.tail = 'd1' 1860 e = SubElement(c, 'e') 1861 e.text = 'e' 1862 e.tail = 'e1' 1863 1864 self.assertEquals( 1865 [a], 1866 list(a.getiterator('a'))) 1867 a2 = SubElement(e, 'a') 1868 self.assertEquals( 1869 [a, a2], 1870 list(a.getiterator('a'))) 1871 self.assertEquals( 1872 [a2], 1873 list(e.getiterator('a')))
1874
1875 - def test_getslice(self):
1876 Element = self.etree.Element 1877 SubElement = self.etree.SubElement 1878 1879 a = Element('a') 1880 b = SubElement(a, 'b') 1881 c = SubElement(a, 'c') 1882 d = SubElement(a, 'd') 1883 1884 self.assertEquals( 1885 [b, c], 1886 a[0:2]) 1887 self.assertEquals( 1888 [b, c, d], 1889 a[:]) 1890 self.assertEquals( 1891 [b, c, d], 1892 a[:10]) 1893 self.assertEquals( 1894 [b], 1895 a[0:1]) 1896 self.assertEquals( 1897 [], 1898 a[10:12])
1899
1900 - def test_getslice_negative(self):
1901 Element = self.etree.Element 1902 SubElement = self.etree.SubElement 1903 1904 a = Element('a') 1905 b = SubElement(a, 'b') 1906 c = SubElement(a, 'c') 1907 d = SubElement(a, 'd') 1908 1909 self.assertEquals( 1910 [d], 1911 a[-1:]) 1912 self.assertEquals( 1913 [c, d], 1914 a[-2:]) 1915 self.assertEquals( 1916 [c], 1917 a[-2:-1]) 1918 self.assertEquals( 1919 [b, c], 1920 a[-3:-1]) 1921 self.assertEquals( 1922 [b, c], 1923 a[-3:2])
1924
1925 - def test_getslice_step(self):
1926 Element = self.etree.Element 1927 SubElement = self.etree.SubElement 1928 1929 a = Element('a') 1930 b = SubElement(a, 'b') 1931 c = SubElement(a, 'c') 1932 d = SubElement(a, 'd') 1933 e = SubElement(a, 'e') 1934 1935 self.assertEquals( 1936 [e,d,c,b], 1937 a[::-1]) 1938 self.assertEquals( 1939 [b,d], 1940 a[::2]) 1941 self.assertEquals( 1942 [e,c], 1943 a[::-2]) 1944 self.assertEquals( 1945 [d,c], 1946 a[-2:0:-1]) 1947 self.assertEquals( 1948 [e], 1949 a[:1:-2])
1950
1951 - def test_getslice_text(self):
1952 ElementTree = self.etree.ElementTree 1953 1954 f = BytesIO('<a><b>B</b>B1<c>C</c>C1</a>') 1955 doc = ElementTree(file=f) 1956 a = doc.getroot() 1957 b = a[0] 1958 c = a[1] 1959 self.assertEquals( 1960 [b, c], 1961 a[:]) 1962 self.assertEquals( 1963 [b], 1964 a[0:1]) 1965 self.assertEquals( 1966 [c], 1967 a[1:])
1968
1969 - def test_comment_getitem_getslice(self):
1970 Element = self.etree.Element 1971 Comment = self.etree.Comment 1972 SubElement = self.etree.SubElement 1973 1974 a = Element('a') 1975 b = SubElement(a, 'b') 1976 foo = Comment('foo') 1977 a.append(foo) 1978 c = SubElement(a, 'c') 1979 self.assertEquals( 1980 [b, foo, c], 1981 a[:]) 1982 self.assertEquals( 1983 foo, 1984 a[1]) 1985 a[1] = new = Element('new') 1986 self.assertEquals( 1987 new, 1988 a[1]) 1989 self.assertXML( 1990 _bytes('<a><b></b><new></new><c></c></a>'), 1991 a)
1992
1993 - def test_delslice(self):
1994 Element = self.etree.Element 1995 SubElement = self.etree.SubElement 1996 1997 a = Element('a') 1998 b = SubElement(a, 'b') 1999 c = SubElement(a, 'c') 2000 d = SubElement(a, 'd') 2001 e = SubElement(a, 'e') 2002 2003 del a[1:3] 2004 self.assertEquals( 2005 [b, e], 2006 list(a))
2007
2008 - def test_delslice_negative1(self):
2009 Element = self.etree.Element 2010 SubElement = self.etree.SubElement 2011 2012 a = Element('a') 2013 b = SubElement(a, 'b') 2014 c = SubElement(a, 'c') 2015 d = SubElement(a, 'd') 2016 e = SubElement(a, 'e') 2017 2018 del a[1:-1] 2019 self.assertEquals( 2020 [b, e], 2021 list(a))
2022
2023 - def test_delslice_negative2(self):
2024 Element = self.etree.Element 2025 SubElement = self.etree.SubElement 2026 2027 a = Element('a') 2028 b = SubElement(a, 'b') 2029 c = SubElement(a, 'c') 2030 d = SubElement(a, 'd') 2031 e = SubElement(a, 'e') 2032 2033 del a[-3:-1] 2034 self.assertEquals( 2035 [b, e], 2036 list(a))
2037
2038 - def test_delslice_step(self):
2039 Element = self.etree.Element 2040 SubElement = self.etree.SubElement 2041 2042 a = Element('a') 2043 b = SubElement(a, 'b') 2044 c = SubElement(a, 'c') 2045 d = SubElement(a, 'd') 2046 e = SubElement(a, 'e') 2047 2048 del a[1::2] 2049 self.assertEquals( 2050 [b, d], 2051 list(a))
2052
2053 - def test_delslice_step_negative(self):
2054 Element = self.etree.Element 2055 SubElement = self.etree.SubElement 2056 2057 a = Element('a') 2058 b = SubElement(a, 'b') 2059 c = SubElement(a, 'c') 2060 d = SubElement(a, 'd') 2061 e = SubElement(a, 'e') 2062 2063 del a[::-1] 2064 self.assertEquals( 2065 [], 2066 list(a))
2067
2068 - def test_delslice_step_negative2(self):
2069 Element = self.etree.Element 2070 SubElement = self.etree.SubElement 2071 2072 a = Element('a') 2073 b = SubElement(a, 'b') 2074 c = SubElement(a, 'c') 2075 d = SubElement(a, 'd') 2076 e = SubElement(a, 'e') 2077 2078 del a[::-2] 2079 self.assertEquals( 2080 [b, d], 2081 list(a))
2082
2083 - def test_delslice_child_tail(self):
2084 ElementTree = self.etree.ElementTree 2085 f = BytesIO('<a><b></b>B2<c></c>C2<d></d>D2<e></e>E2</a>') 2086 doc = ElementTree(file=f) 2087 a = doc.getroot() 2088 del a[1:3] 2089 self.assertXML( 2090 _bytes('<a><b></b>B2<e></e>E2</a>'), 2091 a)
2092
2093 - def test_delslice_tail(self):
2094 XML = self.etree.XML 2095 a = XML(_bytes('<a><b></b>B2<c></c>C2</a>')) 2096 b, c = a 2097 2098 del a[:] 2099 2100 self.assertEquals("B2", b.tail) 2101 self.assertEquals("C2", c.tail)
2102
2103 - def test_delslice_memory(self):
2104 # this could trigger a crash 2105 Element = self.etree.Element 2106 SubElement = self.etree.SubElement 2107 a = Element('a') 2108 b = SubElement(a, 'b') 2109 c = SubElement(b, 'c') 2110 del b # no more reference to b 2111 del a[:] 2112 self.assertEquals('c', c.tag)
2113
2114 - def test_setslice(self):
2115 Element = self.etree.Element 2116 SubElement = self.etree.SubElement 2117 2118 a = Element('a') 2119 b = SubElement(a, 'b') 2120 c = SubElement(a, 'c') 2121 d = SubElement(a, 'd') 2122 2123 e = Element('e') 2124 f = Element('f') 2125 g = Element('g') 2126 2127 s = [e, f, g] 2128 a[1:2] = s 2129 self.assertEquals( 2130 [b, e, f, g, d], 2131 list(a))
2132
2133 - def test_setslice_all(self):
2134 Element = self.etree.Element 2135 SubElement = self.etree.SubElement 2136 2137 a = Element('a') 2138 b = SubElement(a, 'b') 2139 c = SubElement(a, 'c') 2140 2141 e = Element('e') 2142 f = Element('f') 2143 g = Element('g') 2144 2145 s = [e, f, g] 2146 a[:] = s 2147 self.assertEquals( 2148 [e, f, g], 2149 list(a))
2150
2151 - def test_setslice_all_empty(self):
2152 Element = self.etree.Element 2153 SubElement = self.etree.SubElement 2154 2155 a = Element('a') 2156 2157 e = Element('e') 2158 f = Element('f') 2159 g = Element('g') 2160 2161 s = [e, f, g] 2162 a[:] = s 2163 self.assertEquals( 2164 [e, f, g], 2165 list(a))
2166
2167 - def test_setslice_all_replace(self):
2168 Element = self.etree.Element 2169 SubElement = self.etree.SubElement 2170 2171 a = Element('a') 2172 b = SubElement(a, 'b') 2173 c = SubElement(a, 'c') 2174 d = SubElement(a, 'd') 2175 2176 s = [b, c, d] 2177 a[:] = s 2178 self.assertEquals( 2179 [b, c, d], 2180 list(a))
2181
2182 - def test_setslice_all_replace_reversed(self):
2183 Element = self.etree.Element 2184 SubElement = self.etree.SubElement 2185 2186 a = Element('a') 2187 b = SubElement(a, 'b') 2188 c = SubElement(a, 'c') 2189 d = SubElement(a, 'd') 2190 2191 s = [d, c, b] 2192 a[:] = s 2193 self.assertEquals( 2194 [d, c, b], 2195 list(a))
2196
2197 - def test_setslice_all_replace_reversed_ns1(self):
2198 Element = self.etree.Element 2199 SubElement = self.etree.SubElement 2200 2201 a = Element('{ns}a') 2202 b = SubElement(a, '{ns}b', {'{ns1}a1': 'test'}) 2203 c = SubElement(a, '{ns}c', {'{ns2}a2': 'test'}) 2204 d = SubElement(a, '{ns}d', {'{ns3}a3': 'test'}) 2205 2206 s = [d, c, b] 2207 a[:] = s 2208 self.assertEquals( 2209 [d, c, b], 2210 list(a)) 2211 self.assertEquals( 2212 ['{ns}d', '{ns}c', '{ns}b'], 2213 [ child.tag for child in a ]) 2214 2215 self.assertEquals( 2216 [['{ns3}a3'], ['{ns2}a2'], ['{ns1}a1']], 2217 [ list(child.attrib.keys()) for child in a ])
2218
2219 - def test_setslice_all_replace_reversed_ns2(self):
2220 Element = self.etree.Element 2221 SubElement = self.etree.SubElement 2222 2223 a = Element('{ns}a') 2224 b = SubElement(a, '{ns1}b', {'{ns}a1': 'test'}) 2225 c = SubElement(a, '{ns2}c', {'{ns}a2': 'test'}) 2226 d = SubElement(a, '{ns3}d', {'{ns}a3': 'test'}) 2227 2228 s = [d, c, b] 2229 a[:] = s 2230 self.assertEquals( 2231 [d, c, b], 2232 list(a)) 2233 self.assertEquals( 2234 ['{ns3}d', '{ns2}c', '{ns1}b'], 2235 [ child.tag for child in a ]) 2236 2237 self.assertEquals( 2238 [['{ns}a3'], ['{ns}a2'], ['{ns}a1']], 2239 [ list(child.attrib.keys()) for child in a ])
2240
2241 - def test_setslice_end(self):
2242 Element = self.etree.Element 2243 SubElement = self.etree.SubElement 2244 2245 a = Element('a') 2246 b = SubElement(a, 'b') 2247 c = SubElement(a, 'c') 2248 2249 e = Element('e') 2250 f = Element('f') 2251 g = Element('g') 2252 h = Element('h') 2253 2254 s = [e, f] 2255 a[99:] = s 2256 self.assertEquals( 2257 [a, b, e, f], 2258 list(a)) 2259 2260 s = [g, h] 2261 a[:0] = s 2262 self.assertEquals( 2263 [g, h, a, b, e, f], 2264 list(a))
2265
2266 - def test_setslice_single(self):
2267 Element = self.etree.Element 2268 SubElement = self.etree.SubElement 2269 2270 a = Element('a') 2271 b = SubElement(a, 'b') 2272 c = SubElement(a, 'c') 2273 2274 e = Element('e') 2275 f = Element('f') 2276 2277 s = [e] 2278 a[0:1] = s 2279 self.assertEquals( 2280 [e, c], 2281 list(a)) 2282 2283 s = [f] 2284 a[1:2] = s 2285 self.assertEquals( 2286 [e, f], 2287 list(a))
2288
2289 - def test_setslice_tail(self):
2290 ElementTree = self.etree.ElementTree 2291 Element = self.etree.Element 2292 f = BytesIO('<a><b></b>B2<c></c>C2<d></d>D2<e></e>E2</a>') 2293 doc = ElementTree(file=f) 2294 a = doc.getroot() 2295 x = Element('x') 2296 y = Element('y') 2297 z = Element('z') 2298 x.tail = 'X2' 2299 y.tail = 'Y2' 2300 z.tail = 'Z2' 2301 a[1:3] = [x, y, z] 2302 self.assertXML( 2303 _bytes('<a><b></b>B2<x></x>X2<y></y>Y2<z></z>Z2<e></e>E2</a>'), 2304 a)
2305
2306 - def test_setslice_negative(self):
2307 Element = self.etree.Element 2308 SubElement = self.etree.SubElement 2309 2310 a = Element('a') 2311 b = SubElement(a, 'b') 2312 c = SubElement(a, 'c') 2313 d = SubElement(a, 'd') 2314 2315 x = Element('x') 2316 y = Element('y') 2317 2318 a[1:-1] = [x, y] 2319 self.assertEquals( 2320 [b, x, y, d], 2321 list(a))
2322
2323 - def test_setslice_negative2(self):
2324 Element = self.etree.Element 2325 SubElement = self.etree.SubElement 2326 2327 a = Element('a') 2328 b = SubElement(a, 'b') 2329 c = SubElement(a, 'c') 2330 d = SubElement(a, 'd') 2331 2332 x = Element('x') 2333 y = Element('y') 2334 2335 a[1:-2] = [x, y] 2336 self.assertEquals( 2337 [b, x, y, c, d], 2338 list(a))
2339
2340 - def test_setslice_end(self):
2341 Element = self.etree.Element 2342 SubElement = self.etree.SubElement 2343 2344 a = Element('a') 2345 b = SubElement(a, 'b') 2346 c = SubElement(a, 'c') 2347 d = SubElement(a, 'd') 2348 2349 e = Element('e') 2350 f = Element('f') 2351 g = Element('g') 2352 2353 s = [e, f, g] 2354 a[3:] = s 2355 self.assertEquals( 2356 [b, c, d, e, f, g], 2357 list(a))
2358
2359 - def test_setslice_empty(self):
2360 Element = self.etree.Element 2361 2362 a = Element('a') 2363 2364 b = Element('b') 2365 c = Element('c') 2366 2367 a[:] = [b, c] 2368 self.assertEquals( 2369 [b, c], 2370 list(a))
2371
2372 - def test_tail_elementtree_root(self):
2373 Element = self.etree.Element 2374 ElementTree = self.etree.ElementTree 2375 2376 a = Element('a') 2377 a.tail = 'A2' 2378 t = ElementTree(element=a) 2379 self.assertEquals('A2', 2380 a.tail)
2381
2382 - def test_elementtree_getiterator(self):
2383 Element = self.etree.Element 2384 SubElement = self.etree.SubElement 2385 ElementTree = self.etree.ElementTree 2386 2387 a = Element('a') 2388 b = SubElement(a, 'b') 2389 c = SubElement(a, 'c') 2390 d = SubElement(b, 'd') 2391 e = SubElement(c, 'e') 2392 t = ElementTree(element=a) 2393 2394 self.assertEquals( 2395 [a, b, d, c, e], 2396 list(t.getiterator()))
2397
2398 - def test_elementtree_getiterator_filter(self):
2399 Element = self.etree.Element 2400 SubElement = self.etree.SubElement 2401 ElementTree = self.etree.ElementTree 2402 a = Element('a') 2403 b = SubElement(a, 'b') 2404 c = SubElement(a, 'c') 2405 d = SubElement(b, 'd') 2406 e = SubElement(c, 'e') 2407 t = ElementTree(element=a) 2408 2409 self.assertEquals( 2410 [a], 2411 list(t.getiterator('a'))) 2412 a2 = SubElement(e, 'a') 2413 self.assertEquals( 2414 [a, a2], 2415 list(t.getiterator('a')))
2416
2417 - def test_ns_access(self):
2418 ElementTree = self.etree.ElementTree 2419 ns = 'http://xml.infrae.com/1' 2420 f = BytesIO('<x:a xmlns:x="%s"><x:b></x:b></x:a>' % ns) 2421 t = ElementTree(file=f) 2422 a = t.getroot() 2423 self.assertEquals('{%s}a' % ns, 2424 a.tag) 2425 self.assertEquals('{%s}b' % ns, 2426 a[0].tag)
2427
2428 - def test_ns_access2(self):
2429 ElementTree = self.etree.ElementTree 2430 ns = 'http://xml.infrae.com/1' 2431 ns2 = 'http://xml.infrae.com/2' 2432 f = BytesIO('<x:a xmlns:x="%s" xmlns:y="%s"><x:b></x:b><y:b></y:b></x:a>' % (ns, ns2)) 2433 t = ElementTree(file=f) 2434 a = t.getroot() 2435 self.assertEquals('{%s}a' % ns, 2436 a.tag) 2437 self.assertEquals('{%s}b' % ns, 2438 a[0].tag) 2439 self.assertEquals('{%s}b' % ns2, 2440 a[1].tag)
2441
2442 - def test_ns_setting(self):
2443 Element = self.etree.Element 2444 SubElement = self.etree.SubElement 2445 ns = 'http://xml.infrae.com/1' 2446 ns2 = 'http://xml.infrae.com/2' 2447 a = Element('{%s}a' % ns) 2448 b = SubElement(a, '{%s}b' % ns2) 2449 c = SubElement(a, '{%s}c' % ns) 2450 self.assertEquals('{%s}a' % ns, 2451 a.tag) 2452 self.assertEquals('{%s}b' % ns2, 2453 b.tag) 2454 self.assertEquals('{%s}c' % ns, 2455 c.tag) 2456 self.assertEquals('{%s}a' % ns, 2457 a.tag) 2458 self.assertEquals('{%s}b' % ns2, 2459 b.tag) 2460 self.assertEquals('{%s}c' % ns, 2461 c.tag)
2462
2463 - def test_ns_tag_parse(self):
2464 Element = self.etree.Element 2465 SubElement = self.etree.SubElement 2466 ElementTree = self.etree.ElementTree 2467 2468 ns = 'http://xml.infrae.com/1' 2469 ns2 = 'http://xml.infrae.com/2' 2470 f = BytesIO('<a xmlns="%s" xmlns:x="%s"><x:b></x:b><b></b></a>' % (ns, ns2)) 2471 t = ElementTree(file=f) 2472 2473 a = t.getroot() 2474 self.assertEquals('{%s}a' % ns, 2475 a.tag) 2476 self.assertEquals('{%s}b' % ns2, 2477 a[0].tag) 2478 self.assertEquals('{%s}b' % ns, 2479 a[1].tag)
2480
2481 - def test_ns_attr(self):
2482 Element = self.etree.Element 2483 ns = 'http://xml.infrae.com/1' 2484 ns2 = 'http://xml.infrae.com/2' 2485 a = Element('a') 2486 a.set('{%s}foo' % ns, 'Foo') 2487 a.set('{%s}bar' % ns2, 'Bar') 2488 self.assertEquals( 2489 'Foo', 2490 a.get('{%s}foo' % ns)) 2491 self.assertEquals( 2492 'Bar', 2493 a.get('{%s}bar' % ns2)) 2494 try: 2495 self.assertXML( 2496 _bytes('<a xmlns:ns0="%s" xmlns:ns1="%s" ns0:foo="Foo" ns1:bar="Bar"></a>' % (ns, ns2)), 2497 a) 2498 except AssertionError: 2499 self.assertXML( 2500 _bytes('<a xmlns:ns0="%s" xmlns:ns1="%s" ns1:foo="Foo" ns0:bar="Bar"></a>' % (ns2, ns)), 2501 a)
2502
2503 - def test_ns_move(self):
2504 Element = self.etree.Element 2505 one = self.etree.fromstring( 2506 _bytes('<foo><bar xmlns:ns="http://a.b.c"><ns:baz/></bar></foo>')) 2507 baz = one[0][0] 2508 2509 two = Element('root') 2510 two.append(baz) 2511 # removing the originating document could cause a crash/error before 2512 # as namespace is not moved along with it 2513 del one, baz 2514 self.assertEquals('{http://a.b.c}baz', two[0].tag)
2515
2516 - def test_ns_decl_tostring(self):
2517 tostring = self.etree.tostring 2518 root = self.etree.XML( 2519 _bytes('<foo><bar xmlns:ns="http://a.b.c"><ns:baz/></bar></foo>')) 2520 baz = root[0][0] 2521 2522 nsdecl = re.findall(_bytes("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']"), 2523 tostring(baz)) 2524 self.assertEquals([_bytes("http://a.b.c")], nsdecl)
2525
2526 - def test_ns_decl_tostring_default(self):
2527 tostring = self.etree.tostring 2528 root = self.etree.XML( 2529 _bytes('<foo><bar xmlns="http://a.b.c"><baz/></bar></foo>')) 2530 baz = root[0][0] 2531 2532 nsdecl = re.findall(_bytes("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']"), 2533 tostring(baz)) 2534 self.assertEquals([_bytes("http://a.b.c")], nsdecl)
2535
2536 - def test_ns_decl_tostring_root(self):
2537 tostring = self.etree.tostring 2538 root = self.etree.XML( 2539 _bytes('<foo xmlns:ns="http://a.b.c"><bar><ns:baz/></bar></foo>')) 2540 baz = root[0][0] 2541 2542 nsdecl = re.findall(_bytes("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']"), 2543 tostring(baz)) 2544 2545 self.assertEquals([_bytes("http://a.b.c")], nsdecl)
2546
2547 - def test_ns_decl_tostring_element(self):
2548 Element = self.etree.Element 2549 SubElement = self.etree.SubElement 2550 2551 root = Element("foo") 2552 bar = SubElement(root, "{http://a.b.c}bar") 2553 baz = SubElement(bar, "{http://a.b.c}baz") 2554 2555 nsdecl = re.findall(_bytes("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']"), 2556 self.etree.tostring(baz)) 2557 2558 self.assertEquals([_bytes("http://a.b.c")], nsdecl)
2559
2560 - def test_attribute_xmlns_move(self):
2561 Element = self.etree.Element 2562 2563 root = Element('element') 2564 2565 subelement = Element('subelement', 2566 {"{http://www.w3.org/XML/1998/namespace}id": "foo"}) 2567 self.assertEquals(1, len(subelement.attrib)) 2568 self.assertEquals( 2569 "foo", 2570 subelement.get("{http://www.w3.org/XML/1998/namespace}id")) 2571 2572 root.append(subelement) 2573 self.assertEquals(1, len(subelement.attrib)) 2574 self.assertEquals( 2575 list({"{http://www.w3.org/XML/1998/namespace}id" : "foo"}.items()), 2576 list(subelement.attrib.items())) 2577 self.assertEquals( 2578 "foo", 2579 subelement.get("{http://www.w3.org/XML/1998/namespace}id"))
2580
2581 - def test_namespaces_after_serialize(self):
2582 parse = self.etree.parse 2583 tostring = self.etree.tostring 2584 2585 ns_href = "http://a.b.c" 2586 one = parse( 2587 BytesIO('<foo><bar xmlns:ns="%s"><ns:baz/></bar></foo>' % ns_href)) 2588 baz = one.getroot()[0][0] 2589 2590 parsed = parse(BytesIO( tostring(baz) )).getroot() 2591 self.assertEquals('{%s}baz' % ns_href, parsed.tag)
2592
2593 - def test_attribute_namespace_roundtrip(self):
2594 fromstring = self.etree.fromstring 2595 tostring = self.etree.tostring 2596 2597 ns_href = "http://a.b.c" 2598 xml = _bytes('<root xmlns="%s" xmlns:x="%s"><el x:a="test" /></root>' % ( 2599 ns_href,ns_href)) 2600 root = fromstring(xml) 2601 self.assertEquals('test', root[0].get('{%s}a' % ns_href)) 2602 2603 xml2 = tostring(root) 2604 self.assertTrue(_bytes(':a=') in xml2, xml2) 2605 2606 root2 = fromstring(xml2) 2607 self.assertEquals('test', root2[0].get('{%s}a' % ns_href))
2608
2609 - def test_attribute_namespace_roundtrip_replaced(self):
2610 fromstring = self.etree.fromstring 2611 tostring = self.etree.tostring 2612 2613 ns_href = "http://a.b.c" 2614 xml = _bytes('<root xmlns="%s" xmlns:x="%s"><el x:a="test" /></root>' % ( 2615 ns_href,ns_href)) 2616 root = fromstring(xml) 2617 self.assertEquals('test', root[0].get('{%s}a' % ns_href)) 2618 2619 root[0].set('{%s}a' % ns_href, 'TEST') 2620 2621 xml2 = tostring(root) 2622 self.assertTrue(_bytes(':a=') in xml2, xml2) 2623 2624 root2 = fromstring(xml2) 2625 self.assertEquals('TEST', root2[0].get('{%s}a' % ns_href))
2626 2627 required_versions_ET['test_register_namespace'] = (1,3)
2628 - def test_register_namespace(self):
2629 # ET 1.3+ 2630 Element = self.etree.Element 2631 prefix = 'TESTPREFIX' 2632 namespace = 'http://seriously.unknown/namespace/URI' 2633 2634 el = Element('{%s}test' % namespace) 2635 self.assertEquals(_bytes('<ns0:test xmlns:ns0="%s"></ns0:test>' % namespace), 2636 self._writeElement(el)) 2637 2638 self.etree.register_namespace(prefix, namespace) 2639 el = Element('{%s}test' % namespace) 2640 self.assertEquals(_bytes('<%s:test xmlns:%s="%s"></%s:test>' % ( 2641 prefix, prefix, namespace, prefix)), 2642 self._writeElement(el)) 2643 2644 self.assertRaises(ValueError, self.etree.register_namespace, 'ns25', namespace)
2645
2646 - def test_tostring(self):
2647 tostring = self.etree.tostring 2648 Element = self.etree.Element 2649 SubElement = self.etree.SubElement 2650 2651 a = Element('a') 2652 b = SubElement(a, 'b') 2653 c = SubElement(a, 'c') 2654 2655 self.assertEquals(_bytes('<a><b></b><c></c></a>'), 2656 canonicalize(tostring(a)))
2657
2658 - def test_tostring_element(self):
2659 tostring = self.etree.tostring 2660 Element = self.etree.Element 2661 SubElement = self.etree.SubElement 2662 2663 a = Element('a') 2664 b = SubElement(a, 'b') 2665 c = SubElement(a, 'c') 2666 d = SubElement(c, 'd') 2667 self.assertEquals(_bytes('<b></b>'), 2668 canonicalize(tostring(b))) 2669 self.assertEquals(_bytes('<c><d></d></c>'), 2670 canonicalize(tostring(c)))
2671
2672 - def test_tostring_element_tail(self):
2673 tostring = self.etree.tostring 2674 Element = self.etree.Element 2675 SubElement = self.etree.SubElement 2676 2677 a = Element('a') 2678 b = SubElement(a, 'b') 2679 c = SubElement(a, 'c') 2680 d = SubElement(c, 'd') 2681 b.tail = 'Foo' 2682 2683 self.assert_(tostring(b) == _bytes('<b/>Foo') or 2684 tostring(b) == _bytes('<b />Foo'))
2685 2686 required_versions_ET['test_tostring_method_html'] = (1,3)
2687 - def test_tostring_method_html(self):
2688 tostring = self.etree.tostring 2689 Element = self.etree.Element 2690 SubElement = self.etree.SubElement 2691 2692 html = Element('html') 2693 body = SubElement(html, 'body') 2694 p = SubElement(body, 'p') 2695 p.text = "html" 2696 SubElement(p, 'br').tail = "test" 2697 2698 self.assertEquals(_bytes('<html><body><p>html<br>test</p></body></html>'), 2699 tostring(html, method="html"))
2700 2701 required_versions_ET['test_tostring_method_text'] = (1,3)
2702 - def test_tostring_method_text(self):
2703 tostring = self.etree.tostring 2704 Element = self.etree.Element 2705 SubElement = self.etree.SubElement 2706 2707 a = Element('a') 2708 a.text = "A" 2709 a.tail = "tail" 2710 b = SubElement(a, 'b') 2711 b.text = "B" 2712 b.tail = "TAIL" 2713 c = SubElement(a, 'c') 2714 c.text = "C" 2715 2716 self.assertEquals(_bytes('ABTAILCtail'), 2717 tostring(a, method="text"))
2718
2719 - def test_iterparse(self):
2720 iterparse = self.etree.iterparse 2721 f = BytesIO('<a><b></b><c/></a>') 2722 2723 iterator = iterparse(f) 2724 self.assertEquals(None, 2725 iterator.root) 2726 events = list(iterator) 2727 root = iterator.root 2728 self.assertEquals( 2729 [('end', root[0]), ('end', root[1]), ('end', root)], 2730 events)
2731
2732 - def test_iterparse_file(self):
2733 iterparse = self.etree.iterparse 2734 iterator = iterparse(fileInTestDir("test.xml")) 2735 self.assertEquals(None, 2736 iterator.root) 2737 events = list(iterator) 2738 root = iterator.root 2739 self.assertEquals( 2740 [('end', root[0]), ('end', root)], 2741 events)
2742
2743 - def test_iterparse_start(self):
2744 iterparse = self.etree.iterparse 2745 f = BytesIO('<a><b></b><c/></a>') 2746 2747 iterator = iterparse(f, events=('start',)) 2748 events = list(iterator) 2749 root = iterator.root 2750 self.assertEquals( 2751 [('start', root), ('start', root[0]), ('start', root[1])], 2752 events)
2753
2754 - def test_iterparse_start_end(self):
2755 iterparse = self.etree.iterparse 2756 f = BytesIO('<a><b></b><c/></a>') 2757 2758 iterator = iterparse(f, events=('start','end')) 2759 events = list(iterator) 2760 root = iterator.root 2761 self.assertEquals( 2762 [('start', root), ('start', root[0]), ('end', root[0]), 2763 ('start', root[1]), ('end', root[1]), ('end', root)], 2764 events)
2765
2766 - def test_iterparse_clear(self):
2767 iterparse = self.etree.iterparse 2768 f = BytesIO('<a><b></b><c/></a>') 2769 2770 iterator = iterparse(f) 2771 for event, elem in iterator: 2772 elem.clear() 2773 2774 root = iterator.root 2775 self.assertEquals(0, 2776 len(root))
2777
2778 - def test_iterparse_large(self):
2779 iterparse = self.etree.iterparse 2780 CHILD_COUNT = 12345 2781 f = BytesIO('<a>%s</a>' % ('<b>test</b>'*CHILD_COUNT)) 2782 2783 i = 0 2784 for key in iterparse(f): 2785 event, element = key 2786 i += 1 2787 self.assertEquals(i, CHILD_COUNT + 1)
2788
2789 - def test_iterparse_attrib_ns(self):
2790 iterparse = self.etree.iterparse 2791 f = BytesIO('<a xmlns="http://ns1/"><b><c xmlns="http://ns2/"/></b></a>') 2792 2793 attr_name = '{http://testns/}bla' 2794 events = [] 2795 iterator = iterparse(f, events=('start','end','start-ns','end-ns')) 2796 for event, elem in iterator: 2797 events.append(event) 2798 if event == 'start': 2799 if elem.tag != '{http://ns1/}a': 2800 elem.set(attr_name, 'value') 2801 2802 self.assertEquals( 2803 ['start-ns', 'start', 'start', 'start-ns', 'start', 2804 'end', 'end-ns', 'end', 'end', 'end-ns'], 2805 events) 2806 2807 root = iterator.root 2808 self.assertEquals( 2809 None, 2810 root.get(attr_name)) 2811 self.assertEquals( 2812 'value', 2813 root[0].get(attr_name))
2814
2815 - def test_iterparse_getiterator(self):
2816 iterparse = self.etree.iterparse 2817 f = BytesIO('<a><b><d/></b><c/></a>') 2818 2819 counts = [] 2820 for event, elem in iterparse(f): 2821 counts.append(len(list(elem.getiterator()))) 2822 self.assertEquals( 2823 [1,2,1,4], 2824 counts)
2825
2826 - def test_iterparse_move_elements(self):
2827 iterparse = self.etree.iterparse 2828 f = BytesIO('<a><b><d/></b><c/></a>') 2829 2830 for event, node in etree.iterparse(f): pass 2831 2832 root = etree.Element('new_root', {}) 2833 root[:] = node[:] 2834 2835 self.assertEquals( 2836 ['b', 'c'], 2837 [ el.tag for el in root ])
2838
2839 - def test_iterparse_cdata(self):
2840 tostring = self.etree.tostring 2841 f = BytesIO('<root><![CDATA[test]]></root>') 2842 context = self.etree.iterparse(f) 2843 content = [ el.text for event,el in context ] 2844 2845 self.assertEquals(['test'], content) 2846 self.assertEquals(_bytes('<root>test</root>'), 2847 tostring(context.root))
2848
2849 - def test_parse_file(self):
2850 parse = self.etree.parse 2851 # from file 2852 tree = parse(fileInTestDir('test.xml')) 2853 self.assertXML( 2854 _bytes('<a><b></b></a>'), 2855 tree.getroot())
2856
2857 - def test_parse_file_nonexistent(self):
2858 parse = self.etree.parse 2859 self.assertRaises(IOError, parse, fileInTestDir('notthere.xml'))
2860
2861 - def test_parse_error_none(self):
2862 parse = self.etree.parse 2863 self.assertRaises(TypeError, parse, None)
2864 2865 required_versions_ET['test_parse_error'] = (1,3)
2866 - def test_parse_error(self):
2867 # ET < 1.3 raises ExpatError 2868 parse = self.etree.parse 2869 f = BytesIO('<a><b></c></b></a>') 2870 self.assertRaises(SyntaxError, parse, f) 2871 f.close()
2872 2873 required_versions_ET['test_parse_error_from_file'] = (1,3)
2874 - def test_parse_error_from_file(self):
2875 parse = self.etree.parse 2876 # from file 2877 f = open(fileInTestDir('test_broken.xml'), 'rb') 2878 self.assertRaises(SyntaxError, parse, f) 2879 f.close()
2880
2881 - def test_parse_file_object(self):
2882 parse = self.etree.parse 2883 # from file object 2884 f = open(fileInTestDir('test.xml'), 'rb') 2885 tree = parse(f) 2886 f.close() 2887 self.assertXML( 2888 _bytes('<a><b></b></a>'), 2889 tree.getroot())
2890
2891 - def test_parse_stringio(self):
2892 parse = self.etree.parse 2893 f = BytesIO('<a><b></b></a>') 2894 tree = parse(f) 2895 f.close() 2896 self.assertXML( 2897 _bytes('<a><b></b></a>'), 2898 tree.getroot() 2899 )
2900
2901 - def test_parse_cdata(self):
2902 tostring = self.etree.tostring 2903 root = self.etree.XML(_bytes('<root><![CDATA[test]]></root>')) 2904 2905 self.assertEquals('test', root.text) 2906 self.assertEquals(_bytes('<root>test</root>'), 2907 tostring(root))
2908
2909 - def test_parse_with_encoding(self):
2910 # this can fail in libxml2 <= 2.6.22 2911 parse = self.etree.parse 2912 tree = parse(BytesIO('<?xml version="1.0" encoding="ascii"?><html/>')) 2913 self.assertXML(_bytes('<html></html>'), 2914 tree.getroot())
2915
2916 - def test_encoding(self):
2917 Element = self.etree.Element 2918 2919 a = Element('a') 2920 a.text = _str('Søk på nettet') 2921 self.assertXML( 2922 _str('<a>Søk på nettet</a>').encode('UTF-8'), 2923 a, 'utf-8')
2924
2925 - def test_encoding_exact(self):
2926 ElementTree = self.etree.ElementTree 2927 Element = self.etree.Element 2928 2929 a = Element('a') 2930 a.text = _str('Søk på nettet') 2931 2932 f = BytesIO() 2933 tree = ElementTree(element=a) 2934 tree.write(f, encoding='utf-8') 2935 self.assertEquals(_str('<a>Søk på nettet</a>').encode('UTF-8'), 2936 f.getvalue().replace(_bytes('\n'),_bytes('')))
2937
2938 - def test_parse_file_encoding(self):
2939 parse = self.etree.parse 2940 # from file 2941 tree = parse(fileInTestDir('test-string.xml')) 2942 self.assertXML( 2943 _str('<a>Søk på nettet</a>').encode('UTF-8'), 2944 tree.getroot(), 'UTF-8')
2945
2946 - def test_parse_file_object_encoding(self):
2947 parse = self.etree.parse 2948 # from file object 2949 f = open(fileInTestDir('test-string.xml'), 'rb') 2950 tree = parse(f) 2951 f.close() 2952 self.assertXML( 2953 _str('<a>Søk på nettet</a>').encode('UTF-8'), 2954 tree.getroot(), 'UTF-8')
2955
2956 - def test_encoding_8bit_latin1(self):
2957 ElementTree = self.etree.ElementTree 2958 Element = self.etree.Element 2959 2960 a = Element('a') 2961 a.text = _str('Søk på nettet') 2962 2963 f = BytesIO() 2964 tree = ElementTree(element=a) 2965 tree.write(f, encoding='iso-8859-1') 2966 result = f.getvalue() 2967 declaration = _bytes("<?xml version=\'1.0\' encoding=\'iso-8859-1\'?>") 2968 self.assertEncodingDeclaration(result, _bytes('iso-8859-1')) 2969 result = result.split(_bytes('?>'), 1)[-1].replace(_bytes('\n'),_bytes('')) 2970 self.assertEquals(_str('<a>Søk på nettet</a>').encode('iso-8859-1'), 2971 result)
2972 2973 required_versions_ET['test_parse_encoding_8bit_explicit'] = (1,3)
2974 - def test_parse_encoding_8bit_explicit(self):
2975 XMLParser = self.etree.XMLParser 2976 2977 text = _str('Søk på nettet') 2978 xml_latin1 = (_str('<a>%s</a>') % text).encode('iso-8859-1') 2979 2980 self.assertRaises(self.etree.ParseError, 2981 self.etree.parse, 2982 BytesIO(xml_latin1)) 2983 2984 tree = self.etree.parse(BytesIO(xml_latin1), 2985 XMLParser(encoding="iso-8859-1")) 2986 a = tree.getroot() 2987 self.assertEquals(a.text, text)
2988 2989 required_versions_ET['test_parse_encoding_8bit_override'] = (1,3)
2990 - def test_parse_encoding_8bit_override(self):
2991 XMLParser = self.etree.XMLParser 2992 2993 text = _str('Søk på nettet') 2994 wrong_declaration = _str("<?xml version='1.0' encoding='UTF-8'?>") 2995 xml_latin1 = (_str('%s<a>%s</a>') % (wrong_declaration, text) 2996 ).encode('iso-8859-1') 2997 2998 self.assertRaises(self.etree.ParseError, 2999 self.etree.parse, 3000 BytesIO(xml_latin1)) 3001 3002 tree = self.etree.parse(BytesIO(xml_latin1), 3003 XMLParser(encoding="iso-8859-1")) 3004 a = tree.getroot() 3005 self.assertEquals(a.text, text)
3006
3007 - def _test_wrong_unicode_encoding(self):
3008 # raise error on wrong encoding declaration in unicode strings 3009 XML = self.etree.XML 3010 test_utf = (_str('<?xml version="1.0" encoding="iso-8859-1"?>') + 3011 _str('<a>Søk på nettet</a>')) 3012 self.assertRaises(SyntaxError, XML, test_utf)
3013
3014 - def test_encoding_write_default_encoding(self):
3015 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) 3024 data = f.getvalue().replace(_bytes('\n'),_bytes('')) 3025 self.assertEquals( 3026 _str('<a>Søk på nettet</a>').encode('ASCII', 'xmlcharrefreplace'), 3027 data)
3028
3029 - def test_encoding_tostring(self):
3030 Element = self.etree.Element 3031 tostring = self.etree.tostring 3032 3033 a = Element('a') 3034 a.text = _str('Søk på nettet') 3035 self.assertEquals(_str('<a>Søk på nettet</a>').encode('UTF-8'), 3036 tostring(a, encoding='utf-8'))
3037
3038 - def test_encoding_tostring_unknown(self):
3039 Element = self.etree.Element 3040 tostring = self.etree.tostring 3041 3042 a = Element('a') 3043 a.text = _str('Søk på nettet') 3044 self.assertRaises(LookupError, tostring, a, 3045 encoding='Invalid Encoding')
3046
3047 - def test_encoding_tostring_sub(self):
3048 Element = self.etree.Element 3049 SubElement = self.etree.SubElement 3050 tostring = self.etree.tostring 3051 3052 a = Element('a') 3053 b = SubElement(a, 'b') 3054 b.text = _str('Søk på nettet') 3055 self.assertEquals(_str('<b>Søk på nettet</b>').encode('UTF-8'), 3056 tostring(b, encoding='utf-8'))
3057
3058 - def test_encoding_tostring_sub_tail(self):
3059 Element = self.etree.Element 3060 SubElement = self.etree.SubElement 3061 tostring = self.etree.tostring 3062 3063 a = Element('a') 3064 b = SubElement(a, 'b') 3065 b.text = _str('Søk på nettet') 3066 b.tail = _str('Søk') 3067 self.assertEquals(_str('<b>Søk på nettet</b>Søk').encode('UTF-8'), 3068 tostring(b, encoding='utf-8'))
3069
3070 - def test_encoding_tostring_default_encoding(self):
3071 Element = self.etree.Element 3072 SubElement = self.etree.SubElement 3073 tostring = self.etree.tostring 3074 3075 a = Element('a') 3076 a.text = _str('Søk på nettet') 3077 3078 expected = _bytes('<a>S&#248;k p&#229; nettet</a>') 3079 self.assertEquals( 3080 expected, 3081 tostring(a))
3082
3083 - def test_encoding_sub_tostring_default_encoding(self):
3084 Element = self.etree.Element 3085 SubElement = self.etree.SubElement 3086 tostring = self.etree.tostring 3087 3088 a = Element('a') 3089 b = SubElement(a, 'b') 3090 b.text = _str('Søk på nettet') 3091 3092 expected = _bytes('<b>S&#248;k p&#229; nettet</b>') 3093 self.assertEquals( 3094 expected, 3095 tostring(b))
3096
3097 - def test_encoding_8bit_xml(self):
3098 utext = _str('Søk på nettet') 3099 uxml = _str('<p>%s</p>') % utext 3100 prologue = _bytes('<?xml version="1.0" encoding="iso-8859-1" ?>') 3101 isoxml = prologue + uxml.encode('iso-8859-1') 3102 tree = self.etree.XML(isoxml) 3103 self.assertEquals(utext, tree.text)
3104
3105 - def test_encoding_utf8_bom(self):
3106 utext = _str('Søk på nettet') 3107 uxml = (_str('<?xml version="1.0" encoding="UTF-8"?>') + 3108 _str('<p>%s</p>') % utext) 3109 bom = _bytes('\\xEF\\xBB\\xBF').decode("unicode_escape").encode("latin1") 3110 xml = bom + uxml.encode("utf-8") 3111 tree = etree.XML(xml) 3112 self.assertEquals(utext, tree.text)
3113
3114 - def test_encoding_8bit_parse_stringio(self):
3115 utext = _str('Søk på nettet') 3116 uxml = _str('<p>%s</p>') % utext 3117 prologue = _bytes('<?xml version="1.0" encoding="iso-8859-1" ?>') 3118 isoxml = prologue + uxml.encode('iso-8859-1') 3119 el = self.etree.parse(BytesIO(isoxml)).getroot() 3120 self.assertEquals(utext, el.text)
3121
3122 - def test_deepcopy_elementtree(self):
3123 Element = self.etree.Element 3124 ElementTree = self.etree.ElementTree 3125 3126 a = Element('a') 3127 a.text = "Foo" 3128 atree = ElementTree(a) 3129 3130 btree = copy.deepcopy(atree) 3131 self.assertEqual("Foo", atree.getroot().text) 3132 self.assertEqual("Foo", btree.getroot().text) 3133 self.assertFalse(btree is atree) 3134 self.assertFalse(btree.getroot() is atree.getroot())
3135
3136 - def test_deepcopy(self):
3137 Element = self.etree.Element 3138 3139 a = Element('a') 3140 a.text = 'Foo' 3141 3142 b = copy.deepcopy(a) 3143 self.assertEquals('Foo', b.text) 3144 3145 b.text = 'Bar' 3146 self.assertEquals('Bar', b.text) 3147 self.assertEquals('Foo', a.text) 3148 3149 del a 3150 self.assertEquals('Bar', b.text)
3151
3152 - def test_deepcopy_tail(self):
3153 Element = self.etree.Element 3154 3155 a = Element('a') 3156 a.tail = 'Foo' 3157 3158 b = copy.deepcopy(a) 3159 self.assertEquals('Foo', b.tail) 3160 3161 b.tail = 'Bar' 3162 self.assertEquals('Bar', b.tail) 3163 self.assertEquals('Foo', a.tail) 3164 3165 del a 3166 self.assertEquals('Bar', b.tail)
3167
3168 - def test_deepcopy_subelement(self):
3169 Element = self.etree.Element 3170 SubElement = self.etree.SubElement 3171 3172 root = Element('root') 3173 a = SubElement(root, 'a') 3174 a.text = 'FooText' 3175 a.tail = 'FooTail' 3176 3177 b = copy.deepcopy(a) 3178 self.assertEquals('FooText', b.text) 3179 self.assertEquals('FooTail', b.tail) 3180 3181 b.text = 'BarText' 3182 b.tail = 'BarTail' 3183 self.assertEquals('BarTail', b.tail) 3184 self.assertEquals('FooTail', a.tail) 3185 self.assertEquals('BarText', b.text) 3186 self.assertEquals('FooText', a.text) 3187 3188 del a 3189 self.assertEquals('BarTail', b.tail) 3190 self.assertEquals('BarText', b.text)
3191
3192 - def test_deepcopy_namespaces(self):
3193 root = self.etree.XML(_bytes('''<doc xmlns="dns" xmlns:t="tns"> 3194 <parent><node t:foo="bar" /></parent> 3195 </doc>''')) 3196 self.assertEquals( 3197 root[0][0].get('{tns}foo'), 3198 copy.deepcopy(root[0])[0].get('{tns}foo') ) 3199 self.assertEquals( 3200 root[0][0].get('{tns}foo'), 3201 copy.deepcopy(root[0][0]).get('{tns}foo') )
3202
3203 - def test_deepcopy_append(self):
3204 # previously caused a crash 3205 Element = self.etree.Element 3206 tostring = self.etree.tostring 3207 3208 a = Element('a') 3209 b = copy.deepcopy(a) 3210 a.append( Element('C') ) 3211 b.append( Element('X') ) 3212 3213 self.assertEquals(_bytes('<a><C/></a>'), 3214 tostring(a).replace(_bytes(' '), _bytes(''))) 3215 self.assertEquals(_bytes('<a><X/></a>'), 3216 tostring(b).replace(_bytes(' '), _bytes('')))
3217
3218 - def test_deepcopy_comment(self):
3219 # previously caused a crash 3220 # not supported by ET < 1.3! 3221 Comment = self.etree.Comment 3222 3223 a = Comment("ONE") 3224 b = copy.deepcopy(a) 3225 b.text = "ANOTHER" 3226 3227 self.assertEquals('ONE', a.text) 3228 self.assertEquals('ANOTHER', b.text)
3229
3230 - def test_shallowcopy(self):
3231 Element = self.etree.Element 3232 3233 a = Element('a') 3234 a.text = 'Foo' 3235 3236 b = copy.copy(a) 3237 self.assertEquals('Foo', b.text) 3238 3239 b.text = 'Bar' 3240 self.assertEquals('Bar', b.text) 3241 self.assertEquals('Foo', a.text)
3242 # XXX ElementTree will share nodes, but lxml.etree won't.. 3243
3244 - def test_shallowcopy_elementtree(self):
3245 Element = self.etree.Element 3246 ElementTree = self.etree.ElementTree 3247 3248 a = Element('a') 3249 a.text = 'Foo' 3250 atree = ElementTree(a) 3251 3252 btree = copy.copy(atree) 3253 self.assertFalse(btree is atree) 3254 self.assert_(btree.getroot() is atree.getroot()) 3255 self.assertEquals('Foo', atree.getroot().text)
3256
3257 - def _test_element_boolean(self):
3258 # deprecated as of ET 1.3/lxml 2.0 3259 etree = self.etree 3260 e = etree.Element('foo') 3261 self.assertEquals(False, bool(e)) 3262 etree.SubElement(e, 'bar') 3263 self.assertEquals(True, bool(e)) 3264 e = etree.Element('foo') 3265 e.text = 'hey' 3266 self.assertEquals(False, bool(e)) 3267 e = etree.Element('foo') 3268 e.tail = 'bar' 3269 self.assertEquals(False, bool(e)) 3270 e = etree.Element('foo') 3271 e.set('bar', 'Bar') 3272 self.assertEquals(False, bool(e))
3273
3274 - def test_multiple_elementrees(self):
3275 etree = self.etree 3276 3277 a = etree.Element('a') 3278 b = etree.SubElement(a, 'b') 3279 3280 t = etree.ElementTree(a) 3281 self.assertEquals(self._rootstring(t), _bytes('<a><b/></a>')) 3282 3283 t1 = etree.ElementTree(a) 3284 self.assertEquals(self._rootstring(t1), _bytes('<a><b/></a>')) 3285 self.assertEquals(self._rootstring(t), _bytes('<a><b/></a>')) 3286 3287 t2 = etree.ElementTree(b) 3288 self.assertEquals(self._rootstring(t2), _bytes('<b/>')) 3289 self.assertEquals(self._rootstring(t1), _bytes('<a><b/></a>')) 3290 self.assertEquals(self._rootstring(t), _bytes('<a><b/></a>'))
3291
3292 - def test_qname(self):
3293 etree = self.etree 3294 qname = etree.QName('myns', 'a') 3295 a1 = etree.Element(qname) 3296 a2 = etree.SubElement(a1, qname) 3297 self.assertEquals(a1.tag, "{myns}a") 3298 self.assertEquals(a2.tag, "{myns}a")
3299
3300 - def test_qname_cmp(self):
3301 etree = self.etree 3302 qname1 = etree.QName('myns', 'a') 3303 qname2 = etree.QName('myns', 'a') 3304 self.assertEquals(qname1, "{myns}a") 3305 self.assertEquals("{myns}a", qname2) 3306 self.assertEquals(qname1, qname1) 3307 self.assertEquals(qname1, qname2)
3308
3309 - def test_qname_attribute_getset(self):
3310 etree = self.etree 3311 qname = etree.QName('myns', 'a') 3312 3313 a = etree.Element(qname) 3314 a.set(qname, "value") 3315 3316 self.assertEquals(a.get(qname), "value") 3317 self.assertEquals(a.get("{myns}a"), "value")
3318
3319 - def test_qname_attrib(self):
3320 etree = self.etree 3321 qname = etree.QName('myns', 'a') 3322 3323 a = etree.Element(qname) 3324 a.attrib[qname] = "value" 3325 3326 self.assertEquals(a.attrib[qname], "value") 3327 self.assertEquals(a.attrib.get(qname), "value") 3328 3329 self.assertEquals(a.attrib["{myns}a"], "value") 3330 self.assertEquals(a.attrib.get("{myns}a"), "value")
3331
3332 - def test_qname_attribute_resolve(self):
3333 etree = self.etree 3334 qname = etree.QName('http://myns', 'a') 3335 a = etree.Element(qname) 3336 a.set(qname, qname) 3337 3338 self.assertXML( 3339 _bytes('<ns0:a xmlns:ns0="http://myns" ns0:a="ns0:a"></ns0:a>'), 3340 a)
3341
3342 - def test_qname_attribute_resolve_new(self):
3343 etree = self.etree 3344 qname = etree.QName('http://myns', 'a') 3345 a = etree.Element('a') 3346 a.set('a', qname) 3347 3348 self.assertXML( 3349 _bytes('<a xmlns:ns0="http://myns" a="ns0:a"></a>'), 3350 a)
3351
3352 - def test_qname_attrib_resolve(self):
3353 etree = self.etree 3354 qname = etree.QName('http://myns', 'a') 3355 a = etree.Element(qname) 3356 a.attrib[qname] = qname 3357 3358 self.assertXML( 3359 _bytes('<ns0:a xmlns:ns0="http://myns" ns0:a="ns0:a"></ns0:a>'), 3360 a)
3361
3362 - def test_parser_version(self):
3363 etree = self.etree 3364 parser = etree.XMLParser() 3365 if hasattr(parser, "version"): 3366 # ElementTree 1.3+, cET 3367 self.assert_(re.match("[^ ]+ [0-9.]+", parser.version))
3368 3369 # feed parser interface 3370
3371 - def test_feed_parser_bytes(self):
3372 parser = self.etree.XMLParser() 3373 3374 parser.feed(_bytes('<?xml version=')) 3375 parser.feed(_bytes('"1.0"?><ro')) 3376 parser.feed(_bytes('ot><')) 3377 parser.feed(_bytes('a test="works"/')) 3378 parser.feed(_bytes('></root')) 3379 parser.feed(_bytes('>')) 3380 3381 root = parser.close() 3382 3383 self.assertEquals(root.tag, "root") 3384 self.assertEquals(root[0].tag, "a") 3385 self.assertEquals(root[0].get("test"), "works")
3386
3387 - def test_feed_parser_unicode(self):
3388 parser = self.etree.XMLParser() 3389 3390 parser.feed(_str('<ro')) 3391 parser.feed(_str('ot><')) 3392 parser.feed(_str('a test="works"/')) 3393 parser.feed(_str('></root')) 3394 parser.feed(_str('>')) 3395 3396 root = parser.close() 3397 3398 self.assertEquals(root.tag, "root") 3399 self.assertEquals(root[0].tag, "a") 3400 self.assertEquals(root[0].get("test"), "works")
3401 3402 required_versions_ET['test_feed_parser_error_close_empty'] = (1,3)
3403 - def test_feed_parser_error_close_empty(self):
3404 ParseError = self.etree.ParseError 3405 parser = self.etree.XMLParser() 3406 self.assertRaises(ParseError, parser.close)
3407 3408 required_versions_ET['test_feed_parser_error_close_incomplete'] = (1,3)
3409 - def test_feed_parser_error_close_incomplete(self):
3410 ParseError = self.etree.ParseError 3411 parser = self.etree.XMLParser() 3412 3413 parser.feed('<?xml version=') 3414 parser.feed('"1.0"?><ro') 3415 3416 self.assertRaises(ParseError, parser.close)
3417 3418 required_versions_ET['test_feed_parser_error_broken'] = (1,3)
3419 - def test_feed_parser_error_broken(self):
3420 ParseError = self.etree.ParseError 3421 parser = self.etree.XMLParser() 3422 3423 parser.feed('<?xml version=') 3424 parser.feed('"1.0"?><ro') 3425 try: 3426 parser.feed('<><><><><><><') 3427 except ParseError: 3428 # can raise, but not required before close() 3429 pass 3430 3431 self.assertRaises(ParseError, parser.close)
3432 3433 required_versions_ET['test_feed_parser_error_position'] = (1,3)
3434 - def test_feed_parser_error_position(self):
3435 ParseError = self.etree.ParseError 3436 parser = self.etree.XMLParser() 3437 try: 3438 parser.close() 3439 except ParseError: 3440 e = sys.exc_info()[1] 3441 self.assertNotEquals(None, e.code) 3442 self.assertNotEquals(0, e.code) 3443 self.assert_(isinstance(e.position, tuple)) 3444 self.assert_(e.position >= (0, 0))
3445 3446 # parser target interface 3447 3448 required_versions_ET['test_parser_target_property'] = (1,3)
3449 - def test_parser_target_property(self):
3450 class Target(object): 3451 pass
3452 3453 target = Target() 3454 parser = self.etree.XMLParser(target=target) 3455 3456 self.assertEquals(target, parser.target) 3457
3458 - def test_parser_target_tag(self):
3459 assertEquals = self.assertEquals 3460 assertFalse = self.assertFalse 3461 3462 events = [] 3463 class Target(object): 3464 def start(self, tag, attrib): 3465 events.append("start") 3466 assertFalse(attrib) 3467 assertEquals("TAG", tag)
3468 def end(self, tag): 3469 events.append("end") 3470 assertEquals("TAG", tag) 3471 def close(self): 3472 return "DONE" 3473 3474 parser = self.etree.XMLParser(target=Target()) 3475 3476 parser.feed("<TAG/>") 3477 done = parser.close() 3478 3479 self.assertEquals("DONE", done) 3480 self.assertEquals(["start", "end"], events) 3481
3482 - def test_elementtree_parser_target(self):
3483 assertEquals = self.assertEquals 3484 assertFalse = self.assertFalse 3485 Element = self.etree.Element 3486 3487 events = [] 3488 class Target(object): 3489 def start(self, tag, attrib): 3490 events.append("start") 3491 assertFalse(attrib) 3492 assertEquals("TAG", tag)
3493 def end(self, tag): 3494 events.append("end") 3495 assertEquals("TAG", tag) 3496 def close(self): 3497 return Element("DONE") 3498 3499 parser = self.etree.XMLParser(target=Target()) 3500 tree = self.etree.ElementTree() 3501 tree.parse(BytesIO("<TAG/>"), parser=parser) 3502 3503 self.assertEquals("DONE", tree.getroot().tag) 3504 self.assertEquals(["start", "end"], events) 3505
3506 - def test_parser_target_attrib(self):
3507 assertEquals = self.assertEquals 3508 3509 events = [] 3510 class Target(object): 3511 def start(self, tag, attrib): 3512 events.append("start-" + tag) 3513 for name, value in attrib.items(): 3514 assertEquals(tag + name, value)
3515 def end(self, tag): 3516 events.append("end-" + tag) 3517 def close(self): 3518 return "DONE" 3519 3520 parser = self.etree.XMLParser(target=Target()) 3521 3522 parser.feed('<root a="roota" b="rootb"><sub c="subc"/></root>') 3523 done = parser.close() 3524 3525 self.assertEquals("DONE", done) 3526 self.assertEquals(["start-root", "start-sub", "end-sub", "end-root"], 3527 events) 3528
3529 - def test_parser_target_data(self):
3530 events = [] 3531 class Target(object): 3532 def start(self, tag, attrib): 3533 events.append("start-" + tag)
3534 def end(self, tag): 3535 events.append("end-" + tag) 3536 def data(self, data): 3537 events.append("data-" + data) 3538 def close(self): 3539 return "DONE" 3540 3541 parser = self.etree.XMLParser(target=Target()) 3542 3543 parser.feed('<root>A<sub/>B</root>') 3544 done = parser.close() 3545 3546 self.assertEquals("DONE", done) 3547 self.assertEquals(["start-root", "data-A", "start-sub", 3548 "end-sub", "data-B", "end-root"], 3549 events) 3550
3551 - def test_parser_target_entity(self):
3552 events = [] 3553 class Target(object): 3554 def __init__(self): 3555 self._data = []
3556 def _flush_data(self): 3557 if self._data: 3558 events.append("data-" + ''.join(self._data)) 3559 del self._data[:] 3560 def start(self, tag, attrib): 3561 self._flush_data() 3562 events.append("start-" + tag) 3563 def end(self, tag): 3564 self._flush_data() 3565 events.append("end-" + tag) 3566 def data(self, data): 3567 self._data.append(data) 3568 def close(self): 3569 self._flush_data() 3570 return "DONE" 3571 3572 parser = self.etree.XMLParser(target=Target()) 3573 3574 dtd = ''' 3575 <!DOCTYPE root [ 3576 <!ELEMENT root (sub*)> 3577 <!ELEMENT sub (#PCDATA)> 3578 <!ENTITY ent "an entity"> 3579 ]> 3580 ''' 3581 parser.feed(dtd+'<root><sub/><sub>this is &ent;</sub><sub/></root>') 3582 done = parser.close() 3583 3584 self.assertEquals("DONE", done) 3585 self.assertEquals(["start-root", "start-sub", "end-sub", "start-sub", 3586 "data-this is an entity", 3587 "end-sub", "start-sub", "end-sub", "end-root"], 3588 events) 3589 3590 required_versions_ET['test_parser_target_entity_unknown'] = (1,3)
3591 - def test_parser_target_entity_unknown(self):
3592 events = [] 3593 class Target(object): 3594 def __init__(self): 3595 self._data = []
3596 def _flush_data(self): 3597 if self._data: 3598 events.append("data-" + ''.join(self._data)) 3599 del self._data[:] 3600 def start(self, tag, attrib): 3601 self._flush_data() 3602 events.append("start-" + tag) 3603 def end(self, tag): 3604 self._flush_data() 3605 events.append("end-" + tag) 3606 def data(self, data): 3607 self._data.append(data) 3608 def close(self): 3609 self._flush_data() 3610 return "DONE" 3611 3612 parser = self.etree.XMLParser(target=Target()) 3613 3614 def feed(): 3615 parser.feed('<root><sub/><sub>some &ent;</sub><sub/></root>') 3616 parser.close() 3617 3618 self.assertRaises(self.etree.ParseError, feed) 3619
3620 - def test_treebuilder(self):
3621 builder = self.etree.TreeBuilder() 3622 el = builder.start("root", {'a':'A', 'b':'B'}) 3623 self.assertEquals("root", el.tag) 3624 self.assertEquals({'a':'A', 'b':'B'}, el.attrib) 3625 builder.data("ROOTTEXT") 3626 el = builder.start("child", {'x':'X', 'y':'Y'}) 3627 self.assertEquals("child", el.tag) 3628 self.assertEquals({'x':'X', 'y':'Y'}, el.attrib) 3629 builder.data("CHILDTEXT") 3630 el = builder.end("child") 3631 self.assertEquals("child", el.tag) 3632 self.assertEquals({'x':'X', 'y':'Y'}, el.attrib) 3633 self.assertEquals("CHILDTEXT", el.text) 3634 self.assertEquals(None, el.tail) 3635 builder.data("CHILDTAIL") 3636 root = builder.end("root") 3637 3638 self.assertEquals("root", root.tag) 3639 self.assertEquals("ROOTTEXT", root.text) 3640 self.assertEquals("CHILDTEXT", root[0].text) 3641 self.assertEquals("CHILDTAIL", root[0].tail)
3642
3643 - def test_treebuilder_target(self):
3644 parser = self.etree.XMLParser(target=self.etree.TreeBuilder()) 3645 parser.feed('<root>ROOTTEXT<child>CHILDTEXT</child>CHILDTAIL</root>') 3646 root = parser.close() 3647 3648 self.assertEquals("root", root.tag) 3649 self.assertEquals("ROOTTEXT", root.text) 3650 self.assertEquals("CHILDTEXT", root[0].text) 3651 self.assertEquals("CHILDTAIL", root[0].tail)
3652 3653 # helper methods 3654
3655 - def _writeElement(self, element, encoding='us-ascii'):
3656 """Write out element for comparison. 3657 """ 3658 data = self.etree.tostring(element, encoding=encoding) 3659 return canonicalize(data)
3660
3661 - def _writeElementFile(self, element, encoding='us-ascii'):
3662 """Write out element for comparison, using real file. 3663 """ 3664 ElementTree = self.etree.ElementTree 3665 handle, filename = tempfile.mkstemp() 3666 try: 3667 f = open(filename, 'wb') 3668 tree = ElementTree(element=element) 3669 tree.write(f, encoding=encoding) 3670 f.close() 3671 f = open(filename, 'rb') 3672 data = f.read() 3673 f.close() 3674 finally: 3675 os.close(handle) 3676 os.remove(filename) 3677 return canonicalize(data)
3678
3679 - def assertXML(self, expected, element, encoding='us-ascii'):
3680 """Writes element out and checks whether it is expected. 3681 3682 Does this two ways; once using BytesIO, once using a real file. 3683 """ 3684 if isinstance(expected, unicode): 3685 expected = expected.encode(encoding) 3686 self.assertEquals(expected, self._writeElement(element, encoding)) 3687 self.assertEquals(expected, self._writeElementFile(element, encoding))
3688
3689 - def assertEncodingDeclaration(self, result, encoding):
3690 "Checks if the result XML byte string specifies the encoding." 3691 enc_re = r"<\?xml[^>]+ encoding=[\"']([^\"']+)[\"']" 3692 if isinstance(result, str): 3693 has_encoding = re.compile(enc_re).match 3694 else: 3695 has_encoding = re.compile(_bytes(enc_re)).match 3696 self.assert_(has_encoding(result)) 3697 result_encoding = has_encoding(result).group(1) 3698 self.assertEquals(result_encoding.upper(), encoding.upper())
3699
3700 - def _rootstring(self, tree):
3701 return self.etree.tostring(tree.getroot()).replace( 3702 _bytes(' '), _bytes('')).replace(_bytes('\n'), _bytes(''))
3703
3704 - def _check_element_tree(self, tree):
3705 self._check_element(tree.getroot())
3706
3707 - def _check_element(self, element):
3708 self.assert_(hasattr(element, 'tag')) 3709 self.assert_(hasattr(element, 'attrib')) 3710 self.assert_(hasattr(element, 'text')) 3711 self.assert_(hasattr(element, 'tail')) 3712 self._check_string(element.tag) 3713 self._check_mapping(element.attrib) 3714 if element.text != None: 3715 self._check_string(element.text) 3716 if element.tail != None: 3717 self._check_string(element.tail)
3718
3719 - def _check_string(self, string):
3720 len(string) 3721 for char in string: 3722 self.assertEquals(1, len(char)) 3723 new_string = string + "" 3724 new_string = string + " " 3725 string[:0]
3726
3727 - def _check_mapping(self, mapping):
3728 len(mapping) 3729 keys = mapping.keys() 3730 values = mapping.values() 3731 items = mapping.items() 3732 for key in keys: 3733 item = mapping[key] 3734 mapping["key"] = "value" 3735 self.assertEquals("value", mapping["key"])
3736 3737 3738 if etree:
3739 - class ETreeTestCase(_ETreeTestCaseBase):
3740 etree = etree
3741 3742 if ElementTree:
3743 - class ElementTreeTestCase(_ETreeTestCaseBase):
3744 etree = ElementTree
3745 3746 filter_by_version( 3747 ElementTreeTestCase, 3748 ElementTreeTestCase.required_versions_ET, ET_VERSION) 3749 3750 if cElementTree:
3751 - class CElementTreeTestCase(_ETreeTestCaseBase):
3752 etree = cElementTree
3753 3754 filter_by_version( 3755 CElementTreeTestCase, 3756 CElementTreeTestCase.required_versions_cET, CET_VERSION) 3757
3758 -def test_suite():
3759 suite = unittest.TestSuite() 3760 if etree: 3761 suite.addTests([unittest.makeSuite(ETreeTestCase)]) 3762 if ElementTree: 3763 suite.addTests([unittest.makeSuite(ElementTreeTestCase)]) 3764 if cElementTree: 3765 suite.addTests([unittest.makeSuite(CElementTreeTestCase)]) 3766 return suite
3767 3768 if __name__ == '__main__': 3769 print('to test use test.py %s' % __file__) 3770