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