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