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_getiterator(self):
1216 iterwalk = self.etree.iterwalk 1217 root = self.etree.XML(_bytes('<a><b><d/></b><c/></a>')) 1218 1219 counts = [] 1220 for event, elem in iterwalk(root): 1221 counts.append(len(list(elem.getiterator()))) 1222 self.assertEqual( 1223 [1,2,1,4], 1224 counts)
1225
1226 - def test_resolve_string_dtd(self):
1227 parse = self.etree.parse 1228 parser = self.etree.XMLParser(dtd_validation=True) 1229 assertEqual = self.assertEqual 1230 test_url = _str("__nosuch.dtd") 1231 1232 class MyResolver(self.etree.Resolver): 1233 def resolve(self, url, id, context): 1234 assertEqual(url, test_url) 1235 return self.resolve_string( 1236 _str('''<!ENTITY myentity "%s"> 1237 <!ELEMENT doc ANY>''') % url, context)
1238 1239 parser.resolvers.add(MyResolver()) 1240 1241 xml = _str('<!DOCTYPE doc SYSTEM "%s"><doc>&myentity;</doc>') % test_url 1242 tree = parse(StringIO(xml), parser) 1243 root = tree.getroot() 1244 self.assertEqual(root.text, test_url) 1245
1246 - def test_resolve_bytes_dtd(self):
1247 parse = self.etree.parse 1248 parser = self.etree.XMLParser(dtd_validation=True) 1249 assertEqual = self.assertEqual 1250 test_url = _str("__nosuch.dtd") 1251 1252 class MyResolver(self.etree.Resolver): 1253 def resolve(self, url, id, context): 1254 assertEqual(url, test_url) 1255 return self.resolve_string( 1256 (_str('''<!ENTITY myentity "%s"> 1257 <!ELEMENT doc ANY>''') % url).encode('utf-8'), 1258 context)
1259 1260 parser.resolvers.add(MyResolver()) 1261 1262 xml = _str('<!DOCTYPE doc SYSTEM "%s"><doc>&myentity;</doc>') % test_url 1263 tree = parse(StringIO(xml), parser) 1264 root = tree.getroot() 1265 self.assertEqual(root.text, test_url) 1266
1267 - def test_resolve_filelike_dtd(self):
1268 parse = self.etree.parse 1269 parser = self.etree.XMLParser(dtd_validation=True) 1270 assertEqual = self.assertEqual 1271 test_url = _str("__nosuch.dtd") 1272 1273 class MyResolver(self.etree.Resolver): 1274 def resolve(self, url, id, context): 1275 assertEqual(url, test_url) 1276 return self.resolve_file( 1277 SillyFileLike( 1278 _str('''<!ENTITY myentity "%s"> 1279 <!ELEMENT doc ANY>''') % url), context)
1280 1281 parser.resolvers.add(MyResolver()) 1282 1283 xml = _str('<!DOCTYPE doc SYSTEM "%s"><doc>&myentity;</doc>') % test_url 1284 tree = parse(StringIO(xml), parser) 1285 root = tree.getroot() 1286 self.assertEqual(root.text, test_url) 1287
1288 - def test_resolve_filename_dtd(self):
1289 parse = self.etree.parse 1290 parser = self.etree.XMLParser(attribute_defaults=True) 1291 assertEqual = self.assertEqual 1292 test_url = _str("__nosuch.dtd") 1293 1294 class MyResolver(self.etree.Resolver): 1295 def resolve(self, url, id, context): 1296 assertEqual(url, test_url) 1297 return self.resolve_filename( 1298 fileInTestDir('test.dtd'), context)
1299 1300 parser.resolvers.add(MyResolver()) 1301 1302 xml = _str('<!DOCTYPE a SYSTEM "%s"><a><b/></a>') % test_url 1303 tree = parse(StringIO(xml), parser) 1304 root = tree.getroot() 1305 self.assertEqual( 1306 root.attrib, {'default': 'valueA'}) 1307 self.assertEqual( 1308 root[0].attrib, {'default': 'valueB'}) 1309
1310 - def test_resolve_filename_dtd_relative(self):
1311 parse = self.etree.parse 1312 parser = self.etree.XMLParser(attribute_defaults=True) 1313 assertEqual = self.assertEqual 1314 test_url = _str("__nosuch.dtd") 1315 1316 class MyResolver(self.etree.Resolver): 1317 def resolve(self, url, id, context): 1318 expected = fileUrlInTestDir(test_url) 1319 url = url.replace('file://', 'file:') # depends on libxml2 version 1320 expected = expected.replace('file://', 'file:') 1321 assertEqual(url, expected) 1322 return self.resolve_filename( 1323 fileUrlInTestDir('test.dtd'), context)
1324 1325 parser.resolvers.add(MyResolver()) 1326 1327 xml = _str('<!DOCTYPE a SYSTEM "%s"><a><b/></a>') % test_url 1328 tree = parse(StringIO(xml), parser, 1329 base_url=fileUrlInTestDir('__test.xml')) 1330 root = tree.getroot() 1331 self.assertEqual( 1332 root.attrib, {'default': 'valueA'}) 1333 self.assertEqual( 1334 root[0].attrib, {'default': 'valueB'}) 1335
1336 - def test_resolve_file_dtd(self):
1337 parse = self.etree.parse 1338 parser = self.etree.XMLParser(attribute_defaults=True) 1339 assertEqual = self.assertEqual 1340 test_url = _str("__nosuch.dtd") 1341 1342 class MyResolver(self.etree.Resolver): 1343 def resolve(self, url, id, context): 1344 assertEqual(url, test_url) 1345 return self.resolve_file( 1346 open(fileInTestDir('test.dtd'), 'rb'), context)
1347 1348 parser.resolvers.add(MyResolver()) 1349 1350 xml = _str('<!DOCTYPE a SYSTEM "%s"><a><b/></a>') % test_url 1351 tree = parse(StringIO(xml), parser) 1352 root = tree.getroot() 1353 self.assertEqual( 1354 root.attrib, {'default': 'valueA'}) 1355 self.assertEqual( 1356 root[0].attrib, {'default': 'valueB'}) 1357
1358 - def test_resolve_empty(self):
1359 parse = self.etree.parse 1360 parser = self.etree.XMLParser(load_dtd=True) 1361 assertEqual = self.assertEqual 1362 test_url = _str("__nosuch.dtd") 1363 1364 class check(object): 1365 resolved = False
1366 1367 class MyResolver(self.etree.Resolver): 1368 def resolve(self, url, id, context): 1369 assertEqual(url, test_url) 1370 check.resolved = True 1371 return self.resolve_empty(context) 1372 1373 parser.resolvers.add(MyResolver()) 1374 1375 xml = _str('<!DOCTYPE doc SYSTEM "%s"><doc>&myentity;</doc>') % test_url 1376 self.assertRaises(etree.XMLSyntaxError, parse, StringIO(xml), parser) 1377 self.assertTrue(check.resolved) 1378
1379 - def test_resolve_error(self):
1380 parse = self.etree.parse 1381 parser = self.etree.XMLParser(dtd_validation=True) 1382 1383 class _LocalException(Exception): 1384 pass
1385 1386 class MyResolver(self.etree.Resolver): 1387 def resolve(self, url, id, context): 1388 raise _LocalException 1389 1390 parser.resolvers.add(MyResolver()) 1391 1392 xml = '<!DOCTYPE doc SYSTEM "test"><doc>&myentity;</doc>' 1393 self.assertRaises(_LocalException, parse, BytesIO(xml), parser) 1394 1395 if etree.LIBXML_VERSION > (2,6,20):
1396 - def test_entity_parse(self):
1397 parse = self.etree.parse 1398 tostring = self.etree.tostring 1399 parser = self.etree.XMLParser(resolve_entities=False) 1400 Entity = self.etree.Entity 1401 1402 xml = _bytes('<!DOCTYPE doc SYSTEM "test"><doc>&myentity;</doc>') 1403 tree = parse(BytesIO(xml), parser) 1404 root = tree.getroot() 1405 self.assertEqual(root[0].tag, Entity) 1406 self.assertEqual(root[0].text, "&myentity;") 1407 self.assertEqual(root[0].tail, None) 1408 self.assertEqual(root[0].name, "myentity") 1409 1410 self.assertEqual(_bytes('<doc>&myentity;</doc>'), 1411 tostring(root))
1412
1413 - def test_entity_restructure(self):
1414 xml = _bytes('''<!DOCTYPE root [ <!ENTITY nbsp "&#160;"> ]> 1415 <root> 1416 <child1/> 1417 <child2/> 1418 <child3>&nbsp;</child3> 1419 </root>''') 1420 1421 parser = self.etree.XMLParser(resolve_entities=False) 1422 root = etree.fromstring(xml, parser) 1423 self.assertEqual([ el.tag for el in root ], 1424 ['child1', 'child2', 'child3']) 1425 1426 root[0] = root[-1] 1427 self.assertEqual([ el.tag for el in root ], 1428 ['child3', 'child2']) 1429 self.assertEqual(root[0][0].text, '&nbsp;') 1430 self.assertEqual(root[0][0].name, 'nbsp')
1431
1432 - def test_entity_append(self):
1433 Entity = self.etree.Entity 1434 Element = self.etree.Element 1435 tostring = self.etree.tostring 1436 1437 root = Element("root") 1438 root.append( Entity("test") ) 1439 1440 self.assertEqual(root[0].tag, Entity) 1441 self.assertEqual(root[0].text, "&test;") 1442 self.assertEqual(root[0].tail, None) 1443 self.assertEqual(root[0].name, "test") 1444 1445 self.assertEqual(_bytes('<root>&test;</root>'), 1446 tostring(root))
1447
1448 - def test_entity_values(self):
1449 Entity = self.etree.Entity 1450 self.assertEqual(Entity("test").text, '&test;') 1451 self.assertEqual(Entity("#17683").text, '&#17683;') 1452 self.assertEqual(Entity("#x1768").text, '&#x1768;') 1453 self.assertEqual(Entity("#x98AF").text, '&#x98AF;')
1454
1455 - def test_entity_error(self):
1456 Entity = self.etree.Entity 1457 self.assertRaises(ValueError, Entity, 'a b c') 1458 self.assertRaises(ValueError, Entity, 'a,b') 1459 self.assertRaises(ValueError, Entity, 'a\0b') 1460 self.assertRaises(ValueError, Entity, '#abc') 1461 self.assertRaises(ValueError, Entity, '#xxyz')
1462
1463 - def test_cdata(self):
1464 CDATA = self.etree.CDATA 1465 Element = self.etree.Element 1466 tostring = self.etree.tostring 1467 1468 root = Element("root") 1469 root.text = CDATA('test') 1470 1471 self.assertEqual('test', 1472 root.text) 1473 self.assertEqual(_bytes('<root><![CDATA[test]]></root>'), 1474 tostring(root))
1475
1476 - def test_cdata_tail(self):
1477 CDATA = self.etree.CDATA 1478 Element = self.etree.Element 1479 SubElement = self.etree.SubElement 1480 tostring = self.etree.tostring 1481 1482 root = Element("root") 1483 child = SubElement(root, 'child') 1484 child.tail = CDATA('test') 1485 1486 self.assertEqual('test', child.tail) 1487 self.assertEqual(_bytes('<root><child/><![CDATA[test]]></root>'), 1488 tostring(root)) 1489 1490 root = Element("root") 1491 root.tail = CDATA('test') 1492 1493 self.assertEqual('test', root.tail) 1494 self.assertEqual(_bytes('<root/><![CDATA[test]]>'), 1495 tostring(root))
1496
1497 - def test_cdata_type(self):
1498 CDATA = self.etree.CDATA 1499 Element = self.etree.Element 1500 root = Element("root") 1501 1502 root.text = CDATA("test") 1503 self.assertEqual('test', root.text) 1504 1505 root.text = CDATA(_str("test")) 1506 self.assertEqual('test', root.text) 1507 1508 self.assertRaises(TypeError, CDATA, 1)
1509
1510 - def test_cdata_errors(self):
1511 CDATA = self.etree.CDATA 1512 Element = self.etree.Element 1513 1514 root = Element("root") 1515 cdata = CDATA('test') 1516 1517 self.assertRaises(TypeError, 1518 root.set, 'attr', cdata) 1519 self.assertRaises(TypeError, 1520 operator.setitem, root.attrib, 'attr', cdata)
1521
1522 - def test_cdata_parser(self):
1523 tostring = self.etree.tostring 1524 parser = self.etree.XMLParser(strip_cdata=False) 1525 root = self.etree.XML(_bytes('<root><![CDATA[test]]></root>'), parser) 1526 1527 self.assertEqual('test', root.text) 1528 self.assertEqual(_bytes('<root><![CDATA[test]]></root>'), 1529 tostring(root))
1530
1531 - def test_cdata_xpath(self):
1532 tostring = self.etree.tostring 1533 parser = self.etree.XMLParser(strip_cdata=False) 1534 root = self.etree.XML(_bytes('<root><![CDATA[test]]></root>'), parser) 1535 self.assertEqual(_bytes('<root><![CDATA[test]]></root>'), 1536 tostring(root)) 1537 1538 self.assertEqual(['test'], root.xpath('//text()'))
1539 1540 # TypeError in etree, AssertionError in ElementTree;
1541 - def test_setitem_assert(self):
1542 Element = self.etree.Element 1543 SubElement = self.etree.SubElement 1544 1545 a = Element('a') 1546 b = SubElement(a, 'b') 1547 1548 self.assertRaises(TypeError, 1549 a.__setitem__, 0, 'foo')
1550
1551 - def test_append_error(self):
1552 Element = self.etree.Element 1553 root = Element('root') 1554 # raises AssertionError in ElementTree 1555 self.assertRaises(TypeError, root.append, None) 1556 self.assertRaises(TypeError, root.extend, [None]) 1557 self.assertRaises(TypeError, root.extend, [Element('one'), None]) 1558 self.assertEqual('one', root[0].tag)
1559
1560 - def test_append_recursive_error(self):
1561 Element = self.etree.Element 1562 SubElement = self.etree.SubElement 1563 root = Element('root') 1564 self.assertRaises(ValueError, root.append, root) 1565 child = SubElement(root, 'child') 1566 self.assertRaises(ValueError, child.append, root) 1567 child2 = SubElement(child, 'child2') 1568 self.assertRaises(ValueError, child2.append, root) 1569 self.assertRaises(ValueError, child2.append, child) 1570 self.assertEqual('child2', root[0][0].tag)
1571
1572 - def test_addnext(self):
1573 Element = self.etree.Element 1574 SubElement = self.etree.SubElement 1575 root = Element('root') 1576 SubElement(root, 'a') 1577 SubElement(root, 'b') 1578 1579 self.assertEqual(['a', 'b'], 1580 [c.tag for c in root]) 1581 root[1].addnext(root[0]) 1582 self.assertEqual(['b', 'a'], 1583 [c.tag for c in root])
1584
1585 - def test_addprevious(self):
1586 Element = self.etree.Element 1587 SubElement = self.etree.SubElement 1588 root = Element('root') 1589 SubElement(root, 'a') 1590 SubElement(root, 'b') 1591 1592 self.assertEqual(['a', 'b'], 1593 [c.tag for c in root]) 1594 root[0].addprevious(root[1]) 1595 self.assertEqual(['b', 'a'], 1596 [c.tag for c in root])
1597
1598 - def test_addnext_cycle(self):
1599 Element = self.etree.Element 1600 SubElement = self.etree.SubElement 1601 root = Element('root') 1602 a = SubElement(root, 'a') 1603 b = SubElement(a, 'b') 1604 # appending parent as sibling is forbidden 1605 self.assertRaises(ValueError, b.addnext, a) 1606 self.assertEqual(['a'], [c.tag for c in root]) 1607 self.assertEqual(['b'], [c.tag for c in a])
1608
1609 - def test_addprevious_cycle(self):
1610 Element = self.etree.Element 1611 SubElement = self.etree.SubElement 1612 root = Element('root') 1613 a = SubElement(root, 'a') 1614 b = SubElement(a, 'b') 1615 # appending parent as sibling is forbidden 1616 self.assertRaises(ValueError, b.addprevious, a) 1617 self.assertEqual(['a'], [c.tag for c in root]) 1618 self.assertEqual(['b'], [c.tag for c in a])
1619
1620 - def test_addnext_cycle_long(self):
1621 Element = self.etree.Element 1622 SubElement = self.etree.SubElement 1623 root = Element('root') 1624 a = SubElement(root, 'a') 1625 b = SubElement(a, 'b') 1626 c = SubElement(b, 'c') 1627 # appending parent as sibling is forbidden 1628 self.assertRaises(ValueError, c.addnext, a)
1629
1630 - def test_addprevious_cycle_long(self):
1631 Element = self.etree.Element 1632 SubElement = self.etree.SubElement 1633 root = Element('root') 1634 a = SubElement(root, 'a') 1635 b = SubElement(a, 'b') 1636 c = SubElement(b, 'c') 1637 # appending parent as sibling is forbidden 1638 self.assertRaises(ValueError, c.addprevious, a)
1639
1640 - def test_addprevious_noops(self):
1641 Element = self.etree.Element 1642 SubElement = self.etree.SubElement 1643 root = Element('root') 1644 a = SubElement(root, 'a') 1645 b = SubElement(root, 'b') 1646 a.addprevious(a) 1647 self.assertEqual('a', root[0].tag) 1648 self.assertEqual('b', root[1].tag) 1649 b.addprevious(b) 1650 self.assertEqual('a', root[0].tag) 1651 self.assertEqual('b', root[1].tag) 1652 b.addprevious(a) 1653 self.assertEqual('a', root[0].tag) 1654 self.assertEqual('b', root[1].tag)
1655
1656 - def test_addnext_noops(self):
1657 Element = self.etree.Element 1658 SubElement = self.etree.SubElement 1659 root = Element('root') 1660 a = SubElement(root, 'a') 1661 b = SubElement(root, 'b') 1662 a.addnext(a) 1663 self.assertEqual('a', root[0].tag) 1664 self.assertEqual('b', root[1].tag) 1665 b.addnext(b) 1666 self.assertEqual('a', root[0].tag) 1667 self.assertEqual('b', root[1].tag) 1668 a.addnext(b) 1669 self.assertEqual('a', root[0].tag) 1670 self.assertEqual('b', root[1].tag)
1671
1672 - def test_addnext_root(self):
1673 Element = self.etree.Element 1674 a = Element('a') 1675 b = Element('b') 1676 self.assertRaises(TypeError, a.addnext, b)
1677
1678 - def test_addprevious_pi(self):
1679 Element = self.etree.Element 1680 SubElement = self.etree.SubElement 1681 PI = self.etree.PI 1682 root = Element('root') 1683 SubElement(root, 'a') 1684 pi = PI('TARGET', 'TEXT') 1685 pi.tail = "TAIL" 1686 1687 self.assertEqual(_bytes('<root><a></a></root>'), 1688 self._writeElement(root)) 1689 root[0].addprevious(pi) 1690 self.assertEqual(_bytes('<root><?TARGET TEXT?>TAIL<a></a></root>'), 1691 self._writeElement(root))
1692
1693 - def test_addprevious_root_pi(self):
1694 Element = self.etree.Element 1695 PI = self.etree.PI 1696 root = Element('root') 1697 pi = PI('TARGET', 'TEXT') 1698 pi.tail = "TAIL" 1699 1700 self.assertEqual(_bytes('<root></root>'), 1701 self._writeElement(root)) 1702 root.addprevious(pi) 1703 self.assertEqual(_bytes('<?TARGET TEXT?>\n<root></root>'), 1704 self._writeElement(root))
1705
1706 - def test_addnext_pi(self):
1707 Element = self.etree.Element 1708 SubElement = self.etree.SubElement 1709 PI = self.etree.PI 1710 root = Element('root') 1711 SubElement(root, 'a') 1712 pi = PI('TARGET', 'TEXT') 1713 pi.tail = "TAIL" 1714 1715 self.assertEqual(_bytes('<root><a></a></root>'), 1716 self._writeElement(root)) 1717 root[0].addnext(pi) 1718 self.assertEqual(_bytes('<root><a></a><?TARGET TEXT?>TAIL</root>'), 1719 self._writeElement(root))
1720
1721 - def test_addnext_root_pi(self):
1722 Element = self.etree.Element 1723 PI = self.etree.PI 1724 root = Element('root') 1725 pi = PI('TARGET', 'TEXT') 1726 pi.tail = "TAIL" 1727 1728 self.assertEqual(_bytes('<root></root>'), 1729 self._writeElement(root)) 1730 root.addnext(pi) 1731 self.assertEqual(_bytes('<root></root>\n<?TARGET TEXT?>'), 1732 self._writeElement(root))
1733
1734 - def test_addnext_comment(self):
1735 Element = self.etree.Element 1736 SubElement = self.etree.SubElement 1737 Comment = self.etree.Comment 1738 root = Element('root') 1739 SubElement(root, 'a') 1740 comment = Comment('TEXT ') 1741 comment.tail = "TAIL" 1742 1743 self.assertEqual(_bytes('<root><a></a></root>'), 1744 self._writeElement(root)) 1745 root[0].addnext(comment) 1746 self.assertEqual(_bytes('<root><a></a><!--TEXT -->TAIL</root>'), 1747 self._writeElement(root))
1748
1749 - def test_addnext_root_comment(self):
1750 Element = self.etree.Element 1751 Comment = self.etree.Comment 1752 root = Element('root') 1753 comment = Comment('TEXT ') 1754 comment.tail = "TAIL" 1755 1756 self.assertEqual(_bytes('<root></root>'), 1757 self._writeElement(root)) 1758 root.addnext(comment) 1759 self.assertEqual(_bytes('<root></root>\n<!--TEXT -->'), 1760 self._writeElement(root))
1761
1762 - def test_addprevious_comment(self):
1763 Element = self.etree.Element 1764 SubElement = self.etree.SubElement 1765 Comment = self.etree.Comment 1766 root = Element('root') 1767 SubElement(root, 'a') 1768 comment = Comment('TEXT ') 1769 comment.tail = "TAIL" 1770 1771 self.assertEqual(_bytes('<root><a></a></root>'), 1772 self._writeElement(root)) 1773 root[0].addprevious(comment) 1774 self.assertEqual(_bytes('<root><!--TEXT -->TAIL<a></a></root>'), 1775 self._writeElement(root))
1776
1777 - def test_addprevious_root_comment(self):
1778 Element = self.etree.Element 1779 Comment = self.etree.Comment 1780 root = Element('root') 1781 comment = Comment('TEXT ') 1782 comment.tail = "TAIL" 1783 1784 self.assertEqual(_bytes('<root></root>'), 1785 self._writeElement(root)) 1786 root.addprevious(comment) 1787 self.assertEqual(_bytes('<!--TEXT -->\n<root></root>'), 1788 self._writeElement(root))
1789 1790 # ET's Elements have items() and key(), but not values()
1791 - def test_attribute_values(self):
1792 XML = self.etree.XML 1793 1794 root = XML(_bytes('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')) 1795 values = root.values() 1796 values.sort() 1797 self.assertEqual(['Alpha', 'Beta', 'Gamma'], values)
1798 1799 # gives error in ElementTree
1800 - def test_comment_empty(self):
1801 Element = self.etree.Element 1802 Comment = self.etree.Comment 1803 1804 a = Element('a') 1805 a.append(Comment()) 1806 self.assertEqual( 1807 _bytes('<a><!----></a>'), 1808 self._writeElement(a))
1809 1810 # ElementTree ignores comments
1811 - def test_comment_parse_empty(self):
1812 ElementTree = self.etree.ElementTree 1813 tostring = self.etree.tostring 1814 1815 xml = _bytes('<a><b/><!----><c/></a>') 1816 f = BytesIO(xml) 1817 doc = ElementTree(file=f) 1818 a = doc.getroot() 1819 self.assertEqual( 1820 '', 1821 a[1].text) 1822 self.assertEqual( 1823 xml, 1824 tostring(a))
1825 1826 # ElementTree ignores comments
1827 - def test_comment_no_proxy_yet(self):
1828 ElementTree = self.etree.ElementTree 1829 1830 f = BytesIO('<a><b></b><!-- hoi --><c></c></a>') 1831 doc = ElementTree(file=f) 1832 a = doc.getroot() 1833 self.assertEqual( 1834 ' hoi ', 1835 a[1].text)
1836 1837 # does not raise an exception in ElementTree
1838 - def test_comment_immutable(self):
1839 Element = self.etree.Element 1840 Comment = self.etree.Comment 1841 1842 c = Comment() 1843 el = Element('myel') 1844 1845 self.assertRaises(TypeError, c.append, el) 1846 self.assertRaises(TypeError, c.