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

Source Code for Module lxml.tests.test_etree

   1  # -*- coding: utf-8 -*- 
   2   
   3  """ 
   4  Tests specific to the extended etree API 
   5   
   6  Tests that apply to the general ElementTree API should go into 
   7  test_elementtree 
   8  """ 
   9   
  10  from __future__ import absolute_import 
  11   
  12  import os.path 
  13  import unittest 
  14  import copy 
  15  import sys 
  16  import re 
  17  import gc 
  18  import operator 
  19  import tempfile 
  20  import textwrap 
  21  import zlib 
  22  import gzip 
  23  from contextlib import closing, contextmanager 
  24   
  25  from .common_imports import etree, StringIO, BytesIO, HelperTestCase 
  26  from .common_imports import fileInTestDir, fileUrlInTestDir, read_file, path2url 
  27  from .common_imports import SillyFileLike, LargeFileLikeUnicode, doctest, make_doctest 
  28  from .common_imports import canonicalize, _str, _bytes 
  29   
  30  print("") 
  31  print("TESTED VERSION: %s" % etree.__version__) 
  32  print("    Python:           " + repr(sys.version_info)) 
  33  print("    lxml.etree:       " + repr(etree.LXML_VERSION)) 
  34  print("    libxml used:      " + repr(etree.LIBXML_VERSION)) 
  35  print("    libxml compiled:  " + repr(etree.LIBXML_COMPILED_VERSION)) 
  36  print("    libxslt used:     " + repr(etree.LIBXSLT_VERSION)) 
  37  print("    libxslt compiled: " + repr(etree.LIBXSLT_COMPILED_VERSION)) 
  38  print("") 
  39   
  40  try: 
  41      _unicode = unicode 
  42  except NameError: 
  43      # Python 3 
  44      _unicode = str 
45 46 47 @contextmanager 48 -def tmpfile():
49 handle, filename = tempfile.mkstemp() 50 try: 51 yield filename 52 finally: 53 os.close(handle) 54 os.remove(filename)
55
56 57 -class ETreeOnlyTestCase(HelperTestCase):
58 """Tests only for etree, not ElementTree""" 59 etree = etree 60
61 - def test_version(self):
62 self.assertTrue(isinstance(etree.__version__, _unicode)) 63 self.assertTrue(isinstance(etree.LXML_VERSION, tuple)) 64 self.assertEqual(len(etree.LXML_VERSION), 4) 65 self.assertTrue(isinstance(etree.LXML_VERSION[0], int)) 66 self.assertTrue(isinstance(etree.LXML_VERSION[1], int)) 67 self.assertTrue(isinstance(etree.LXML_VERSION[2], int)) 68 self.assertTrue(isinstance(etree.LXML_VERSION[3], int)) 69 self.assertTrue(etree.__version__.startswith( 70 str(etree.LXML_VERSION[0])))
71
72 - def test_c_api(self):
73 if hasattr(self.etree, '__pyx_capi__'): 74 # newer Pyrex compatible C-API 75 self.assertTrue(isinstance(self.etree.__pyx_capi__, dict)) 76 self.assertTrue(len(self.etree.__pyx_capi__) > 0) 77 else: 78 # older C-API mechanism 79 self.assertTrue(hasattr(self.etree, '_import_c_api'))
80
81 - def test_include_paths(self):
82 import lxml 83 includes = lxml.get_include() 84 self.assertTrue(includes) 85 self.assertTrue(len(includes) >= 2) 86 self.assertTrue(os.path.join(os.path.dirname(lxml.__file__), 'includes') in includes, 87 includes)
88
89 - def test_element_names(self):
90 Element = self.etree.Element 91 el = Element('name') 92 self.assertEqual(el.tag, 'name') 93 el = Element('{}name') 94 self.assertEqual(el.tag, 'name')
95
96 - def test_element_name_empty(self):
97 Element = self.etree.Element 98 el = Element('name') 99 self.assertRaises(ValueError, Element, '{}') 100 self.assertRaises(ValueError, setattr, el, 'tag', '{}') 101 102 self.assertRaises(ValueError, Element, '{test}') 103 self.assertRaises(ValueError, setattr, el, 'tag', '{test}')
104
105 - def test_element_name_colon(self):
106 Element = self.etree.Element 107 self.assertRaises(ValueError, Element, 'p:name') 108 self.assertRaises(ValueError, Element, '{test}p:name') 109 110 el = Element('name') 111 self.assertRaises(ValueError, setattr, el, 'tag', 'p:name')
112
113 - def test_element_name_quote(self):
114 Element = self.etree.Element 115 self.assertRaises(ValueError, Element, "p'name") 116 self.assertRaises(ValueError, Element, 'p"name') 117 118 self.assertRaises(ValueError, Element, "{test}p'name") 119 self.assertRaises(ValueError, Element, '{test}p"name') 120 121 el = Element('name') 122 self.assertRaises(ValueError, setattr, el, 'tag', "p'name") 123 self.assertRaises(ValueError, setattr, el, 'tag', 'p"name')
124
125 - def test_element_name_space(self):
126 Element = self.etree.Element 127 self.assertRaises(ValueError, Element, ' name ') 128 self.assertRaises(ValueError, Element, 'na me') 129 self.assertRaises(ValueError, Element, '{test} name') 130 131 el = Element('name') 132 self.assertRaises(ValueError, setattr, el, 'tag', ' name ')
133
134 - def test_subelement_name_empty(self):
135 Element = self.etree.Element 136 SubElement = self.etree.SubElement 137 138 el = Element('name') 139 self.assertRaises(ValueError, SubElement, el, '{}') 140 self.assertRaises(ValueError, SubElement, el, '{test}')
141
142 - def test_subelement_name_colon(self):
143 Element = self.etree.Element 144 SubElement = self.etree.SubElement 145 146 el = Element('name') 147 self.assertRaises(ValueError, SubElement, el, 'p:name') 148 self.assertRaises(ValueError, SubElement, el, '{test}p:name')
149
150 - def test_subelement_name_quote(self):
151 Element = self.etree.Element 152 SubElement = self.etree.SubElement 153 154 el = Element('name') 155 self.assertRaises(ValueError, SubElement, el, "p'name") 156 self.assertRaises(ValueError, SubElement, el, "{test}p'name") 157 158 self.assertRaises(ValueError, SubElement, el, 'p"name') 159 self.assertRaises(ValueError, SubElement, el, '{test}p"name')
160
161 - def test_subelement_name_space(self):
162 Element = self.etree.Element 163 SubElement = self.etree.SubElement 164 165 el = Element('name') 166 self.assertRaises(ValueError, SubElement, el, ' name ') 167 self.assertRaises(ValueError, SubElement, el, 'na me') 168 self.assertRaises(ValueError, SubElement, el, '{test} name')
169
171 Element = self.etree.Element 172 SubElement = self.etree.SubElement 173 174 el = Element('name') 175 self.assertRaises(ValueError, SubElement, el, 'name', {'a b c' : 'abc'}) 176 self.assertRaises(ValueError, SubElement, el, 'name', {'a' : 'a\0\n'}) 177 self.assertEqual(0, len(el))
178
179 - def test_qname_empty(self):
180 QName = self.etree.QName 181 self.assertRaises(ValueError, QName, '') 182 self.assertRaises(ValueError, QName, 'test', '')
183
184 - def test_qname_colon(self):
185 QName = self.etree.QName 186 self.assertRaises(ValueError, QName, 'p:name') 187 self.assertRaises(ValueError, QName, 'test', 'p:name')
188
189 - def test_qname_space(self):
190 QName = self.etree.QName 191 self.assertRaises(ValueError, QName, ' name ') 192 self.assertRaises(ValueError, QName, 'na me') 193 self.assertRaises(ValueError, QName, 'test', ' name')
194
196 # ET doesn't have namespace/localname properties on QNames 197 QName = self.etree.QName 198 namespace, localname = 'http://myns', 'a' 199 qname = QName(namespace, localname) 200 self.assertEqual(namespace, qname.namespace) 201 self.assertEqual(localname, qname.localname)
202
203 - def test_qname_element(self):
204 # ET doesn't have namespace/localname properties on QNames 205 QName = self.etree.QName 206 qname1 = QName('http://myns', 'a') 207 a = self.etree.Element(qname1, nsmap={'p' : 'http://myns'}) 208 209 qname2 = QName(a) 210 self.assertEqual(a.tag, qname1.text) 211 self.assertEqual(qname1.text, qname2.text) 212 self.assertEqual(qname1, qname2)
213
214 - def test_qname_text_resolve(self):
215 # ET doesn't resove QNames as text values 216 etree = self.etree 217 qname = etree.QName('http://myns', 'a') 218 a = etree.Element(qname, nsmap={'p' : 'http://myns'}) 219 a.text = qname 220 221 self.assertEqual("p:a", a.text)
222
223 - def test_nsmap_prefix_invalid(self):
224 etree = self.etree 225 self.assertRaises(ValueError, 226 etree.Element, "root", nsmap={'"' : 'testns'}) 227 self.assertRaises(ValueError, 228 etree.Element, "root", nsmap={'&' : 'testns'}) 229 self.assertRaises(ValueError, 230 etree.Element, "root", nsmap={'a:b' : 'testns'})
231
232 - def test_attribute_has_key(self):
233 # ET in Py 3.x has no "attrib.has_key()" method 234 XML = self.etree.XML 235 236 root = XML(_bytes('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')) 237 self.assertEqual( 238 True, root.attrib.has_key('bar')) 239 self.assertEqual( 240 False, root.attrib.has_key('baz')) 241 self.assertEqual( 242 False, root.attrib.has_key('hah')) 243 self.assertEqual( 244 True, 245 root.attrib.has_key('{http://ns.codespeak.net/test}baz'))
246
247 - def test_attribute_set(self):
248 Element = self.etree.Element 249 root = Element("root") 250 root.set("attr", "TEST") 251 self.assertEqual("TEST", root.get("attr"))
252
254 # ElementTree accepts arbitrary attribute values 255 # lxml.etree allows only strings 256 Element = self.etree.Element 257 258 root = Element("root") 259 root.set("attr", "TEST") 260 self.assertEqual("TEST", root.get("attr")) 261 self.assertRaises(TypeError, root.set, "newattr", 5)
262
263 - def test_attrib_and_keywords(self):
264 Element = self.etree.Element 265 266 root = Element("root") 267 root.set("attr", "TEST") 268 self.assertEqual("TEST", root.attrib["attr"]) 269 270 root2 = Element("root2", root.attrib, attr2='TOAST') 271 self.assertEqual("TEST", root2.attrib["attr"]) 272 self.assertEqual("TOAST", root2.attrib["attr2"]) 273 self.assertEqual(None, root.attrib.get("attr2"))
274
275 - def test_attrib_order(self):
276 Element = self.etree.Element 277 278 keys = ["attr%d" % i for i in range(10)] 279 values = ["TEST-%d" % i for i in range(10)] 280 items = list(zip(keys, values)) 281 282 root = Element("root") 283 for key, value in items: 284 root.set(key, value) 285 self.assertEqual(keys, root.attrib.keys()) 286 self.assertEqual(values, root.attrib.values()) 287 288 root2 = Element("root2", root.attrib, 289 attr_99='TOAST-1', attr_98='TOAST-2') 290 self.assertEqual(['attr_98', 'attr_99'] + keys, 291 root2.attrib.keys()) 292 self.assertEqual(['TOAST-2', 'TOAST-1'] + values, 293 root2.attrib.values()) 294 295 self.assertEqual(keys, root.attrib.keys()) 296 self.assertEqual(values, root.attrib.values())
297
298 - def test_attribute_set_invalid(self):
299 # ElementTree accepts arbitrary attribute values 300 # lxml.etree allows only strings, or None for (html5) boolean attributes 301 Element = self.etree.Element 302 root = Element("root") 303 self.assertRaises(TypeError, root.set, "newattr", 5) 304 self.assertRaises(TypeError, root.set, "newattr", object) 305 self.assertRaises(TypeError, root.set, "newattr", None) 306 self.assertRaises(TypeError, root.set, "newattr")
307
308 - def test_strip_attributes(self):
309 XML = self.etree.XML 310 xml = _bytes('<test a="5" b="10" c="20"><x a="4" b="2"/></test>') 311 312 root = XML(xml) 313 self.etree.strip_attributes(root, 'a') 314 self.assertEqual(_bytes('<test b="10" c="20"><x b="2"></x></test>'), 315 self._writeElement(root)) 316 317 root = XML(xml) 318 self.etree.strip_attributes(root, 'b', 'c') 319 self.assertEqual(_bytes('<test a="5"><x a="4"></x></test>'), 320 self._writeElement(root))
321
322 - def test_strip_attributes_ns(self):
323 XML = self.etree.XML 324 xml = _bytes('<test xmlns:n="http://test/ns" a="6" b="10" c="20" n:a="5"><x a="4" n:b="2"/></test>') 325 326 root = XML(xml) 327 self.etree.strip_attributes(root, 'a') 328 self.assertEqual( 329 _bytes('<test xmlns:n="http://test/ns" b="10" c="20" n:a="5"><x n:b="2"></x></test>'), 330 self._writeElement(root)) 331 332 root = XML(xml) 333 self.etree.strip_attributes(root, '{http://test/ns}a', 'c') 334 self.assertEqual( 335 _bytes('<test xmlns:n="http://test/ns" a="6" b="10"><x a="4" n:b="2"></x></test>'), 336 self._writeElement(root)) 337 338 root = XML(xml) 339 self.etree.strip_attributes(root, '{http://test/ns}*') 340 self.assertEqual( 341 _bytes('<test xmlns:n="http://test/ns" a="6" b="10" c="20"><x a="4"></x></test>'), 342 self._writeElement(root))
343
344 - def test_strip_elements(self):
345 XML = self.etree.XML 346 xml = _bytes('<test><a><b><c/></b></a><x><a><b/><c/></a></x></test>') 347 348 root = XML(xml) 349 self.etree.strip_elements(root, 'a') 350 self.assertEqual(_bytes('<test><x></x></test>'), 351 self._writeElement(root)) 352 353 root = XML(xml) 354 self.etree.strip_elements(root, 'b', 'c', 'X', 'Y', 'Z') 355 self.assertEqual(_bytes('<test><a></a><x><a></a></x></test>'), 356 self._writeElement(root)) 357 358 root = XML(xml) 359 self.etree.strip_elements(root, 'c') 360 self.assertEqual(_bytes('<test><a><b></b></a><x><a><b></b></a></x></test>'), 361 self._writeElement(root))
362
363 - def test_strip_elements_ns(self):
364 XML = self.etree.XML 365 xml = _bytes('<test>TEST<n:a xmlns:n="urn:a">A<b>B<c xmlns="urn:c"/>C</b>BT</n:a>AT<x>X<a>A<b xmlns="urn:a"/>BT<c xmlns="urn:x"/>CT</a>AT</x>XT</test>') 366 367 root = XML(xml) 368 self.etree.strip_elements(root, 'a') 369 self.assertEqual(_bytes('<test>TEST<n:a xmlns:n="urn:a">A<b>B<c xmlns="urn:c"></c>C</b>BT</n:a>AT<x>X</x>XT</test>'), 370 self._writeElement(root)) 371 372 root = XML(xml) 373 self.etree.strip_elements(root, '{urn:a}b', 'c') 374 self.assertEqual(_bytes('<test>TEST<n:a xmlns:n="urn:a">A<b>B<c xmlns="urn:c"></c>C</b>BT</n:a>AT<x>X<a>A<c xmlns="urn:x"></c>CT</a>AT</x>XT</test>'), 375 self._writeElement(root)) 376 377 root = XML(xml) 378 self.etree.strip_elements(root, '{urn:a}*', 'c') 379 self.assertEqual(_bytes('<test>TEST<x>X<a>A<c xmlns="urn:x"></c>CT</a>AT</x>XT</test>'), 380 self._writeElement(root)) 381 382 root = XML(xml) 383 self.etree.strip_elements(root, '{urn:a}*', 'c', with_tail=False) 384 self.assertEqual(_bytes('<test>TESTAT<x>X<a>ABT<c xmlns="urn:x"></c>CT</a>AT</x>XT</test>'), 385 self._writeElement(root))
386
387 - def test_strip_tags(self):
388 XML = self.etree.XML 389 xml = _bytes('<test>TEST<a>A<b>B<c/>CT</b>BT</a>AT<x>X<a>A<b/>BT<c/>CT</a>AT</x>XT</test>') 390 391 root = XML(xml) 392 self.etree.strip_tags(root, 'a') 393 self.assertEqual(_bytes('<test>TESTA<b>B<c></c>CT</b>BTAT<x>XA<b></b>BT<c></c>CTAT</x>XT</test>'), 394 self._writeElement(root)) 395 396 root = XML(xml) 397 self.etree.strip_tags(root, 'b', 'c', 'X', 'Y', 'Z') 398 self.assertEqual(_bytes('<test>TEST<a>ABCTBT</a>AT<x>X<a>ABTCT</a>AT</x>XT</test>'), 399 self._writeElement(root)) 400 401 root = XML(xml) 402 self.etree.strip_tags(root, 'c') 403 self.assertEqual(_bytes('<test>TEST<a>A<b>BCT</b>BT</a>AT<x>X<a>A<b></b>BTCT</a>AT</x>XT</test>'), 404 self._writeElement(root))
405
406 - def test_strip_tags_pi_comment(self):
407 XML = self.etree.XML 408 PI = self.etree.ProcessingInstruction 409 Comment = self.etree.Comment 410 xml = _bytes('<!--comment1-->\n<?PI1?>\n<test>TEST<!--comment2-->XT<?PI2?></test>\n<!--comment3-->\n<?PI1?>') 411 412 root = XML(xml) 413 self.etree.strip_tags(root, PI) 414 self.assertEqual(_bytes('<!--comment1-->\n<?PI1?>\n<test>TEST<!--comment2-->XT</test>\n<!--comment3-->\n<?PI1?>'), 415 self._writeElement(root)) 416 417 root = XML(xml) 418 self.etree.strip_tags(root, Comment) 419 self.assertEqual(_bytes('<!--comment1-->\n<?PI1?>\n<test>TESTXT<?PI2?></test>\n<!--comment3-->\n<?PI1?>'), 420 self._writeElement(root)) 421 422 root = XML(xml) 423 self.etree.strip_tags(root, PI, Comment) 424 self.assertEqual(_bytes('<!--comment1-->\n<?PI1?>\n<test>TESTXT</test>\n<!--comment3-->\n<?PI1?>'), 425 self._writeElement(root)) 426 427 root = XML(xml) 428 self.etree.strip_tags(root, Comment, PI) 429 self.assertEqual(_bytes('<!--comment1-->\n<?PI1?>\n<test>TESTXT</test>\n<!--comment3-->\n<?PI1?>'), 430 self._writeElement(root))
431
433 XML = self.etree.XML 434 ElementTree = self.etree.ElementTree 435 PI = self.etree.ProcessingInstruction 436 Comment = self.etree.Comment 437 xml = _bytes('<!--comment1-->\n<?PI1?>\n<test>TEST<!--comment2-->XT<?PI2?></test>\n<!--comment3-->\n<?PI1?>') 438 439 root = XML(xml) 440 self.etree.strip_tags(ElementTree(root), PI) 441 self.assertEqual(_bytes('<!--comment1-->\n<test>TEST<!--comment2-->XT</test>\n<!--comment3-->'), 442 self._writeElement(root)) 443 444 root = XML(xml) 445 self.etree.strip_tags(ElementTree(root), Comment) 446 self.assertEqual(_bytes('<?PI1?>\n<test>TESTXT<?PI2?></test>\n<?PI1?>'), 447 self._writeElement(root)) 448 449 root = XML(xml) 450 self.etree.strip_tags(ElementTree(root), PI, Comment) 451 self.assertEqual(_bytes('<test>TESTXT</test>'), 452 self._writeElement(root)) 453 454 root = XML(xml) 455 self.etree.strip_tags(ElementTree(root), Comment, PI) 456 self.assertEqual(_bytes('<test>TESTXT</test>'), 457 self._writeElement(root))
458
459 - def test_strip_tags_doc_style(self):
460 XML = self.etree.XML 461 xml = _bytes(''' 462 <div> 463 <div> 464 I like <strong>sheep</strong>. 465 <br/> 466 I like lots of <strong>sheep</strong>. 467 <br/> 468 Click <a href="http://www.sheep.com">here</a> 469 for <a href="http://www.sheep.com">those</a> sheep. 470 <br/> 471 </div> 472 </div> 473 '''.strip()) 474 475 root = XML(xml) 476 self.etree.strip_tags(root, 'a') 477 self.assertEqual(re.sub(_bytes('</?a[^>]*>'), _bytes(''), xml).replace(_bytes('<br/>'), _bytes('<br></br>')), 478 self._writeElement(root)) 479 480 root = XML(xml) 481 self.etree.strip_tags(root, 'a', 'br') 482 self.assertEqual(re.sub(_bytes('</?a[^>]*>'), _bytes(''), 483 re.sub(_bytes('<br[^>]*>'), _bytes(''), xml)), 484 self._writeElement(root))
485
486 - def test_strip_tags_ns(self):
487 XML = self.etree.XML 488 xml = _bytes('<test>TEST<n:a xmlns:n="urn:a">A<b>B<c xmlns="urn:c"/>CT</b>BT</n:a>AT<x>X<a>A<b xmlns="urn:a"/>BT<c xmlns="urn:x"/>CT</a>AT</x>XT</test>') 489 490 root = XML(xml) 491 self.etree.strip_tags(root, 'a') 492 self.assertEqual(_bytes('<test>TEST<n:a xmlns:n="urn:a">A<b>B<c xmlns="urn:c"></c>CT</b>BT</n:a>AT<x>XA<b xmlns="urn:a"></b>BT<c xmlns="urn:x"></c>CTAT</x>XT</test>'), 493 self._writeElement(root)) 494 495 root = XML(xml) 496 self.etree.strip_tags(root, '{urn:a}b', 'c') 497 self.assertEqual(_bytes('<test>TEST<n:a xmlns:n="urn:a">A<b>B<c xmlns="urn:c"></c>CT</b>BT</n:a>AT<x>X<a>ABT<c xmlns="urn:x"></c>CT</a>AT</x>XT</test>'), 498 self._writeElement(root)) 499 500 root = XML(xml) 501 self.etree.strip_tags(root, '{urn:a}*', 'c') 502 self.assertEqual(_bytes('<test>TESTA<b>B<c xmlns="urn:c"></c>CT</b>BTAT<x>X<a>ABT<c xmlns="urn:x"></c>CT</a>AT</x>XT</test>'), 503 self._writeElement(root))
504
505 - def test_strip_tags_and_remove(self):
506 # previously crashed 507 HTML = self.etree.HTML 508 root = HTML(_bytes('<div><h1>title</h1> <b>foo</b> <p>boo</p></div>'))[0][0] 509 self.assertEqual(_bytes('<div><h1>title</h1> <b>foo</b> <p>boo</p></div>'), 510 self.etree.tostring(root)) 511 self.etree.strip_tags(root, 'b') 512 self.assertEqual(_bytes('<div><h1>title</h1> foo <p>boo</p></div>'), 513 self.etree.tostring(root)) 514 root.remove(root[0]) 515 self.assertEqual(_bytes('<div><p>boo</p></div>'), 516 self.etree.tostring(root))
517
518 - def test_pi(self):
519 # lxml.etree separates target and text 520 Element = self.etree.Element 521 SubElement = self.etree.SubElement 522 ProcessingInstruction = self.etree.ProcessingInstruction 523 524 a = Element('a') 525 a.append(ProcessingInstruction('foo', 'some more text')) 526 self.assertEqual(a[0].target, 'foo') 527 self.assertEqual(a[0].text, 'some more text')
528
529 - def test_pi_parse(self):
530 XML = self.etree.XML 531 root = XML(_bytes("<test><?mypi my test ?></test>")) 532 self.assertEqual(root[0].target, "mypi") 533 self.assertEqual(root[0].text, "my test ")
534
536 XML = self.etree.XML 537 root = XML(_bytes("<test><?mypi my='1' test=\" abc \" quotes=\"' '\" only names ?></test>")) 538 self.assertEqual(root[0].target, "mypi") 539 self.assertEqual(root[0].get('my'), "1") 540 self.assertEqual(root[0].get('test'), " abc ") 541 self.assertEqual(root[0].get('quotes'), "' '") 542 self.assertEqual(root[0].get('only'), None) 543 self.assertEqual(root[0].get('names'), None) 544 self.assertEqual(root[0].get('nope'), None)
545
547 XML = self.etree.XML 548 root = XML(_bytes("<test><?mypi my='1' test=\" abc \" quotes=\"' '\" only names ?></test>")) 549 self.assertEqual(root[0].target, "mypi") 550 self.assertEqual(root[0].attrib['my'], "1") 551 self.assertEqual(root[0].attrib['test'], " abc ") 552 self.assertEqual(root[0].attrib['quotes'], "' '") 553 self.assertRaises(KeyError, root[0].attrib.__getitem__, 'only') 554 self.assertRaises(KeyError, root[0].attrib.__getitem__, 'names') 555 self.assertRaises(KeyError, root[0].attrib.__getitem__, 'nope')
556
557 - def test_deepcopy_pi(self):
558 # previously caused a crash 559 ProcessingInstruction = self.etree.ProcessingInstruction 560 561 a = ProcessingInstruction("PI", "ONE") 562 b = copy.deepcopy(a) 563 b.text = "ANOTHER" 564 565 self.assertEqual('ONE', a.text) 566 self.assertEqual('ANOTHER', b.text)
567
569 XML = self.etree.XML 570 tostring = self.etree.tostring 571 root = XML(_bytes("<?mypi my test ?><test/><!--comment -->")) 572 tree1 = self.etree.ElementTree(root) 573 self.assertEqual(_bytes("<?mypi my test ?><test/><!--comment -->"), 574 tostring(tree1)) 575 576 tree2 = copy.deepcopy(tree1) 577 self.assertEqual(_bytes("<?mypi my test ?><test/><!--comment -->"), 578 tostring(tree2)) 579 580 root2 = copy.deepcopy(tree1.getroot()) 581 self.assertEqual(_bytes("<test/>"), 582 tostring(root2))
583
585 XML = self.etree.XML 586 tostring = self.etree.tostring 587 xml = _bytes('<!DOCTYPE test [\n<!ENTITY entity "tasty">\n]>\n<test/>') 588 root = XML(xml) 589 tree1 = self.etree.ElementTree(root) 590 self.assertEqual(xml, tostring(tree1)) 591 592 tree2 = copy.deepcopy(tree1) 593 self.assertEqual(xml, tostring(tree2)) 594 595 root2 = copy.deepcopy(tree1.getroot()) 596 self.assertEqual(_bytes("<test/>"), 597 tostring(root2))
598
599 - def test_deepcopy_pi_dtd(self):
600 XML = self.etree.XML 601 tostring = self.etree.tostring 602 xml = _bytes('<!-- comment --><!DOCTYPE test [\n<!ENTITY entity "tasty">\n]>\n<test/>') 603 root = XML(xml) 604 tree1 = self.etree.ElementTree(root) 605 self.assertEqual(xml, tostring(tree1)) 606 607 tree2 = copy.deepcopy(tree1) 608 self.assertEqual(xml, tostring(tree2))
609
610 - def test_parse_remove_comments(self):
611 fromstring = self.etree.fromstring 612 tostring = self.etree.tostring 613 XMLParser = self.etree.XMLParser 614 615 xml = _bytes('<a><!--A--><b><!-- B --><c/></b><!--C--></a>') 616 parser = XMLParser(remove_comments=True) 617 root = fromstring(xml, parser) 618 self.assertEqual( 619 _bytes('<a><b><c/></b></a>'), 620 tostring(root))
621
622 - def test_parse_remove_pis(self):
623 parse = self.etree.parse 624 tostring = self.etree.tostring 625 XMLParser = self.etree.XMLParser 626 627 xml = _bytes('<?test?><a><?A?><b><?B?><c/></b><?C?></a><?tail?>') 628 629 f = BytesIO(xml) 630 tree = parse(f) 631 self.assertEqual( 632 xml, 633 tostring(tree)) 634 635 parser = XMLParser(remove_pis=True) 636 tree = parse(f, parser) 637 self.assertEqual( 638 _bytes('<a><b><c/></b></a>'), 639 tostring(tree))
640
642 # ET raises IOError only 643 parse = self.etree.parse 644 self.assertRaises(TypeError, parse, 'notthere.xml', object())
645
647 # ET removes comments 648 iterparse = self.etree.iterparse 649 tostring = self.etree.tostring 650 651 f = BytesIO('<a><!--A--><b><!-- B --><c/></b><!--C--></a>') 652 events = list(iterparse(f)) 653 root = events[-1][1] 654 self.assertEqual(3, len(events)) 655 self.assertEqual( 656 _bytes('<a><!--A--><b><!-- B --><c/></b><!--C--></a>'), 657 tostring(root))
658
659 - def test_iterparse_comments(self):
660 # ET removes comments 661 iterparse = self.etree.iterparse 662 tostring = self.etree.tostring 663 664 def name(event, el): 665 if event == 'comment': 666 return el.text 667 else: 668 return el.tag
669 670 f = BytesIO('<a><!--A--><b><!-- B --><c/></b><!--C--></a>') 671 events = list(iterparse(f, events=('end', 'comment'))) 672 root = events[-1][1] 673 self.assertEqual(6, len(events)) 674 self.assertEqual(['A', ' B ', 'c', 'b', 'C', 'a'], 675 [ name(*item) for item in events ]) 676 self.assertEqual( 677 _bytes('<a><!--A--><b><!-- B --><c/></b><!--C--></a>'), 678 tostring(root))
679
680 - def test_iterparse_pis(self):
681 # ET removes pis 682 iterparse = self.etree.iterparse 683 tostring = self.etree.tostring 684 ElementTree = self.etree.ElementTree 685 686 def name(event, el): 687 if event == 'pi': 688 return (el.target, el.text) 689 else: 690 return el.tag
691 692 f = BytesIO('<?pia a?><a><?pib b?><b><?pic c?><c/></b><?pid d?></a><?pie e?>') 693 events = list(iterparse(f, events=('end', 'pi'))) 694 root = events[-2][1] 695 self.assertEqual(8, len(events)) 696 self.assertEqual([('pia','a'), ('pib','b'), ('pic','c'), 'c', 'b', 697 ('pid','d'), 'a', ('pie','e')], 698 [ name(*item) for item in events ]) 699 self.assertEqual( 700 _bytes('<?pia a?><a><?pib b?><b><?pic c?><c/></b><?pid d?></a><?pie e?>'), 701 tostring(ElementTree(root))) 702
703 - def test_iterparse_remove_comments(self):
704 iterparse = self.etree.iterparse 705 tostring = self.etree.tostring 706 707 f = BytesIO('<a><!--A--><b><!-- B --><c/></b><!--C--></a>') 708 events = list(iterparse(f, remove_comments=True, 709 events=('end', 'comment'))) 710 root = events[-1][1] 711 self.assertEqual(3, len(events)) 712 self.assertEqual(['c', 'b', 'a'], 713 [ el.tag for (event, el) in events ]) 714 self.assertEqual( 715 _bytes('<a><b><c/></b></a>'), 716 tostring(root))
717
718 - def test_iterparse_broken(self):
719 iterparse = self.etree.iterparse 720 f = BytesIO('<a><b><c/></a>') 721 # ET raises ExpatError, lxml raises XMLSyntaxError 722 self.assertRaises(self.etree.XMLSyntaxError, list, iterparse(f))
723
724 - def test_iterparse_broken_recover(self):
725 iterparse = self.etree.iterparse 726 f = BytesIO('<a><b><c/></a>') 727 it = iterparse(f, events=('start', 'end'), recover=True) 728 events = [(ev, el.tag) for ev, el in it] 729 root = it.root 730 self.assertTrue(root is not None) 731 732 self.assertEqual(1, events.count(('start', 'a'))) 733 self.assertEqual(1, events.count(('end', 'a'))) 734 735 self.assertEqual(1, events.count(('start', 'b'))) 736 self.assertEqual(1, events.count(('end', 'b'))) 737 738 self.assertEqual(1, events.count(('start', 'c'))) 739 self.assertEqual(1, events.count(('end', 'c')))
740
741 - def test_iterparse_broken_multi_recover(self):
742 iterparse = self.etree.iterparse 743 f = BytesIO('<a><b><c/></d><b><c/></a></b>') 744 it = iterparse(f, events=('start', 'end'), recover=True) 745 events = [(ev, el.tag) for ev, el in it] 746 root = it.root 747 self.assertTrue(root is not None) 748 749 self.assertEqual(1, events.count(('start', 'a'))) 750 self.assertEqual(1, events.count(('end', 'a'))) 751 752 self.assertEqual(2, events.count(('start', 'b'))) 753 self.assertEqual(2, events.count(('end', 'b'))) 754 755 self.assertEqual(2, events.count(('start', 'c'))) 756 self.assertEqual(2, events.count(('end', 'c')))
757
758 - def test_iterparse_strip(self):
759 iterparse = self.etree.iterparse 760 f = BytesIO(""" 761 <a> \n \n <b> b test </b> \n 762 763 \n\t <c> \n </c> </a> \n """) 764 iterator = iterparse(f, remove_blank_text=True) 765 text = [ (element.text, element.tail) 766 for event, element in iterator ] 767 self.assertEqual( 768 [(" b test ", None), (" \n ", None), (None, None)], 769 text)
770
771 - def test_iterparse_tag(self):
772 iterparse = self.etree.iterparse 773 f = BytesIO('<a><b><d/></b><c/></a>') 774 775 iterator = iterparse(f, tag="b", events=('start', 'end')) 776 events = list(iterator) 777 root = iterator.root 778 self.assertEqual( 779 [('start', root[0]), ('end', root[0])], 780 events)
781
782 - def test_iterparse_tag_all(self):
783 iterparse = self.etree.iterparse 784 f = BytesIO('<a><b><d/></b><c/></a>') 785 786 iterator = iterparse(f, tag="*", events=('start', 'end')) 787 events = list(iterator) 788 self.assertEqual( 789 8, 790 len(events))
791
792 - def test_iterparse_tag_ns(self):
793 iterparse = self.etree.iterparse 794 f = BytesIO('<a xmlns="urn:test:1"><b><d/></b><c/></a>') 795 796 iterator = iterparse(f, tag="{urn:test:1}b", events=('start', 'end')) 797 events = list(iterator) 798 root = iterator.root 799 self.assertEqual( 800 [('start', root[0]), ('end', root[0])], 801 events)
802
803 - def test_iterparse_tag_ns_empty(self):
804 iterparse = self.etree.iterparse 805 f = BytesIO('<a><b><d/></b><c/></a>') 806 iterator = iterparse(f, tag="{}b", events=('start', 'end')) 807 events = list(iterator) 808 root = iterator.root 809 self.assertEqual( 810 [('start', root[0]), ('end', root[0])], 811 events) 812 813 f = BytesIO('<a xmlns="urn:test:1"><b><d/></b><c/></a>') 814 iterator = iterparse(f, tag="{}b", events=('start', 'end')) 815 events = list(iterator) 816 root = iterator.root 817 self.assertEqual([], events)
818
819 - def test_iterparse_tag_ns_all(self):
820 iterparse = self.etree.iterparse 821 f = BytesIO('<a xmlns="urn:test:1"><b><d/></b><c/></a>') 822 iterator = iterparse(f, tag="{urn:test:1}*", events=('start', 'end')) 823 events = list(iterator) 824 self.assertEqual(8, len(events))
825
826 - def test_iterparse_tag_ns_empty_all(self):
827 iterparse = self.etree.iterparse 828 f = BytesIO('<a xmlns="urn:test:1"><b><d/></b><c/></a>') 829 iterator = iterparse(f, tag="{}*", events=('start', 'end')) 830 events = list(iterator) 831 self.assertEqual([], events) 832 833 f = BytesIO('<a><b><d/></b><c/></a>') 834 iterator = iterparse(f, tag="{}*", events=('start', 'end')) 835 events = list(iterator) 836 self.assertEqual(8, len(events))
837
838 - def test_iterparse_encoding_error(self):
839 text = _str('Søk på nettet') 840 wrong_declaration = "<?xml version='1.0' encoding='UTF-8'?>" 841 xml_latin1 = (_str('%s<a>%s</a>') % (wrong_declaration, text) 842 ).encode('iso-8859-1') 843 844 self.assertRaises(self.etree.ParseError, 845 list, self.etree.iterparse(BytesIO(xml_latin1)))
846
847 - def test_iterparse_encoding_8bit_override(self):
848 text = _str('Søk på nettet', encoding="UTF-8") 849 wrong_declaration = "<?xml version='1.0' encoding='UTF-8'?>" 850 xml_latin1 = (_str('%s<a>%s</a>') % (wrong_declaration, text) 851 ).encode('iso-8859-1') 852 853 iterator = self.etree.iterparse(BytesIO(xml_latin1), 854 encoding="iso-8859-1") 855 self.assertEqual(1, len(list(iterator))) 856 857 a = iterator.root 858 self.assertEqual(a.text, text)
859
860 - def test_iterparse_keep_cdata(self):
861 tostring = self.etree.tostring 862 f = BytesIO('<root><![CDATA[test]]></root>') 863 context = self.etree.iterparse(f, strip_cdata=False) 864 content = [ el.text for event,el in context ] 865 866 self.assertEqual(['test'], content) 867 self.assertEqual(_bytes('<root><![CDATA[test]]></root>'), 868 tostring(context.root))
869
870 - def test_parser_encoding_unknown(self):
871 self.assertRaises( 872 LookupError, self.etree.XMLParser, encoding="hopefully unknown")
873
874 - def test_parser_encoding(self):
875 self.etree.XMLParser(encoding="ascii") 876 self.etree.XMLParser(encoding="utf-8") 877 self.etree.XMLParser(encoding="iso-8859-1")
878
879 - def test_feed_parser_recover(self):
880 parser = self.etree.XMLParser(recover=True) 881 882 parser.feed('<?xml version=') 883 parser.feed('"1.0"?><ro') 884 parser.feed('ot><') 885 parser.feed('a test="works"') 886 parser.feed('><othertag/></root') # <a> not closed! 887 parser.feed('>') 888 889 root = parser.close() 890 891 self.assertEqual(root.tag, "root") 892 self.assertEqual(len(root), 1) 893 self.assertEqual(root[0].tag, "a") 894 self.assertEqual(root[0].get("test"), "works") 895 self.assertEqual(len(root[0]), 1) 896 self.assertEqual(root[0][0].tag, "othertag")
897 # FIXME: would be nice to get some errors logged ... 898 #self.assertTrue(len(parser.error_log) > 0, "error log is empty") 899
900 - def test_feed_parser_recover_no_id_dict(self):
901 # test that recover mode plays nicely with the no-id-dict setup 902 parser = self.etree.XMLParser(recover=True, collect_ids=False) 903 904 parser.feed('<?xml version=') 905 parser.feed('"1.0"?><ro') 906 parser.feed('ot xml:id="123"><') 907 parser.feed('a test="works" xml:id=') 908 parser.feed('"321"><othertag/></root') # <a> not closed! 909 parser.feed('>') 910 911 root = parser.close() 912 913 self.assertEqual(root.tag, "root") 914 self.assertEqual(len(root), 1) 915 self.assertEqual(root[0].tag, "a") 916 self.assertEqual(root[0].get("test"), "works") 917 self.assertEqual(root[0].attrib, { 918 'test': 'works', 919 '{http://www.w3.org/XML/1998/namespace}id': '321'}) 920 self.assertEqual(len(root[0]), 1) 921 self.assertEqual(root[0][0].tag, "othertag")
922 # FIXME: would be nice to get some errors logged ... 923 #self.assertTrue(len(parser.error_log) > 0, "error log is empty") 924
925 - def test_elementtree_parser_target_type_error(self):
926 assertEqual = self.assertEqual 927 assertFalse = self.assertFalse 928 929 events = [] 930 class Target(object): 931 def start(self, tag, attrib): 932 events.append("start") 933 assertFalse(attrib) 934 assertEqual("TAG", tag)
935 def end(self, tag): 936 events.append("end") 937 assertEqual("TAG", tag) 938 def close(self): 939 return "DONE" # no Element! 940 941 parser = self.etree.XMLParser(target=Target()) 942 tree = self.etree.ElementTree() 943 944 self.assertRaises(TypeError, 945 tree.parse, BytesIO("<TAG/>"), parser=parser) 946 self.assertEqual(["start", "end"], events) 947
948 - def test_parser_target_feed_exception(self):
949 # ET doesn't call .close() on errors 950 events = [] 951 class Target(object): 952 def start(self, tag, attrib): 953 events.append("start-" + tag)
954 def end(self, tag): 955 events.append("end-" + tag) 956 if tag == 'a': 957 raise ValueError("dead and gone") 958 def data(self, data): 959 events.append("data-" + data) 960 def close(self): 961 events.append("close") 962 return "DONE" 963 964 parser = self.etree.XMLParser(target=Target()) 965 966 try: 967 parser.feed(_bytes('<root>A<a>ca</a>B</root>')) 968 done = parser.close() 969 self.fail("error expected, but parsing succeeded") 970 except ValueError: 971 done = 'value error received as expected' 972 973 self.assertEqual(["start-root", "data-A", "start-a", 974 "data-ca", "end-a", "close"], 975 events) 976
977 - def test_parser_target_fromstring_exception(self):
978 # ET doesn't call .close() on errors 979 events = [] 980 class Target(object): 981 def start(self, tag, attrib): 982 events.append("start-" + tag)
983 def end(self, tag): 984 events.append("end-" + tag) 985 if tag == 'a': 986 raise ValueError("dead and gone") 987 def data(self, data): 988 events.append("data-" + data) 989 def close(self): 990 events.append("close") 991 return "DONE" 992 993 parser = self.etree.XMLParser(target=Target()) 994 995 try: 996 done = self.etree.fromstring(_bytes('<root>A<a>ca</a>B</root>'), 997 parser=parser) 998 self.fail("error expected, but parsing succeeded") 999 except ValueError: 1000 done = 'value error received as expected' 1001 1002 self.assertEqual(["start-root", "data-A", "start-a", 1003 "data-ca", "end-a", "close"], 1004 events) 1005
1006 - def test_parser_target_feed_no_id_dict(self):
1007 # test that target parsing works nicely with the no-id-hash setup 1008 events = [] 1009 class Target(object): 1010 def start(self, tag, attrib): 1011 events.append("start-" + tag)
1012 def end(self, tag): 1013 events.append("end-" + tag) 1014 def data(self, data): 1015 events.append("data-" + data) 1016 def comment(self, text): 1017 events.append("comment-" + text) 1018 def close(self): 1019 return "DONE" 1020 1021 parser = self.etree.XMLParser(target=Target(), collect_ids=False) 1022 1023 parser.feed(_bytes('<!--a--><root xml:id="123">A<!--b-->')) 1024 parser.feed(_bytes('<sub xml:id="321"/>B</root>')) 1025 done = parser.close() 1026 1027 self.assertEqual("DONE", done) 1028 self.assertEqual(["comment-a", "start-root", "data-A", "comment-b", 1029 "start-sub", "end-sub", "data-B", "end-root"], 1030 events) 1031
1032 - def test_parser_target_comment(self):
1033 events = [] 1034 class Target(object): 1035 def start(self, tag, attrib): 1036 events.append("start-" + tag)
1037 def end(self, tag): 1038 events.append("end-" + tag) 1039 def data(self, data): 1040 events.append("data-" + data) 1041 def comment(self, text): 1042 events.append("comment-" + text) 1043 def close(self): 1044 return "DONE" 1045 1046 parser = self.etree.XMLParser(target=Target()) 1047 1048 parser.feed(_bytes('<!--a--><root>A<!--b--><sub/><!--c-->B</root><!--d-->')) 1049 done = parser.close() 1050 1051 self.assertEqual("DONE", done) 1052 self.assertEqual(["comment-a", "start-root", "data-A", "comment-b", 1053 "start-sub", "end-sub", "comment-c", "data-B", 1054 "end-root", "comment-d"], 1055 events) 1056
1057 - def test_parser_target_pi(self):
1058 events = [] 1059 class Target(object): 1060 def start(self, tag, attrib): 1061 events.append("start-" + tag)
1062 def end(self, tag): 1063 events.append("end-" + tag) 1064 def data(self, data): 1065 events.append("data-" + data) 1066 def pi(self, target, data): 1067 events.append("pi-" + target + "-" + data) 1068 def close(self): 1069 return "DONE" 1070 1071 parser = self.etree.XMLParser(target=Target()) 1072 1073 parser.feed(_bytes('<?test a?><root>A<?test b?>B</root><?test c?>')) 1074 done = parser.close() 1075 1076 self.assertEqual("DONE", done) 1077 self.assertEqual(["pi-test-a", "start-root", "data-A", "pi-test-b", 1078 "data-B", "end-root", "pi-test-c"], 1079 events) 1080
1081 - def test_parser_target_cdata(self):
1082 events = [] 1083 class Target(object): 1084 def start(self, tag, attrib): 1085 events.append("start-" + tag)
1086 def end(self, tag): 1087 events.append("end-" + tag) 1088 def data(self, data): 1089 events.append("data-" + data) 1090 def close(self): 1091 return "DONE" 1092 1093 parser = self.etree.XMLParser(target=Target(), 1094 strip_cdata=False) 1095 1096 parser.feed(_bytes('<root>A<a><![CDATA[ca]]></a>B</root>')) 1097 done = parser.close() 1098 1099 self.assertEqual("DONE", done) 1100 self.assertEqual(["start-root", "data-A", "start-a", 1101 "data-ca", "end-a", "data-B", "end-root"], 1102 events) 1103
1104 - def test_parser_target_recover(self):
1105 events = [] 1106 class Target(object): 1107 def start(self, tag, attrib): 1108 events.append("start-" + tag)
1109 def end(self, tag): 1110 events.append("end-" + tag) 1111 def data(self, data): 1112 events.append("data-" + data) 1113 def close(self): 1114 events.append("close") 1115 return "DONE" 1116 1117 parser = self.etree.XMLParser(target=Target(), 1118 recover=True) 1119 1120 parser.feed(_bytes('<root>A<a>ca</a>B</not-root>')) 1121 done = parser.close() 1122 1123 self.assertEqual("DONE", done) 1124 self.assertEqual(["start-root", "data-A", "start-a", 1125 "data-ca", "end-a", "data-B", 1126 "end-root", "close"], 1127 events) 1128
1129 - def test_iterwalk_tag(self):
1130 iterwalk = self.etree.iterwalk 1131 root = self.etree.XML(_bytes('<a><b><d/></b><c/></a>')) 1132 1133 iterator = iterwalk(root, tag="b", events=('start', 'end')) 1134 events = list(iterator) 1135 self.assertEqual( 1136 [('start', root[0]), ('end', root[0])], 1137 events)
1138
1139 - def test_iterwalk_tag_all(self):
1140 iterwalk = self.etree.iterwalk 1141 root = self.etree.XML(_bytes('<a><b><d/></b><c/></a>')) 1142 1143 iterator = iterwalk(root, tag="*", events=('start', 'end')) 1144 events = list(iterator) 1145 self.assertEqual( 1146 8, 1147 len(events))
1148
1149 - def test_iterwalk(self):
1150 iterwalk = self.etree.iterwalk 1151 root = self.etree.XML(_bytes('<a><b></b><c/></a>')) 1152 1153 events = list(iterwalk(root)) 1154 self.assertEqual( 1155 [('end', root[0]), ('end', root[1]), ('end', root)], 1156 events)
1157
1158 - def test_iterwalk_start(self):
1159 iterwalk = self.etree.iterwalk 1160 root = self.etree.XML(_bytes('<a><b></b><c/></a>')) 1161 1162 iterator = iterwalk(root, events=('start',)) 1163 events = list(iterator) 1164 self.assertEqual( 1165 [('start', root), ('start', root[0]), ('start', root[1])], 1166 events)
1167
1168 - def test_iterwalk_start_end(self):
1169 iterwalk = self.etree.iterwalk 1170 root = self.etree.XML(_bytes('<a><b></b><c/></a>')) 1171 1172 iterator = iterwalk(root, events=('start','end')) 1173 events = list(iterator) 1174 self.assertEqual( 1175 [('start', root), ('start', root[0]), ('end', root[0]), 1176 ('start', root[1]), ('end', root[1]), ('end', root)], 1177 events)
1178
1179 - def test_iterwalk_clear(self):
1180 iterwalk = self.etree.iterwalk 1181 root = self.etree.XML(_bytes('<a><b></b><c/></a>')) 1182 1183 iterator = iterwalk(root) 1184 for event, elem in iterator: 1185 elem.clear() 1186 1187 self.assertEqual(0, 1188 len(root))
1189
1190 - def test_iterwalk_attrib_ns(self):
1191 iterwalk = self.etree.iterwalk 1192 root = self.etree.XML(_bytes('<a xmlns="ns1"><b><c xmlns="ns2"/></b></a>')) 1193 1194 attr_name = '{testns}bla' 1195 events = [] 1196 iterator = iterwalk(root, events=('start','end','start-ns','end-ns')) 1197 for event, elem in iterator: 1198 events.append(event) 1199 if event == 'start': 1200 if elem.tag != '{ns1}a': 1201 elem.set(attr_name, 'value') 1202 1203 self.assertEqual( 1204 ['start-ns', 'start', 'start', 'start-ns', 'start', 1205 'end', 'end-ns', 'end', 'end', 'end-ns'], 1206 events) 1207 1208 self.assertEqual( 1209 None, 1210 root.get(attr_name)) 1211 self.assertEqual( 1212 'value', 1213 root[0].get(attr_name))
1214
1215 - def test_iterwalk_end_skip(self):
1216 iterwalk = self.etree.iterwalk 1217 root = self.etree.XML(_bytes('<a><b><c/></b><d><e/></d></a>')) 1218 1219 iterator = iterwalk(root) 1220 tags = [] 1221 for event, elem in iterator: 1222 tags.append(elem.tag) 1223 # requesting a skip after an 'end' event should never have an effect 1224 iterator.skip_subtree() 1225 1226 self.assertEqual(['c', 'b', 'e', 'd', 'a'], tags)
1227
1228 - def test_iterwalk_start_end_skip(self):
1229 iterwalk = self.etree.iterwalk 1230 root = self.etree.XML(_bytes('<a><b><c/></b><d><e/></d></a>')) 1231 1232 iterator = iterwalk(root, events=('start', 'end')) 1233 tags = [] 1234 for event, elem in iterator: 1235 tags.append((event, elem.tag)) 1236 if elem.tag in ('b', 'e'): 1237 # skipping should only have an effect on 'start', not on 'end' 1238 iterator.skip_subtree() 1239 1240 self.assertEqual( 1241 [('start', 'a'), 1242 ('start', 'b'), ('end', 'b'), # ignored child 'c' 1243 ('start', 'd'), 1244 ('start', 'e'), ('end', 'e'), 1245 ('end', 'd'), 1246 ('end', 'a')], 1247 tags)
1248
1249 - def test_iterwalk_ns_skip(self):
1250 iterwalk = self.etree.iterwalk 1251 root = self.etree.XML(_bytes( 1252 '<a xmlns="ns1"><b xmlns="nsb"><c xmlns="ns2"/></b><d xmlns="ns2"><e/></d></a>')) 1253 1254 events = [] 1255 iterator = iterwalk(root, events=('start','start-ns','end-ns')) 1256 for event, elem in iterator: 1257 if event in ('start-ns', 'end-ns'): 1258 events.append((event, elem)) 1259 if event == 'start-ns' and elem == ('', 'nsb'): 1260 events.append('skip') 1261 iterator.skip_subtree() 1262 else: 1263 events.append((event, elem.tag)) 1264 1265 self.assertEqual( 1266 [('start-ns', ('', 'ns1')), 1267 ('start', '{ns1}a'), 1268 ('start-ns', ('', 'nsb')), 1269 'skip', 1270 ('start', '{nsb}b'), 1271 ('end-ns', None), 1272 ('start-ns', ('', 'ns2')), 1273 ('start', '{ns2}d'), 1274 ('start', '{ns2}e'), 1275 ('end-ns', None), 1276 ('end-ns', None) 1277 ], 1278 events)
1279
1280 - def test_iterwalk_getiterator(self):
1281 iterwalk = self.etree.iterwalk 1282 root = self.etree.XML(_bytes('<a><b><d/></b><c/></a>')) 1283 1284 counts = [] 1285 for event, elem in iterwalk(root): 1286 counts.append(len(list(elem.getiterator()))) 1287 self.assertEqual( 1288 [1,2,1,4], 1289 counts)
1290
1291 - def test_resolve_string_dtd(self):
1292 parse = self.etree.parse 1293 parser = self.etree.XMLParser(dtd_validation=True) 1294 assertEqual = self.assertEqual 1295 test_url = _str("__nosuch.dtd") 1296 1297 class MyResolver(self.etree.Resolver): 1298 def resolve(self, url, id, context): 1299 assertEqual(url, test_url) 1300 return self.resolve_string( 1301 _str('''<!ENTITY myentity "%s"> 1302 <!ELEMENT doc ANY>''') % url, context)
1303 1304 parser.resolvers.add(MyResolver()) 1305 1306 xml = _str('<!DOCTYPE doc SYSTEM "%s"><doc>&myentity;</doc>') % test_url 1307 tree = parse(StringIO(xml), parser) 1308 root = tree.getroot() 1309 self.assertEqual(root.text, test_url) 1310
1311 - def test_resolve_bytes_dtd(self):
1312 parse = self.etree.parse 1313 parser = self.etree.XMLParser(dtd_validation=True) 1314 assertEqual = self.assertEqual 1315 test_url = _str("__nosuch.dtd") 1316 1317 class MyResolver(self.etree.Resolver): 1318 def resolve(self, url, id, context): 1319 assertEqual(url, test_url) 1320 return self.resolve_string( 1321 (_str('''<!ENTITY myentity "%s"> 1322 <!ELEMENT doc ANY>''') % url).encode('utf-8'), 1323 context)
1324 1325 parser.resolvers.add(MyResolver()) 1326 1327 xml = _str('<!DOCTYPE doc SYSTEM "%s"><doc>&myentity;</doc>') % test_url 1328 tree = parse(StringIO(xml), parser) 1329 root = tree.getroot() 1330 self.assertEqual(root.text, test_url) 1331
1332 - def test_resolve_filelike_dtd(self):
1333 parse = self.etree.parse 1334 parser = self.etree.XMLParser(dtd_validation=True) 1335 assertEqual = self.assertEqual 1336 test_url = _str("__nosuch.dtd") 1337 1338 class MyResolver(self.etree.Resolver): 1339 def resolve(self, url, id, context): 1340 assertEqual(url, test_url) 1341 return self.resolve_file( 1342 SillyFileLike( 1343 _str('''<!ENTITY myentity "%s"> 1344 <!ELEMENT doc ANY>''') % url), context)
1345 1346 parser.resolvers.add(MyResolver()) 1347 1348 xml = _str('<!DOCTYPE doc SYSTEM "%s"><doc>&myentity;</doc>') % test_url 1349 tree = parse(StringIO(xml), parser) 1350 root = tree.getroot() 1351 self.assertEqual(root.text, test_url) 1352
1353 - def test_resolve_filename_dtd(self):
1354 parse = self.etree.parse 1355 parser = self.etree.XMLParser(attribute_defaults=True) 1356 assertEqual = self.assertEqual 1357 test_url = _str("__nosuch.dtd") 1358 1359 class MyResolver(self.etree.Resolver): 1360 def resolve(self, url, id, context): 1361 assertEqual(url, test_url) 1362 return self.resolve_filename( 1363 fileInTestDir('test.dtd'), context)
1364 1365 parser.resolvers.add(MyResolver()) 1366 1367 xml = _str('<!DOCTYPE a SYSTEM "%s"><a><b/></a>') % test_url 1368 tree = parse(StringIO(xml), parser) 1369 root = tree.getroot() 1370 self.assertEqual( 1371 root.attrib, {'default': 'valueA'}) 1372 self.assertEqual( 1373 root[0].attrib, {'default': 'valueB'}) 1374
1375 - def test_resolve_filename_dtd_relative(self):
1376 parse = self.etree.parse 1377 parser = self.etree.XMLParser(attribute_defaults=True) 1378 assertEqual = self.assertEqual 1379 test_url = _str("__nosuch.dtd") 1380 1381 class MyResolver(self.etree.Resolver): 1382 def resolve(self, url, id, context): 1383 expected = fileUrlInTestDir(test_url) 1384 url = url.replace('file://', 'file:') # depends on libxml2 version 1385 expected = expected.replace('file://', 'file:') 1386 assertEqual(url, expected) 1387 return self.resolve_filename( 1388 fileUrlInTestDir('test.dtd'), context)
1389 1390 parser.resolvers.add(MyResolver()) 1391 1392 xml = _str('<!DOCTYPE a SYSTEM "%s"><a><b/></a>') % test_url 1393 tree = parse(StringIO(xml), parser, 1394 base_url=fileUrlInTestDir('__test.xml')) 1395 root = tree.getroot() 1396 self.assertEqual( 1397 root.attrib, {'default': 'valueA'}) 1398 self.assertEqual( 1399 root[0].attrib, {'default': 'valueB'}) 1400
1401 - def test_resolve_file_dtd(self):
1402 parse = self.etree.parse 1403 parser = self.etree.XMLParser(attribute_defaults=True) 1404 assertEqual = self.assertEqual 1405 test_url = _str("__nosuch.dtd") 1406 1407 class MyResolver(self.etree.Resolver): 1408 def resolve(self, url, id, context): 1409 assertEqual(url, test_url) 1410 return self.resolve_file( 1411 open(fileInTestDir('test.dtd'), 'rb'), context)
1412 1413 parser.resolvers.add(MyResolver()) 1414 1415 xml = _str('<!DOCTYPE a SYSTEM "%s"><a><b/></a>') % test_url 1416 tree = parse(StringIO(xml), parser) 1417 root = tree.getroot() 1418 self.assertEqual( 1419 root.attrib, {'default': 'valueA'}) 1420 self.assertEqual( 1421 root[0].attrib, {'default': 'valueB'}) 1422
1423 - def test_resolve_empty(self):
1424 parse = self.etree.parse 1425 parser = self.etree.XMLParser(load_dtd=True) 1426 assertEqual = self.assertEqual 1427 test_url = _str("__nosuch.dtd") 1428 1429 class check(object): 1430 resolved = False
1431 1432 class MyResolver(self.etree.Resolver): 1433 def resolve(self, url, id, context): 1434 assertEqual(url, test_url) 1435 check.resolved = True 1436 return self.resolve_empty(context) 1437 1438 parser.resolvers.add(MyResolver()) 1439 1440 xml = _str('<!DOCTYPE doc SYSTEM "%s"><doc>&myentity;</doc>') % test_url 1441 self.assertRaises(etree.XMLSyntaxError, parse, StringIO(xml), parser) 1442 self.assertTrue(check.resolved) 1443
1444 - def test_resolve_error(self):
1445 parse = self.etree.parse 1446 parser = self.etree.XMLParser(dtd_validation=True) 1447 1448 class _LocalException(Exception): 1449 pass
1450 1451 class MyResolver(self.etree.Resolver): 1452 def resolve(self, url, id, context): 1453 raise _LocalException 1454 1455 parser.resolvers.add(MyResolver()) 1456 1457 xml = '<!DOCTYPE doc SYSTEM "test"><doc>&myentity;</doc>' 1458 self.assertRaises(_LocalException, parse, BytesIO(xml), parser) 1459 1460 if etree.LIBXML_VERSION > (2,6,20):
1461 - def test_entity_parse(self):
1462 parse = self.etree.parse 1463 tostring = self.etree.tostring 1464 parser = self.etree.XMLParser(resolve_entities=False) 1465 Entity = self.etree.Entity 1466 1467 xml = _bytes('<!DOCTYPE doc SYSTEM "test"><doc>&myentity;</doc>') 1468 tree = parse(BytesIO(xml), parser) 1469 root = tree.getroot() 1470 self.assertEqual(root[0].tag, Entity) 1471 self.assertEqual(root[0].text, "&myentity;") 1472 self.assertEqual(root[0].tail, None) 1473 self.assertEqual(root[0].name, "myentity") 1474 1475 self.assertEqual(_bytes('<doc>&myentity;</doc>'), 1476 tostring(root))
1477
1478 - def test_entity_restructure(self):
1479 xml = _bytes('''<!DOCTYPE root [ <!ENTITY nbsp "&#160;"> ]> 1480 <root> 1481 <child1/> 1482 <child2/> 1483 <child3>&nbsp;</child3> 1484 </root>''') 1485 1486 parser = self.etree.XMLParser(resolve_entities=False) 1487 root = etree.fromstring(xml, parser) 1488 self.assertEqual([ el.tag for el in root ], 1489 ['child1', 'child2', 'child3']) 1490 1491 root[0] = root[-1] 1492 self.assertEqual([ el.tag for el in root ], 1493 ['child3', 'child2']) 1494 self.assertEqual(root[0][0].text, '&nbsp;') 1495 self.assertEqual(root[0][0].name, 'nbsp')
1496
1497 - def test_entity_append(self):
1498 Entity = self.etree.Entity 1499 Element = self.etree.Element 1500 tostring = self.etree.tostring 1501 1502 root = Element("root") 1503 root.append( Entity("test") ) 1504 1505 self.assertEqual(root[0].tag, Entity) 1506 self.assertEqual(root[0].text, "&test;") 1507 self.assertEqual(root[0].tail, None) 1508 self.assertEqual(root[0].name, "test") 1509 1510 self.assertEqual(_bytes('<root>&test;</root>'), 1511 tostring(root))
1512
1513 - def test_entity_values(self):
1514 Entity = self.etree.Entity 1515 self.assertEqual(Entity("test").text, '&test;') 1516 self.assertEqual(Entity("#17683").text, '&#17683;') 1517 self.assertEqual(Entity("#x1768").text, '&#x1768;') 1518 self.assertEqual(Entity("#x98AF").text, '&#x98AF;')
1519
1520 - def test_entity_error(self):
1521 Entity = self.etree.Entity 1522 self.assertRaises(ValueError, Entity, 'a b c') 1523 self.assertRaises(ValueError, Entity, 'a,b') 1524 self.assertRaises(ValueError, Entity, 'a\0b') 1525 self.assertRaises(ValueError, Entity, '#abc') 1526 self.assertRaises(ValueError, Entity, '#xxyz')
1527
1528 - def test_cdata(self):
1529 CDATA = self.etree.CDATA 1530 Element = self.etree.Element 1531 tostring = self.etree.tostring 1532 1533 root = Element("root") 1534 root.text = CDATA('test') 1535 1536 self.assertEqual('test', 1537 root.text) 1538 self.assertEqual(_bytes('<root><![CDATA[test]]></root>'), 1539 tostring(root))
1540
1541 - def test_cdata_tail(self):
1542 CDATA = self.etree.CDATA 1543 Element = self.etree.Element 1544 SubElement = self.etree.SubElement 1545 tostring = self.etree.tostring 1546 1547 root = Element("root") 1548 child = SubElement(root, 'child') 1549 child.tail = CDATA('test') 1550 1551 self.assertEqual('test', child.tail) 1552 self.assertEqual(_bytes('<root><child/><![CDATA[test]]></root>'), 1553 tostring(root)) 1554 1555 root = Element("root") 1556 root.tail = CDATA('test') 1557 1558 self.assertEqual('test', root.tail) 1559 self.assertEqual(_bytes('<root/><![CDATA[test]]>'), 1560 tostring(root))
1561
1562 - def test_cdata_type(self):
1563 CDATA = self.etree.CDATA 1564 Element = self.etree.Element 1565 root = Element("root") 1566 1567 root.text = CDATA("test") 1568 self.assertEqual('test', root.text) 1569 1570 root.text = CDATA(_str("test")) 1571 self.assertEqual('test', root.text) 1572 1573 self.assertRaises(TypeError, CDATA, 1)
1574
1575 - def test_cdata_errors(self):
1576 CDATA = self.etree.CDATA 1577 Element = self.etree.Element 1578 1579 root = Element("root") 1580 cdata = CDATA('test') 1581 1582 self.assertRaises(TypeError, 1583 root.set, 'attr', cdata) 1584 self.assertRaises(TypeError, 1585 operator.setitem, root.attrib, 'attr', cdata)
1586
1587 - def test_cdata_parser(self):
1588 tostring = self.etree.tostring 1589 parser = self.etree.XMLParser(strip_cdata=False) 1590 root = self.etree.XML(_bytes('<root><![CDATA[test]]></root>'), parser) 1591 1592 self.assertEqual('test', root.text) 1593 self.assertEqual(_bytes('<root><![CDATA[test]]></root>'), 1594 tostring(root))
1595
1596 - def test_cdata_xpath(self):
1597 tostring = self.etree.tostring 1598 parser = self.etree.XMLParser(strip_cdata=False) 1599 root = self.etree.XML(_bytes('<root><![CDATA[test]]></root>'), parser) 1600 self.assertEqual(_bytes('<root><![CDATA[test]]></root>'), 1601 tostring(root)) 1602 1603 self.assertEqual(['test'], root.xpath('//text()'))
1604 1605 # TypeError in etree, AssertionError in ElementTree;
1606 - def test_setitem_assert(self):
1607 Element = self.etree.Element 1608 SubElement = self.etree.SubElement 1609 1610 a = Element('a') 1611 b = SubElement(a, 'b') 1612 1613 self.assertRaises(TypeError, 1614 a.__setitem__, 0, 'foo')
1615
1616 - def test_append_error(self):
1617 Element = self.etree.Element 1618 root = Element('root') 1619 # raises AssertionError in ElementTree 1620 self.assertRaises(TypeError, root.append, None) 1621 self.assertRaises(TypeError, root.extend, [None]) 1622 self.assertRaises(TypeError, root.extend, [Element('one'), None]) 1623 self.assertEqual('one', root[0].tag)
1624
1625 - def test_append_recursive_error(self):
1626 Element = self.etree.Element 1627 SubElement = self.etree.SubElement 1628 root = Element('root') 1629 self.assertRaises(ValueError, root.append, root) 1630 child = SubElement(root, 'child') 1631 self.assertRaises(ValueError, child.append, root) 1632 child2 = SubElement(child, 'child2') 1633 self.assertRaises(ValueError, child2.append, root) 1634 self.assertRaises(ValueError, child2.append, child) 1635 self.assertEqual('child2', root[0][0].tag)
1636
1637 - def test_addnext(self):
1638 Element = self.etree.Element 1639 SubElement = self.etree.SubElement 1640 root = Element('root') 1641 SubElement(root, 'a') 1642 SubElement(root, 'b') 1643 1644 self.assertEqual(['a', 'b'], 1645 [c.tag for c in root]) 1646 root[1].addnext(root[0]) 1647 self.assertEqual(['b', 'a'], 1648 [c.tag for c in root])
1649
1650 - def test_addprevious(self):
1651 Element = self.etree.Element 1652 SubElement = self.etree.SubElement 1653 root = Element('root') 1654 SubElement(root, 'a') 1655 SubElement(root, 'b') 1656 1657 self.assertEqual(['a', 'b'], 1658 [c.tag for c in root]) 1659 root[0].addprevious(root[1]) 1660 self.assertEqual(['b', 'a'], 1661 [c.tag for c in root])
1662
1663 - def test_addnext_cycle(self):
1664 Element = self.etree.Element 1665 SubElement = self.etree.SubElement 1666 root = Element('root') 1667 a = SubElement(root, 'a') 1668 b = SubElement(a, 'b') 1669 # appending parent as sibling is forbidden 1670 self.assertRaises(ValueError, b.addnext, a) 1671 self.assertEqual(['a'], [c.tag for c in root]) 1672 self.assertEqual(['b'], [c.tag for c in a])
1673
1674 - def test_addprevious_cycle(self):
1675 Element = self.etree.Element 1676 SubElement = self.etree.SubElement 1677 root = Element('root') 1678 a = SubElement(root, 'a') 1679 b = SubElement(a, 'b') 1680 # appending parent as sibling is forbidden 1681 self.assertRaises(ValueError, b.addprevious, a) 1682 self.assertEqual(['a'], [c.tag for c in root]) 1683 self.assertEqual(['b'], [c.tag for c in a])
1684
1685 - def test_addnext_cycle_long(self):
1686 Element = self.etree.Element 1687 SubElement = self.etree.SubElement 1688 root = Element('root') 1689 a = SubElement(root, 'a') 1690 b = SubElement(a, 'b') 1691 c = SubElement(b, 'c') 1692 # appending parent as sibling is forbidden 1693 self.assertRaises(ValueError, c.addnext, a)
1694
1695 - def test_addprevious_cycle_long(self):
1696 Element = self.etree.Element 1697 SubElement = self.etree.SubElement 1698 root = Element('root') 1699 a = SubElement(root, 'a') 1700 b = SubElement(a, 'b') 1701 c = SubElement(b, 'c') 1702 # appending parent as sibling is forbidden 1703 self.assertRaises(ValueError, c.addprevious, a)
1704
1705 - def test_addprevious_noops(self):
1706 Element = self.etree.Element 1707 SubElement = self.etree.SubElement 1708 root = Element('root') 1709 a = SubElement(root, 'a') 1710 b = SubElement(root, 'b') 1711 a.addprevious(a) 1712 self.assertEqual('a', root[0].tag) 1713 self.assertEqual('b', root[1].tag) 1714 b.addprevious(b) 1715 self.assertEqual('a', root[0].tag) 1716 self.assertEqual('b', root[1].tag) 1717 b.addprevious(a) 1718 self.assertEqual('a', root[0].tag) 1719 self.assertEqual('b', root[1].tag)
1720
1721 - def test_addnext_noops(self):
1722 Element = self.etree.Element 1723 SubElement = self.etree.SubElement 1724 root = Element('root') 1725 a = SubElement(root, 'a') 1726 b = SubElement(root, 'b') 1727 a.addnext(a) 1728 self.assertEqual('a', root[0].tag) 1729 self.assertEqual('b', root[1].tag) 1730 b.addnext(b) 1731 self.assertEqual('a', root[0].tag) 1732 self.assertEqual('b', root[1].tag) 1733 a.addnext(b) 1734 self.assertEqual('a', root[0].tag) 1735 self.assertEqual('b', root[1].tag)
1736
1737 - def test_addnext_root(self):
1738 Element = self.etree.Element 1739 a = Element('a') 1740 b = Element('b') 1741 self.assertRaises(TypeError, a.addnext, b)
1742
1743 - def test_addprevious_pi(self):
1744 Element = self.etree.Element 1745 SubElement = self.etree.SubElement 1746 PI = self.etree.PI 1747 root = Element('root') 1748 SubElement(root, 'a') 1749 pi = PI('TARGET', 'TEXT') 1750 pi.tail = "TAIL" 1751 1752 self.assertEqual(_bytes('<root><a></a></root>'), 1753 self._writeElement(root)) 1754 root[0].addprevious(pi) 1755 self.assertEqual(_bytes('<root><?TARGET TEXT?>TAIL<a></a></root>'), 1756 self._writeElement(root))
1757
1758 - def test_addprevious_root_pi(self):
1759 Element = self.etree.Element 1760 PI = self.etree.PI 1761 root = Element('root') 1762 pi = PI('TARGET', 'TEXT') 1763 pi.tail = "TAIL" 1764 1765 self.assertEqual(_bytes('<root></root>'), 1766 self._writeElement(root)) 1767 root.addprevious(pi) 1768 self.assertEqual(_bytes('<?TARGET TEXT?>\n<root></root>'), 1769 self._writeElement(root))
1770
1771 - def test_addnext_pi(self):
1772 Element = self.etree.Element 1773 SubElement = self.etree.SubElement 1774 PI = self.etree.PI 1775 root = Element('root') 1776 SubElement(root, 'a') 1777 pi = PI('TARGET', 'TEXT') 1778 pi.tail = "TAIL" 1779 1780 self.assertEqual(_bytes('<root><a></a></root>'), 1781 self._writeElement(root)) 1782 root[0].addnext(pi) 1783 self.assertEqual(_bytes('<root><a></a><?TARGET TEXT?>TAIL</root>'), 1784 self._writeElement(root))
1785
1786 - def test_addnext_root_pi(self):
1787 Element = self.etree.Element 1788 PI = self.etree.PI 1789 root = Element('root') 1790 pi = PI('TARGET', 'TEXT') 1791 pi.tail = "TAIL" 1792 1793 self.assertEqual(_bytes('<root></root>'), 1794 self._writeElement(root)) 1795 root.addnext(pi) 1796 self.assertEqual(_bytes('<root></root>\n<?TARGET TEXT?>'), 1797 self._writeElement(root))
1798
1799 - def test_addnext_comment(self):
1800 Element = self.etree.Element 1801 SubElement = self.etree.SubElement 1802 Comment = self.etree.Comment 1803 root = Element('root') 1804 SubElement(root, 'a') 1805 comment = Comment('TEXT ') 1806 comment.tail = "TAIL" 1807 1808 self.assertEqual(_bytes('<root><a></a></root>'), 1809 self._writeElement(root)) 1810 root[0].addnext(comment) 1811 self.assertEqual(_bytes('<root><a></a><!--TEXT -->TAIL</root>'), 1812 self._writeElement(root))
1813
1814 - def test_addnext_root_comment(self):
1815 Element = self.etree.Element 1816 Comment = self.etree.Comment 1817 root = Element('root') 1818 comment = Comment('TEXT ') 1819 comment.tail = "TAIL" 1820 1821 self.assertEqual(_bytes('<root></root>'), 1822 self._writeElement(root)) 1823 root.addnext(comment) 1824 self.assertEqual(_bytes('<root></root>\n<!--TEXT -->'), 1825 self._writeElement(root))
1826
1827 - def test_addprevious_comment(self):
1828 Element = self.etree.Element 1829 SubElement = self.etree.SubElement 1830 Comment = self.etree.Comment 1831 root = Element('root') 1832 SubElement(root, 'a') 1833 comment = Comment('TEXT ') 1834 comment.tail = "TAIL" 1835 1836 self.assertEqual(_bytes('<root><a></a></root>'), 1837 self._writeElement(root)) 1838 root[0].addprevious(comment) 1839 self.assertEqual(_bytes('<root><!--TEXT -->TAIL<a></a></root>'), 1840 self._writeElement(root))
1841
1842 - def test_addprevious_root_comment(self):
1843 Element = self.etree.Element 1844 Comment = self.etree.Comment 1845 root = Element('root') 1846 comment = Comment('TEXT ') 1847 comment.tail = "TAIL" 1848 1849 self.assertEqual(_bytes('<root></root>'), 1850 self._writeElement(root)) 1851 root.addprevious(