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

# Source Code for Module lxml.tests.test_elementtree

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