Package lxml :: Package tests :: Module test_elementtree

[hide private]
[frames] | no frames]

# Source Code for Module lxml.tests.test_elementtree

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