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_delitem_tail(self):
    1372          ElementTree = self.etree.ElementTree
    1373          f = BytesIO('<a><b></b>B2<c></c>C2</a>')
    1374          doc = ElementTree(file=f)
    1375          a = doc.getroot()
    1376          del a[0]
    1377          self.assertXML(
    1378              _bytes('<a><c></c>C2</a>'),
    1379              a)
    1380
    1381 -    def test_clear(self):
    1382          Element = self.etree.Element
    1383
    1384          a = Element('a')
    1385          a.text = 'foo'
    1386          a.tail = 'bar'
    1387          a.set('hoi', 'dag')
    1388          a.clear()
    1389          self.assertEquals(None, a.text)
    1390          self.assertEquals(None, a.tail)
    1391          self.assertEquals(None, a.get('hoi'))
    1392          self.assertEquals('a', a.tag)
    1393
    1394 -    def test_clear_sub(self):
    1395          Element = self.etree.Element
    1396          SubElement = self.etree.SubElement
    1397
    1398          a = Element('a')
    1399          a.text = 'foo'
    1400          a.tail = 'bar'
    1401          a.set('hoi', 'dag')
    1402          b = SubElement(a, 'b')
    1403          c = SubElement(b, 'c')
    1404          a.clear()
    1405          self.assertEquals(None, a.text)
    1406          self.assertEquals(None, a.tail)
    1407          self.assertEquals(None, a.get('hoi'))
    1408          self.assertEquals('a', a.tag)
    1409          self.assertEquals(0, len(a))
    1410          self.assertXML(_bytes('<a></a>'),
    1411                         a)
    1412          self.assertXML(_bytes('<b><c></c></b>'),
    1413                         b)
    1414
    1415 -    def test_clear_tail(self):
    1416          ElementTree = self.etree.ElementTree
    1417          f = BytesIO('<a><b></b>B2<c></c>C2</a>')
    1418          doc = ElementTree(file=f)
    1419          a = doc.getroot()
    1420          a.clear()
    1421          self.assertXML(
    1422              _bytes('<a></a>'),
    1423              a)
    1424
    1425 -    def test_insert(self):
    1426          Element = self.etree.Element
    1427          SubElement = self.etree.SubElement
    1428
    1429          a = Element('a')
    1430          b = SubElement(a, 'b')
    1431          c = SubElement(a, 'c')
    1432          d = Element('d')
    1433          a.insert(0, d)
    1434
    1435          self.assertEquals(
    1436              d,
    1437              a[0])
    1438
    1439          self.assertXML(
    1440              _bytes('<a><d></d><b></b><c></c></a>'),
    1441              a)
    1442
    1443          e = Element('e')
    1444          a.insert(2, e)
    1445          self.assertEquals(
    1446              e,
    1447              a[2])
    1448          self.assertXML(
    1449              _bytes('<a><d></d><b></b><e></e><c></c></a>'),
    1450              a)
    1451
    1452 -    def test_insert_beyond_index(self):
    1453          Element = self.etree.Element
    1454          SubElement = self.etree.SubElement
    1455
    1456          a = Element('a')
    1457          b = SubElement(a, 'b')
    1458          c = Element('c')
    1459
    1460          a.insert(2, c)
    1461          self.assertEquals(
    1462              c,
    1463              a[1])
    1464          self.assertXML(
    1465              _bytes('<a><b></b><c></c></a>'),
    1466              a)
    1467
    1468 -    def test_insert_negative(self):
    1469          Element = self.etree.Element
    1470          SubElement = self.etree.SubElement
    1471
    1472          a = Element('a')
    1473          b = SubElement(a, 'b')
    1474          c = SubElement(a, 'c')
    1475
    1476          d = Element('d')
    1477          a.insert(-1, d)
    1478          self.assertEquals(
    1479              d,
    1480              a[-2])
    1481          self.assertXML(
    1482              _bytes('<a><b></b><d></d><c></c></a>'),
    1483              a)
    1484
    1485 -    def test_insert_tail(self):
    1486          Element = self.etree.Element
    1487          SubElement = self.etree.SubElement
    1488
    1489          a = Element('a')
    1490          b = SubElement(a, 'b')
    1491
    1492          c = Element('c')
    1493          c.tail = 'C2'
    1494
    1495          a.insert(0, c)
    1496          self.assertXML(
    1497              _bytes('<a><c></c>C2<b></b></a>'),
    1498              a)
    1499
    1500 -    def test_remove(self):
    1501          Element = self.etree.Element
    1502          SubElement = self.etree.SubElement
    1503
    1504          a = Element('a')
    1505          b = SubElement(a, 'b')
    1506          c = SubElement(a, 'c')
    1507
    1508          a.remove(b)
    1509          self.assertEquals(
    1510              c,
    1511              a[0])
    1512          self.assertXML(
    1513              _bytes('<a><c></c></a>'),
    1514              a)
    1515
    1516 -    def test_remove_ns(self):
    1517          Element = self.etree.Element
    1518          SubElement = self.etree.SubElement
    1519
    1520          a = Element('{http://test}a')
    1521          b = SubElement(a, '{http://test}b')
    1522          c = SubElement(a, '{http://test}c')
    1523
    1524          a.remove(b)
    1525          self.assertXML(
    1526              _bytes('<ns0:a xmlns:ns0="http://test"><ns0:c></ns0:c></ns0:a>'),
    1527              a)
    1528          self.assertXML(
    1529              _bytes('<ns0:b xmlns:ns0="http://test"></ns0:b>'),
    1530              b)
    1531
    1532 -    def test_remove_nonexisting(self):
    1533          Element = self.etree.Element
    1534          SubElement = self.etree.SubElement
    1535
    1536          a = Element('a')
    1537          b = SubElement(a, 'b')
    1538          c = SubElement(a, 'c')
    1539          d = Element('d')
    1540          self.assertRaises(
    1541              ValueError, a.remove, d)
    1542
    1543 -    def test_remove_tail(self):
    1544          Element = self.etree.Element
    1545          SubElement = self.etree.SubElement
    1546
    1547          a = Element('a')
    1548          b = SubElement(a, 'b')
    1549          b.tail = 'b2'
    1550          a.remove(b)
    1551          self.assertXML(
    1552              _bytes('<a></a>'),
    1553              a)
    1554          self.assertEquals('b2', b.tail)
    1555
    1556 -    def _test_getchildren(self):
    1557          Element = self.etree.Element
    1558          SubElement = self.etree.SubElement
    1559
    1560          a = Element('a')
    1561          b = SubElement(a, 'b')
    1562          c = SubElement(a, 'c')
    1563          d = SubElement(b, 'd')
    1564          e = SubElement(c, 'e')
    1565          self.assertXML(
    1566              _bytes('<a><b><d></d></b><c><e></e></c></a>'),
    1567              a)
    1568          self.assertEquals(
    1569              [b, c],
    1570              a.getchildren())
    1571          self.assertEquals(
    1572              [d],
    1573              b.getchildren())
    1574          self.assertEquals(
    1575              [],
    1576              d.getchildren())
    1577
    1578 -    def test_makeelement(self):
    1579          Element = self.etree.Element
    1580
    1581          a = Element('a')
    1582          b = a.makeelement('c', {'hoi':'dag'})
    1583          self.assertXML(
    1584              _bytes('<c hoi="dag"></c>'),
    1585              b)
    1586
    1587 -    def test_iter(self):
    1588          Element = self.etree.Element
    1589          SubElement = self.etree.SubElement
    1590
    1591          a = Element('a')
    1592          b = SubElement(a, 'b')
    1593          c = SubElement(a, 'c')
    1594          d = SubElement(b, 'd')
    1595          e = SubElement(c, 'e')
    1596
    1597          self.assertEquals(
    1598              [a, b, d, c, e],
    1599              list(a.iter()))
    1600          self.assertEquals(
    1601              [d],
    1602              list(d.iter()))
    1603
    1604 -    def test_getiterator(self):
    1605          Element = self.etree.Element
    1606          SubElement = self.etree.SubElement
    1607
    1608          a = Element('a')
    1609          b = SubElement(a, 'b')
    1610          c = SubElement(a, 'c')
    1611          d = SubElement(b, 'd')
    1612          e = SubElement(c, 'e')
    1613
    1614          self.assertEquals(
    1615              [a, b, d, c, e],
    1616              list(a.getiterator()))
    1617          self.assertEquals(
    1618              [d],
    1619              list(d.getiterator()))
    1620
    1621 -    def test_getiterator_empty(self):
    1622          Element = self.etree.Element
    1623          SubElement = self.etree.SubElement
    1624
    1625          a = Element('a')
    1626          b = SubElement(a, 'b')
    1627          c = SubElement(a, 'c')
    1628          d = SubElement(b, 'd')
    1629          e = SubElement(c, 'e')
    1630
    1631          self.assertEquals(
    1632              [],
    1633              list(a.getiterator('none')))
    1634          self.assertEquals(
    1635              [],
    1636              list(e.getiterator('none')))
    1637          self.assertEquals(
    1638              [e],
    1639              list(e.getiterator()))
    1640
    1641 -    def test_getiterator_filter(self):
    1642          Element = self.etree.Element
    1643          SubElement = self.etree.SubElement
    1644
    1645          a = Element('a')
    1646          b = SubElement(a, 'b')
    1647          c = SubElement(a, 'c')
    1648          d = SubElement(b, 'd')
    1649          e = SubElement(c, 'e')
    1650
    1651          self.assertEquals(
    1652              [a],
    1653              list(a.getiterator('a')))
    1654          a2 = SubElement(e, 'a')
    1655          self.assertEquals(
    1656              [a, a2],
    1657              list(a.getiterator('a')))
    1658          self.assertEquals(
    1659              [a2],
    1660              list(c.getiterator('a')))
    1661
    1662 -    def test_getiterator_filter_all(self):
    1663          Element = self.etree.Element
    1664          SubElement = self.etree.SubElement
    1665
    1666          a = Element('a')
    1667          b = SubElement(a, 'b')
    1668          c = SubElement(a, 'c')
    1669          d = SubElement(b, 'd')
    1670          e = SubElement(c, 'e')
    1671
    1672          self.assertEquals(
    1673              [a, b, d, c, e],
    1674              list(a.getiterator('*')))
    1675
    1676 -    def test_getiterator_filter_comment(self):
    1677          Element = self.etree.Element
    1678          Comment = self.etree.Comment
    1679          SubElement = self.etree.SubElement
    1680
    1681          a = Element('a')
    1682          b = SubElement(a, 'b')
    1683          comment_b = Comment("TEST-b")
    1684          b.append(comment_b)
    1685
    1686          self.assertEquals(
    1687              [comment_b],
    1688              list(a.getiterator(Comment)))
    1689
    1690          comment_a = Comment("TEST-a")
    1691          a.append(comment_a)
    1692
    1693          self.assertEquals(
    1694              [comment_b, comment_a],
    1695              list(a.getiterator(Comment)))
    1696
    1697          self.assertEquals(
    1698              [comment_b],
    1699              list(b.getiterator(Comment)))
    1700
    1701 -    def test_getiterator_filter_pi(self):
    1702          Element = self.etree.Element
    1703          PI = self.etree.ProcessingInstruction
    1704          SubElement = self.etree.SubElement
    1705
    1706          a = Element('a')
    1707          b = SubElement(a, 'b')
    1708          pi_b = PI("TEST-b")
    1709          b.append(pi_b)
    1710
    1711          self.assertEquals(
    1712              [pi_b],
    1713              list(a.getiterator(PI)))
    1714
    1715          pi_a = PI("TEST-a")
    1716          a.append(pi_a)
    1717
    1718          self.assertEquals(
    1719              [pi_b, pi_a],
    1720              list(a.getiterator(PI)))
    1721
    1722          self.assertEquals(
    1723              [pi_b],
    1724              list(b.getiterator(PI)))
    1725
    1726 -    def test_getiterator_with_text(self):
    1727          Element = self.etree.Element
    1728          SubElement = self.etree.SubElement
    1729
    1730          a = Element('a')
    1731          a.text = 'a'
    1732          b = SubElement(a, 'b')
    1733          b.text = 'b'
    1734          b.tail = 'b1'
    1735          c = SubElement(a, 'c')
    1736          c.text = 'c'
    1737          c.tail = 'c1'
    1738          d = SubElement(b, 'd')
    1739          c.text = 'd'
    1740          c.tail = 'd1'
    1741          e = SubElement(c, 'e')
    1742          e.text = 'e'
    1743          e.tail = 'e1'
    1744
    1745          self.assertEquals(
    1746              [a, b, d, c, e],
    1747              list(a.getiterator()))
    1748          #self.assertEquals(
    1749          #    [d],
    1750          #    list(d.getiterator()))
    1751
    1752 -    def test_getiterator_filter_with_text(self):
    1753          Element = self.etree.Element
    1754          SubElement = self.etree.SubElement
    1755
    1756          a = Element('a')
    1757          a.text = 'a'
    1758          b = SubElement(a, 'b')
    1759          b.text = 'b'
    1760          b.tail = 'b1'
    1761          c = SubElement(a, 'c')
    1762          c.text = 'c'
    1763          c.tail = 'c1'
    1764          d = SubElement(b, 'd')
    1765          c.text = 'd'
    1766          c.tail = 'd1'
    1767          e = SubElement(c, 'e')
    1768          e.text = 'e'
    1769          e.tail = 'e1'
    1770
    1771          self.assertEquals(
    1772              [a],
    1773              list(a.getiterator('a')))
    1774          a2 = SubElement(e, 'a')
    1775          self.assertEquals(
    1776              [a, a2],
    1777              list(a.getiterator('a')))
    1778          self.assertEquals(
    1779              [a2],
    1780              list(e.getiterator('a')))
    1781
    1782 -    def test_attribute_manipulation(self):
    1783          Element = self.etree.Element
    1784
    1785          a = Element('a')
    1786          a.attrib['foo'] = 'Foo'
    1787          a.attrib['bar'] = 'Bar'
    1788          self.assertEquals('Foo', a.attrib['foo'])
    1789          del a.attrib['foo']
    1790          self.assertRaises(KeyError, operator.getitem, a.attrib, 'foo')
    1791
    1792 -    def test_getslice(self):
    1793          Element = self.etree.Element
    1794          SubElement = self.etree.SubElement
    1795
    1796          a = Element('a')
    1797          b = SubElement(a, 'b')
    1798          c = SubElement(a, 'c')
    1799          d = SubElement(a, 'd')
    1800
    1801          self.assertEquals(
    1802              [b, c],
    1803              a[0:2])
    1804          self.assertEquals(
    1805              [b, c, d],
    1806              a[:])
    1807          self.assertEquals(
    1808              [b, c, d],
    1809              a[:10])
    1810          self.assertEquals(
    1811              [b],
    1812              a[0:1])
    1813          self.assertEquals(
    1814              [],
    1815              a[10:12])
    1816
    1817 -    def test_getslice_negative(self):
    1818          Element = self.etree.Element
    1819          SubElement = self.etree.SubElement
    1820
    1821          a = Element('a')
    1822          b = SubElement(a, 'b')
    1823          c = SubElement(a, 'c')
    1824          d = SubElement(a, 'd')
    1825
    1826          self.assertEquals(
    1827              [d],
    1828              a[-1:])
    1829          self.assertEquals(
    1830              [c, d],
    1831              a[-2:])
    1832          self.assertEquals(
    1833              [c],
    1834              a[-2:-1])
    1835          self.assertEquals(
    1836              [b, c],
    1837              a[-3:-1])
    1838          self.assertEquals(
    1839              [b, c],
    1840              a[-3:2])
    1841
    1842 -    def test_getslice_step(self):
    1843          Element = self.etree.Element
    1844          SubElement = self.etree.SubElement
    1845
    1846          a = Element('a')
    1847          b = SubElement(a, 'b')
    1848          c = SubElement(a, 'c')
    1849          d = SubElement(a, 'd')
    1850          e = SubElement(a, 'e')
    1851
    1852          self.assertEquals(
    1853              [e,d,c,b],
    1854              a[::-1])
    1855          self.assertEquals(
    1856              [b,d],
    1857              a[::2])
    1858          self.assertEquals(
    1859              [e,c],
    1860              a[::-2])
    1861          self.assertEquals(
    1862              [d,c],
    1863              a[-2:0:-1])
    1864          self.assertEquals(
    1865              [e],
    1866              a[:1:-2])
    1867
    1868 -    def test_getslice_text(self):
    1869          ElementTree = self.etree.ElementTree
    1870
    1871          f = BytesIO('<a><b>B</b>B1<c>C</c>C1</a>')
    1872          doc = ElementTree(file=f)
    1873          a = doc.getroot()
    1874          b = a[0]
    1875          c = a[1]
    1876          self.assertEquals(
    1877              [b, c],
    1878              a[:])
    1879          self.assertEquals(
    1880              [b],
    1881              a[0:1])
    1882          self.assertEquals(
    1883              [c],
    1884              a[1:])
    1885
    1886 -    def test_comment_getitem_getslice(self):
    1887          Element = self.etree.Element
    1888          Comment = self.etree.Comment
    1889          SubElement = self.etree.SubElement
    1890
    1891          a = Element('a')
    1892          b = SubElement(a, 'b')
    1893          foo = Comment('foo')
    1894          a.append(foo)
    1895          c = SubElement(a, 'c')
    1896          self.assertEquals(
    1897              [b, foo, c],
    1898              a[:])
    1899          self.assertEquals(
    1900              foo,
    1901              a[1])
    1902          a[1] = new = Element('new')
    1903          self.assertEquals(
    1904              new,
    1905              a[1])
    1906          self.assertXML(
    1907              _bytes('<a><b></b><new></new><c></c></a>'),
    1908              a)
    1909
    1910 -    def test_delslice(self):
    1911          Element = self.etree.Element
    1912          SubElement = self.etree.SubElement
    1913
    1914          a = Element('a')
    1915          b = SubElement(a, 'b')
    1916          c = SubElement(a, 'c')
    1917          d = SubElement(a, 'd')
    1918          e = SubElement(a, 'e')
    1919
    1920          del a[1:3]
    1921          self.assertEquals(
    1922              [b, e],
    1923              list(a))
    1924
    1925 -    def test_delslice_negative1(self):
    1926          Element = self.etree.Element
    1927          SubElement = self.etree.SubElement
    1928
    1929          a = Element('a')
    1930          b = SubElement(a, 'b')
    1931          c = SubElement(a, 'c')
    1932          d = SubElement(a, 'd')
    1933          e = SubElement(a, 'e')
    1934
    1935          del a[1:-1]
    1936          self.assertEquals(
    1937              [b, e],
    1938              list(a))
    1939
    1940 -    def test_delslice_negative2(self):
    1941          Element = self.etree.Element
    1942          SubElement = self.etree.SubElement
    1943
    1944          a = Element('a')
    1945          b = SubElement(a, 'b')
    1946          c = SubElement(a, 'c')
    1947          d = SubElement(a, 'd')
    1948          e = SubElement(a, 'e')
    1949
    1950          del a[-3:-1]
    1951          self.assertEquals(
    1952              [b, e],
    1953              list(a))
    1954
    1955 -    def test_delslice_step(self):
    1956          Element = self.etree.Element
    1957          SubElement = self.etree.SubElement
    1958
    1959          a = Element('a')
    1960          b = SubElement(a, 'b')
    1961          c = SubElement(a, 'c')
    1962          d = SubElement(a, 'd')
    1963          e = SubElement(a, 'e')
    1964
    1965          del a[1::2]
    1966          self.assertEquals(
    1967              [b, d],
    1968              list(a))
    1969
    1970 -    def test_delslice_step_negative(self):
    1971          Element = self.etree.Element
    1972          SubElement = self.etree.SubElement
    1973
    1974          a = Element('a')
    1975          b = SubElement(a, 'b')
    1976          c = SubElement(a, 'c')
    1977          d = SubElement(a, 'd')
    1978          e = SubElement(a, 'e')
    1979
    1980          del a[::-1]
    1981          self.assertEquals(
    1982              [],
    1983              list(a))
    1984
    1985 -    def test_delslice_step_negative2(self):
    1986          Element = self.etree.Element
    1987          SubElement = self.etree.SubElement
    1988
    1989          a = Element('a')
    1990          b = SubElement(a, 'b')
    1991          c = SubElement(a, 'c')
    1992          d = SubElement(a, 'd')
    1993          e = SubElement(a, 'e')
    1994
    1995          del a[::-2]
    1996          self.assertEquals(
    1997              [b, d],
    1998              list(a))
    1999
    2000 -    def test_delslice_child_tail(self):
    2001          ElementTree = self.etree.ElementTree
    2002          f = BytesIO('<a><b></b>B2<c></c>C2<d></d>D2<e></e>E2</a>')
    2003          doc = ElementTree(file=f)
    2004          a = doc.getroot()
    2005          del a[1:3]
    2006          self.assertXML(
    2007              _bytes('<a><b></b>B2<e></e>E2</a>'),
    2008              a)
    2009
    2010 -    def test_delslice_tail(self):
    2011          XML = self.etree.XML
    2012          a = XML(_bytes('<a><b></b>B2<c></c>C2</a>'))
    2013          b, c = a
    2014
    2015          del a[:]
    2016
    2017          self.assertEquals("B2", b.tail)
    2018          self.assertEquals("C2", c.tail)
    2019
    2020 -    def test_delslice_memory(self):
    2021          # this could trigger a crash
    2022          Element = self.etree.Element
    2023          SubElement = self.etree.SubElement
    2024          a = Element('a')
    2025          b = SubElement(a, 'b')
    2026          c = SubElement(b, 'c')
    2027          del b # no more reference to b
    2028          del a[:]
    2029          self.assertEquals('c', c.tag)
    2030
    2031 -    def test_setslice(self):
    2032          Element = self.etree.Element
    2033          SubElement = self.etree.SubElement
    2034
    2035          a = Element('a')
    2036          b = SubElement(a, 'b')
    2037          c = SubElement(a, 'c')
    2038          d = SubElement(a, 'd')
    2039
    2040          e = Element('e')
    2041          f = Element('f')
    2042          g = Element('g')
    2043
    2044          s = [e, f, g]
    2045          a[1:2] = s
    2046          self.assertEquals(
    2047              [b, e, f, g, d],
    2048              list(a))
    2049
    2050 -    def test_setslice_all(self):
    2051          Element = self.etree.Element
    2052          SubElement = self.etree.SubElement
    2053
    2054          a = Element('a')
    2055          b = SubElement(a, 'b')
    2056          c = SubElement(a, 'c')
    2057
    2058          e = Element('e')
    2059          f = Element('f')
    2060          g = Element('g')
    2061
    2062          s = [e, f, g]
    2063          a[:] = s
    2064          self.assertEquals(
    2065              [e, f, g],
    2066              list(a))
    2067
    2068 -    def test_setslice_all_empty(self):
    2069          Element = self.etree.Element
    2070          SubElement = self.etree.SubElement
    2071
    2072          a = Element('a')
    2073
    2074          e = Element('e')
    2075          f = Element('f')
    2076          g = Element('g')
    2077
    2078          s = [e, f, g]
    2079          a[:] = s
    2080          self.assertEquals(
    2081              [e, f, g],
    2082              list(a))
    2083
    2084 -    def test_setslice_all_replace(self):
    2085          Element = self.etree.Element
    2086          SubElement = self.etree.SubElement
    2087
    2088          a = Element('a')
    2089          b = SubElement(a, 'b')
    2090          c = SubElement(a, 'c')
    2091          d = SubElement(a, 'd')
    2092
    2093          s = [b, c, d]
    2094          a[:] = s
    2095          self.assertEquals(
    2096              [b, c, d],
    2097              list(a))
    2098
    2099 -    def test_setslice_all_replace_reversed(self):
    2100          Element = self.etree.Element
    2101          SubElement = self.etree.SubElement
    2102
    2103          a = Element('a')
    2104          b = SubElement(a, 'b')
    2105          c = SubElement(a, 'c')
    2106          d = SubElement(a, 'd')
    2107
    2108          s = [d, c, b]
    2109          a[:] = s
    2110          self.assertEquals(
    2111              [d, c, b],
    2112              list(a))
    2113
    2114 -    def test_setslice_all_replace_reversed_ns1(self):
    2115          Element = self.etree.Element
    2116          SubElement = self.etree.SubElement
    2117
    2118          a = Element('{ns}a')
    2119          b = SubElement(a, '{ns}b', {'{ns1}a1': 'test'})
    2120          c = SubElement(a, '{ns}c', {'{ns2}a2': 'test'})
    2121          d = SubElement(a, '{ns}d', {'{ns3}a3': 'test'})
    2122
    2123          s = [d, c, b]
    2124          a[:] = s
    2125          self.assertEquals(
    2126              [d, c, b],
    2127              list(a))
    2128          self.assertEquals(
    2129              ['{ns}d', '{ns}c', '{ns}b'],
    2130              [ child.tag for child in a ])
    2131
    2132          self.assertEquals(
    2133              [['{ns3}a3'], ['{ns2}a2'], ['{ns1}a1']],
    2134              [ child.attrib.keys() for child in a ])
    2135
    2136 -    def test_setslice_all_replace_reversed_ns2(self):
    2137          Element = self.etree.Element
    2138          SubElement = self.etree.SubElement
    2139
    2140          a = Element('{ns}a')
    2141          b = SubElement(a, '{ns1}b', {'{ns}a1': 'test'})
    2142          c = SubElement(a, '{ns2}c', {'{ns}a2': 'test'})
    2143          d = SubElement(a, '{ns3}d', {'{ns}a3': 'test'})
    2144
    2145          s = [d, c, b]
    2146          a[:] = s
    2147          self.assertEquals(
    2148              [d, c, b],
    2149              list(a))
    2150          self.assertEquals(
    2151              ['{ns3}d', '{ns2}c', '{ns1}b'],
    2152              [ child.tag for child in a ])
    2153
    2154          self.assertEquals(
    2155              [['{ns}a3'], ['{ns}a2'], ['{ns}a1']],
    2156              [ child.attrib.keys() for child in a ])
    2157
    2158 -    def test_setslice_end(self):
    2159          Element = self.etree.Element
    2160          SubElement = self.etree.SubElement
    2161
    2162          a = Element('a')
    2163          b = SubElement(a, 'b')
    2164          c = SubElement(a, 'c')
    2165
    2166          e = Element('e')
    2167          f = Element('f')
    2168          g = Element('g')
    2169          h = Element('h')
    2170
    2171          s = [e, f]
    2172          a[99:] = s
    2173          self.assertEquals(
    2174              [a, b, e, f],
    2175              list(a))
    2176
    2177          s = [g, h]
    2178          a[:0] = s
    2179          self.assertEquals(
    2180              [g, h, a, b, e, f],
    2181              list(a))
    2182
    2183 -    def test_setslice_single(self):
    2184          Element = self.etree.Element
    2185          SubElement = self.etree.SubElement
    2186
    2187          a = Element('a')
    2188          b = SubElement(a, 'b')
    2189          c = SubElement(a, 'c')
    2190
    2191          e = Element('e')
    2192          f = Element('f')
    2193
    2194          s = [e]
    2195          a[0:1] = s
    2196          self.assertEquals(
    2197              [e, c],
    2198              list(a))
    2199
    2200          s = [f]
    2201          a[1:2] = s
    2202          self.assertEquals(
    2203              [e, f],
    2204              list(a))
    2205
    2206 -    def test_setslice_tail(self):
    2207          ElementTree = self.etree.ElementTree
    2208          Element = self.etree.Element
    2209          f = BytesIO('<a><b></b>B2<c></c>C2<d></d>D2<e></e>E2</a>')
    2210          doc = ElementTree(file=f)
    2211          a = doc.getroot()
    2212          x = Element('x')
    2213          y = Element('y')
    2214          z = Element('z')
    2215          x.tail = 'X2'
    2216          y.tail = 'Y2'
    2217          z.tail = 'Z2'
    2218          a[1:3] = [x, y, z]
    2219          self.assertXML(
    2220              _bytes('<a><b></b>B2<x></x>X2<y></y>Y2<z></z>Z2<e></e>E2</a>'),
    2221              a)
    2222
    2223 -    def test_setslice_negative(self):
    2224          Element = self.etree.Element
    2225          SubElement = self.etree.SubElement
    2226
    2227          a = Element('a')
    2228          b = SubElement(a, 'b')
    2229          c = SubElement(a, 'c')
    2230          d = SubElement(a, 'd')
    2231
    2232          x = Element('x')
    2233          y = Element('y')
    2234
    2235          a[1:-1] = [x, y]
    2236          self.assertEquals(
    2237              [b, x, y, d],
    2238              list(a))
    2239
    2240 -    def test_setslice_negative2(self):
    2241          Element = self.etree.Element
    2242          SubElement = self.etree.SubElement
    2243
    2244          a = Element('a')
    2245          b = SubElement(a, 'b')
    2246          c = SubElement(a, 'c')
    2247          d = SubElement(a, 'd')
    2248
    2249          x = Element('x')
    2250          y = Element('y')
    2251
    2252          a[1:-2] = [x, y]
    2253          self.assertEquals(
    2254              [b, x, y, c, d],
    2255              list(a))
    2256
    2257 -    def test_setslice_end(self):
    2258          Element = self.etree.Element
    2259          SubElement = self.etree.SubElement
    2260
    2261          a = Element('a')
    2262          b = SubElement(a, 'b')
    2263          c = SubElement(a, 'c')
    2264          d = SubElement(a, 'd')
    2265
    2266          e = Element('e')
    2267          f = Element('f')
    2268          g = Element('g')
    2269
    2270          s = [e, f, g]
    2271          a[3:] = s
    2272          self.assertEquals(
    2273              [b, c, d, e, f, g],
    2274              list(a))
    2275
    2276 -    def test_setslice_empty(self):
    2277          Element = self.etree.Element
    2278
    2279          a = Element('a')
    2280
    2281          b = Element('b')
    2282          c = Element('c')
    2283
    2284          a[:] = [b, c]
    2285          self.assertEquals(
    2286              [b, c],
    2287              list(a))
    2288
    2289 -    def test_tail_elementtree_root(self):
    2290          Element = self.etree.Element
    2291          ElementTree = self.etree.ElementTree
    2292
    2293          a = Element('a')
    2294          a.tail = 'A2'
    2295          t = ElementTree(element=a)
    2296          self.assertEquals('A2',
    2297                            a.tail)
    2298
    2299 -    def test_elementtree_getiterator(self):
    2300          Element = self.etree.Element
    2301          SubElement = self.etree.SubElement
    2302          ElementTree = self.etree.ElementTree
    2303
    2304          a = Element('a')
    2305          b = SubElement(a, 'b')
    2306          c = SubElement(a, 'c')
    2307          d = SubElement(b, 'd')
    2308          e = SubElement(c, 'e')
    2309          t = ElementTree(element=a)
    2310
    2311          self.assertEquals(
    2312              [a, b, d, c, e],
    2313              list(t.getiterator()))
    2314
    2315 -    def test_elementtree_getiterator_filter(self):
    2316          Element = self.etree.Element
    2317          SubElement = self.etree.SubElement
    2318          ElementTree = self.etree.ElementTree
    2319          a = Element('a')
    2320          b = SubElement(a, 'b')
    2321          c = SubElement(a, 'c')
    2322          d = SubElement(b, 'd')
    2323          e = SubElement(c, 'e')
    2324          t = ElementTree(element=a)
    2325
    2326          self.assertEquals(
    2327              [a],
    2328              list(t.getiterator('a')))
    2329          a2 = SubElement(e, 'a')
    2330          self.assertEquals(
    2331              [a, a2],
    2332              list(t.getiterator('a')))
    2333
    2334 -    def test_ns_access(self):
    2335          ElementTree = self.etree.ElementTree
    2336          ns = 'http://xml.infrae.com/1'
    2337          f = BytesIO('<x:a xmlns:x="%s"><x:b></x:b></x:a>' % ns)
    2338          t = ElementTree(file=f)
    2339          a = t.getroot()
    2340          self.assertEquals('{%s}a' % ns,
    2341                            a.tag)
    2342          self.assertEquals('{%s}b' % ns,
    2343                            a[0].tag)
    2344
    2345 -    def test_ns_access2(self):
    2346          ElementTree = self.etree.ElementTree
    2347          ns = 'http://xml.infrae.com/1'
    2348          ns2 = 'http://xml.infrae.com/2'
    2349          f = BytesIO('<x:a xmlns:x="%s" xmlns:y="%s"><x:b></x:b><y:b></y:b></x:a>' % (ns, ns2))
    2350          t = ElementTree(file=f)
    2351          a = t.getroot()
    2352          self.assertEquals('{%s}a' % ns,
    2353                            a.tag)
    2354          self.assertEquals('{%s}b' % ns,
    2355                            a[0].tag)
    2356          self.assertEquals('{%s}b' % ns2,
    2357                            a[1].tag)
    2358
    2359 -    def test_ns_setting(self):
    2360          Element = self.etree.Element
    2361          SubElement = self.etree.SubElement
    2362          ns = 'http://xml.infrae.com/1'
    2363          ns2 = 'http://xml.infrae.com/2'
    2364          a = Element('{%s}a' % ns)
    2365          b = SubElement(a, '{%s}b' % ns2)
    2366          c = SubElement(a, '{%s}c' % ns)
    2367          self.assertEquals('{%s}a' % ns,
    2368                            a.tag)
    2369          self.assertEquals('{%s}b' % ns2,
    2370                            b.tag)
    2371          self.assertEquals('{%s}c' % ns,
    2372                            c.tag)
    2373          self.assertEquals('{%s}a' % ns,
    2374                            a.tag)
    2375          self.assertEquals('{%s}b' % ns2,
    2376                            b.tag)
    2377          self.assertEquals('{%s}c' % ns,
    2378                            c.tag)
    2379
    2380 -    def test_ns_tag_parse(self):
    2381          Element = self.etree.Element
    2382          SubElement = self.etree.SubElement
    2383          ElementTree = self.etree.ElementTree
    2384
    2385          ns = 'http://xml.infrae.com/1'
    2386          ns2 = 'http://xml.infrae.com/2'
    2387          f = BytesIO('<a xmlns="%s" xmlns:x="%s"><x:b></x:b><b></b></a>' % (ns, ns2))
    2388          t = ElementTree(file=f)
    2389
    2390          a = t.getroot()
    2391          self.assertEquals('{%s}a' % ns,
    2392                            a.tag)
    2393          self.assertEquals('{%s}b' % ns2,
    2394                            a[0].tag)
    2395          self.assertEquals('{%s}b' % ns,
    2396                            a[1].tag)
    2397
    2398 -    def test_ns_attr(self):
    2399          Element = self.etree.Element
    2400          ns = 'http://xml.infrae.com/1'
    2401          ns2 = 'http://xml.infrae.com/2'
    2402          a = Element('a')
    2403          a.set('{%s}foo' % ns, 'Foo')
    2404          a.set('{%s}bar' % ns2, 'Bar')
    2405          self.assertEquals(
    2406              'Foo',
    2407              a.get('{%s}foo' % ns))
    2408          self.assertEquals(
    2409              'Bar',
    2410              a.get('{%s}bar' % ns2))
    2411          try:
    2412              self.assertXML(
    2413                  _bytes('<a xmlns:ns0="%s" xmlns:ns1="%s" ns0:foo="Foo" ns1:bar="Bar"></a>' % (ns, ns2)),
    2414                  a)
    2415          except AssertionError:
    2416              self.assertXML(
    2417                  _bytes('<a xmlns:ns0="%s" xmlns:ns1="%s" ns1:foo="Foo" ns0:bar="Bar"></a>' % (ns2, ns)),
    2418                  a)
    2419
    2420 -    def test_ns_move(self):
    2421          Element = self.etree.Element
    2422          one = self.etree.fromstring(
    2423              _bytes('<foo><bar xmlns:ns="http://a.b.c"><ns:baz/></bar></foo>'))
    2424          baz = one[0][0]
    2425
    2426          two = Element('root')
    2427          two.append(baz)
    2428          # removing the originating document could cause a crash/error before
    2429          # as namespace is not moved along with it
    2430          del one, baz
    2431          self.assertEquals('{http://a.b.c}baz', two[0].tag)
    2432
    2433 -    def test_ns_decl_tostring(self):
    2434          tostring = self.etree.tostring
    2435          root = self.etree.XML(
    2436              _bytes('<foo><bar xmlns:ns="http://a.b.c"><ns:baz/></bar></foo>'))
    2437          baz = root[0][0]
    2438
    2439          nsdecl = re.findall(_bytes("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']"),
    2440                              tostring(baz))
    2441          self.assertEquals([_bytes("http://a.b.c")], nsdecl)
    2442
    2443 -    def test_ns_decl_tostring_default(self):
    2444          tostring = self.etree.tostring
    2445          root = self.etree.XML(
    2446              _bytes('<foo><bar xmlns="http://a.b.c"><baz/></bar></foo>'))
    2447          baz = root[0][0]
    2448
    2449          nsdecl = re.findall(_bytes("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']"),
    2450                              tostring(baz))
    2451          self.assertEquals([_bytes("http://a.b.c")], nsdecl)
    2452
    2453 -    def test_ns_decl_tostring_root(self):
    2454          tostring = self.etree.tostring
    2455          root = self.etree.XML(
    2456              _bytes('<foo xmlns:ns="http://a.b.c"><bar><ns:baz/></bar></foo>'))
    2457          baz = root[0][0]
    2458
    2459          nsdecl = re.findall(_bytes("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']"),
    2460                              tostring(baz))
    2461
    2462          self.assertEquals([_bytes("http://a.b.c")], nsdecl)
    2463
    2464 -    def test_ns_decl_tostring_element(self):
    2465          Element = self.etree.Element
    2466          SubElement = self.etree.SubElement
    2467
    2468          root = Element("foo")
    2469          bar = SubElement(root, "{http://a.b.c}bar")
    2470          baz = SubElement(bar, "{http://a.b.c}baz")
    2471
    2472          nsdecl = re.findall(_bytes("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']"),
    2473                              self.etree.tostring(baz))
    2474
    2475          self.assertEquals([_bytes("http://a.b.c")], nsdecl)
    2476
    2477 -    def test_attribute_xmlns_move(self):
    2478          Element = self.etree.Element
    2479
    2480          root = Element('element')
    2481
    2482          subelement = Element('subelement',
    2483                               {"{http://www.w3.org/XML/1998/namespace}id": "foo"})
    2484          self.assertEquals(1, len(subelement.attrib))
    2485          self.assertEquals(
    2486              "foo",
    2487              subelement.get("{http://www.w3.org/XML/1998/namespace}id"))
    2488
    2489          root.append(subelement)
    2490          self.assertEquals(1, len(subelement.attrib))
    2491          self.assertEquals(
    2492              list({"{http://www.w3.org/XML/1998/namespace}id" : "foo"}.items()),
    2493              list(subelement.attrib.items()))
    2494          self.assertEquals(
    2495              "foo",
    2496              subelement.get("{http://www.w3.org/XML/1998/namespace}id"))
    2497
    2498 -    def test_namespaces_after_serialize(self):
    2499          parse = self.etree.parse
    2500          tostring = self.etree.tostring
    2501
    2502          ns_href = "http://a.b.c"
    2503          one = parse(
    2504              BytesIO('<foo><bar xmlns:ns="%s"><ns:baz/></bar></foo>' % ns_href))
    2505          baz = one.getroot()[0][0]
    2506
    2507          parsed = parse(BytesIO( tostring(baz) )).getroot()
    2508          self.assertEquals('{%s}baz' % ns_href, parsed.tag)
    2509
    2510 -    def test_tostring(self):
    2511          tostring = self.etree.tostring
    2512          Element = self.etree.Element
    2513          SubElement = self.etree.SubElement
    2514
    2515          a = Element('a')
    2516          b = SubElement(a, 'b')
    2517          c = SubElement(a, 'c')
    2518
    2519          self.assertEquals(_bytes('<a><b></b><c></c></a>'),
    2520                            canonicalize(tostring(a)))
    2521
    2522 -    def test_tostring_element(self):
    2523          tostring = self.etree.tostring
    2524          Element = self.etree.Element
    2525          SubElement = self.etree.SubElement
    2526
    2527          a = Element('a')
    2528          b = SubElement(a, 'b')
    2529          c = SubElement(a, 'c')
    2530          d = SubElement(c, 'd')
    2531          self.assertEquals(_bytes('<b></b>'),
    2532                            canonicalize(tostring(b)))
    2533          self.assertEquals(_bytes('<c><d></d></c>'),
    2534                            canonicalize(tostring(c)))
    2535
    2536 -    def test_tostring_element_tail(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          b.tail = 'Foo'
    2546
    2547          self.assert_(tostring(b) == _bytes('<b/>Foo') or
    2548                       tostring(b) == _bytes('<b />Foo'))
    2549
    2550 -    def test_tostring_method_html(self):
    2551          tostring = self.etree.tostring
    2552          Element = self.etree.Element
    2553          SubElement = self.etree.SubElement
    2554
    2555          html = Element('html')
    2556          body = SubElement(html, 'body')
    2557          p = SubElement(body, 'p')
    2558          p.text = "html"
    2559          SubElement(p, 'br').tail = "test"
    2560
    2561          self.assertEquals(_bytes('<html><body><p>html<br>test</p></body></html>'),
    2562                            tostring(html, method="html"))
    2563
    2564 -    def test_tostring_method_text(self):
    2565          tostring = self.etree.tostring
    2566          Element = self.etree.Element
    2567          SubElement = self.etree.SubElement
    2568
    2569          a = Element('a')
    2570          a.text = "A"
    2571          a.tail = "tail"
    2572          b = SubElement(a, 'b')
    2573          b.text = "B"
    2574          b.tail = "TAIL"
    2575          c = SubElement(a, 'c')
    2576          c.text = "C"
    2577
    2578          self.assertEquals(_bytes('ABTAILCtail'),
    2579                            tostring(a, method="text"))
    2580
    2581 -    def test_iterparse(self):
    2582          iterparse = self.etree.iterparse
    2583          f = BytesIO('<a><b></b><c/></a>')
    2584
    2585          iterator = iterparse(f)
    2586          self.assertEquals(None,
    2587                            iterator.root)
    2588          events = list(iterator)
    2589          root = iterator.root
    2590          self.assertEquals(
    2591              [('end', root[0]), ('end', root[1]), ('end', root)],
    2592              events)
    2593
    2594 -    def test_iterparse_file(self):
    2595          iterparse = self.etree.iterparse
    2596          iterator = iterparse(fileInTestDir("test.xml"))
    2597          self.assertEquals(None,
    2598                            iterator.root)
    2599          events = list(iterator)
    2600          root = iterator.root
    2601          self.assertEquals(
    2602              [('end', root[0]), ('end', root)],
    2603              events)
    2604
    2605 -    def test_iterparse_start(self):
    2606          iterparse = self.etree.iterparse
    2607          f = BytesIO('<a><b></b><c/></a>')
    2608
    2609          iterator = iterparse(f, events=('start',))
    2610          events = list(iterator)
    2611          root = iterator.root
    2612          self.assertEquals(
    2613              [('start', root), ('start', root[0]), ('start', root[1])],
    2614              events)
    2615
    2616 -    def test_iterparse_start_end(self):
    2617          iterparse = self.etree.iterparse
    2618          f = BytesIO('<a><b></b><c/></a>')
    2619
    2620          iterator = iterparse(f, events=('start','end'))
    2621          events = list(iterator)
    2622          root = iterator.root
    2623          self.assertEquals(
    2624              [('start', root), ('start', root[0]), ('end', root[0]),
    2625               ('start', root[1]), ('end', root[1]), ('end', root)],
    2626              events)
    2627
    2628 -    def test_iterparse_clear(self):
    2629          iterparse = self.etree.iterparse
    2630          f = BytesIO('<a><b></b><c/></a>')
    2631
    2632          iterator = iterparse(f)
    2633          for event, elem in iterator:
    2634              elem.clear()
    2635
    2636          root = iterator.root
    2637          self.assertEquals(0,
    2638                            len(root))
    2639
    2640 -    def test_iterparse_large(self):
    2641          iterparse = self.etree.iterparse
    2642          CHILD_COUNT = 12345
    2643          f = BytesIO('<a>%s</a>' % ('<b>test</b>'*CHILD_COUNT))
    2644
    2645          i = 0
    2646          for key in iterparse(f):
    2647              event, element = key
    2648              i += 1
    2649          self.assertEquals(i, CHILD_COUNT + 1)
    2650
    2651 -    def test_iterparse_attrib_ns(self):
    2652          iterparse = self.etree.iterparse
    2653          f = BytesIO('<a xmlns="http://ns1/"><b><c xmlns="http://ns2/"/></b></a>')
    2654
    2655          attr_name = '{http://testns/}bla'
    2656          events = []
    2657          iterator = iterparse(f, events=('start','end','start-ns','end-ns'))
    2658          for event, elem in iterator:
    2659              events.append(event)
    2660              if event == 'start':
    2661                  if elem.tag != '{http://ns1/}a':
    2662                      elem.set(attr_name, 'value')
    2663
    2664          self.assertEquals(
    2665              ['start-ns', 'start', 'start', 'start-ns', 'start',
    2666               'end', 'end-ns', 'end', 'end', 'end-ns'],
    2667              events)
    2668
    2669          root = iterator.root
    2670          self.assertEquals(
    2671              None,
    2672              root.get(attr_name))
    2673          self.assertEquals(
    2674              'value',
    2675              root[0].get(attr_name))
    2676
    2677 -    def test_iterparse_getiterator(self):
    2678          iterparse = self.etree.iterparse
    2679          f = BytesIO('<a><b><d/></b><c/></a>')
    2680
    2681          counts = []
    2682          for event, elem in iterparse(f):
    2683              counts.append(len(list(elem.getiterator())))
    2684          self.assertEquals(
    2685              [1,2,1,4],
    2686              counts)
    2687
    2688 -    def test_iterparse_move_elements(self):
    2689          iterparse = self.etree.iterparse
    2690          f = BytesIO('<a><b><d/></b><c/></a>')
    2691
    2692          for event, node in etree.iterparse(f): pass
    2693
    2694          root = etree.Element('new_root', {})
    2695          root[:] = node[:]
    2696
    2697          self.assertEquals(
    2698              ['b', 'c'],
    2699              [ el.tag for el in root ])
    2700
    2701 -    def test_iterparse_cdata(self):
    2702          tostring = self.etree.tostring
    2703          f = BytesIO('<root><![CDATA[test]]></root>')
    2704          context = self.etree.iterparse(f)
    2705          content = [ el.text for event,el in context ]
    2706
    2707          self.assertEquals(['test'], content)
    2708          self.assertEquals(_bytes('<root>test</root>'),
    2709                            tostring(context.root))
    2710
    2711 -    def test_parse_file(self):
    2712          parse = self.etree.parse
    2713          # from file
    2714          tree = parse(fileInTestDir('test.xml'))
    2715          self.assertXML(
    2716              _bytes('<a><b></b></a>'),
    2717              tree.getroot())
    2718
    2719 -    def test_parse_file_nonexistent(self):
    2720          parse = self.etree.parse
    2721          self.assertRaises(IOError, parse, fileInTestDir('notthere.xml'))
    2722
    2723 -    def test_parse_error_none(self):
    2724          parse = self.etree.parse
    2725          self.assertRaises(TypeError, parse, None)
    2726
    2727 -    def test_parse_error(self):
    2728          # ET < 1.3 raises ExpatError
    2729          parse = self.etree.parse
    2730          f = BytesIO('<a><b></c></b></a>')
    2731          self.assertRaises(SyntaxError, parse, f)
    2732          f.close()
    2733
    2734 -    def test_parse_error_from_file(self):
    2735          parse = self.etree.parse
    2736          # from file
    2737          f = open(fileInTestDir('test_broken.xml'), 'rb')
    2738          self.assertRaises(SyntaxError, parse, f)
    2739          f.close()
    2740
    2741 -    def test_parse_file_object(self):
    2742          parse = self.etree.parse
    2743          # from file object
    2744          f = open(fileInTestDir('test.xml'), 'rb')
    2745          tree = parse(f)
    2746          f.close()
    2747          self.assertXML(
    2748              _bytes('<a><b></b></a>'),
    2749              tree.getroot())
    2750
    2751 -    def test_parse_stringio(self):
    2752          parse = self.etree.parse
    2753          f = BytesIO('<a><b></b></a>')
    2754          tree = parse(f)
    2755          f.close()
    2756          self.assertXML(
    2757              _bytes('<a><b></b></a>'),
    2758              tree.getroot()
    2759             )
    2760
    2761 -    def test_parse_cdata(self):
    2762          tostring = self.etree.tostring
    2763          root = self.etree.XML(_bytes('<root><![CDATA[test]]></root>'))
    2764
    2765          self.assertEquals('test', root.text)
    2766          self.assertEquals(_bytes('<root>test</root>'),
    2767                            tostring(root))
    2768
    2769 -    def test_parse_with_encoding(self):
    2770          # this can fail in libxml2 <= 2.6.22
    2771          parse = self.etree.parse
    2772          tree = parse(BytesIO('<?xml version="1.0" encoding="ascii"?><html/>'))
    2773          self.assertXML(_bytes('<html></html>'),
    2774                         tree.getroot())
    2775
    2776 -    def test_encoding(self):
    2777          Element = self.etree.Element
    2778
    2779          a = Element('a')
    2780          a.text = _str('Søk på nettet')
    2781          self.assertXML(
    2782              _str('<a>Søk på nettet</a>').encode('UTF-8'),
    2783              a, 'utf-8')
    2784
    2785 -    def test_encoding_exact(self):
    2786          ElementTree = self.etree.ElementTree
    2787          Element = self.etree.Element
    2788
    2789          a = Element('a')
    2790          a.text = _str('Søk på nettet')
    2791
    2792          f = BytesIO()
    2793          tree = ElementTree(element=a)
    2794          tree.write(f, encoding='utf-8')
    2795          self.assertEquals(_str('<a>Søk på nettet</a>').encode('UTF-8'),
    2796                            f.getvalue().replace(_bytes('\n'),_bytes('')))
    2797
    2798 -    def test_parse_file_encoding(self):
    2799          parse = self.etree.parse
    2800          # from file
    2801          tree = parse(fileInTestDir('test-string.xml'))
    2802          self.assertXML(
    2803              _str('<a>Søk på nettet</a>').encode('UTF-8'),
    2804              tree.getroot(), 'UTF-8')
    2805
    2806 -    def test_parse_file_object_encoding(self):
    2807          parse = self.etree.parse
    2808          # from file object
    2809          f = open(fileInTestDir('test-string.xml'), 'rb')
    2810          tree = parse(f)
    2811          f.close()
    2812          self.assertXML(
    2813              _str('<a>Søk på nettet</a>').encode('UTF-8'),
    2814              tree.getroot(), 'UTF-8')
    2815
    2816 -    def test_encoding_8bit_latin1(self):
    2817          ElementTree = self.etree.ElementTree
    2818          Element = self.etree.Element
    2819
    2820          a = Element('a')
    2821          a.text = _str('Søk på nettet')
    2822
    2823          f = BytesIO()
    2824          tree = ElementTree(element=a)
    2825          tree.write(f, encoding='iso-8859-1')
    2826          result = f.getvalue()
    2827          declaration = _bytes("<?xml version=\'1.0\' encoding=\'iso-8859-1\'?>")
    2828          self.assertEncodingDeclaration(result, _bytes('iso-8859-1'))
    2829          result = result.split(_bytes('?>'), 1)[-1].replace(_bytes('\n'),_bytes(''))
    2830          self.assertEquals(_str('<a>Søk på nettet</a>').encode('iso-8859-1'),
    2831                            result)
    2832
    2833 -    def test_parse_encoding_8bit_explicit(self):
    2834          XMLParser = self.etree.XMLParser
    2835
    2836          text = _str('Søk på nettet')
    2837          xml_latin1 = (_str('<a>%s</a>') % text).encode('iso-8859-1')
    2838
    2839          self.assertRaises(self.etree.ParseError,
    2840                            self.etree.parse,
    2841                            BytesIO(xml_latin1))
    2842
    2843          tree = self.etree.parse(BytesIO(xml_latin1),
    2844                                  XMLParser(encoding="iso-8859-1"))
    2845          a = tree.getroot()
    2846          self.assertEquals(a.text, text)
    2847
    2848 -    def test_parse_encoding_8bit_override(self):
    2849          XMLParser = self.etree.XMLParser
    2850
    2851          text = _str('Søk på nettet')
    2852          wrong_declaration = _str("<?xml version='1.0' encoding='UTF-8'?>")
    2853          xml_latin1 = (_str('%s<a>%s</a>') % (wrong_declaration, text)
    2854                        ).encode('iso-8859-1')
    2855
    2856          self.assertRaises(self.etree.ParseError,
    2857                            self.etree.parse,
    2858                            BytesIO(xml_latin1))
    2859
    2860          tree = self.etree.parse(BytesIO(xml_latin1),
    2861                                  XMLParser(encoding="iso-8859-1"))
    2862          a = tree.getroot()
    2863          self.assertEquals(a.text, text)
    2864
    2865 -    def _test_wrong_unicode_encoding(self):
    2866          # raise error on wrong encoding declaration in unicode strings
    2867          XML = self.etree.XML
    2868          test_utf = (_str('<?xml version="1.0" encoding="iso-8859-1"?>') +
    2869                      _str('<a>Søk på nettet</a>'))
    2870          self.assertRaises(SyntaxError, XML, test_utf)
    2871
    2872 -    def test_encoding_write_default_encoding(self):
    2873          ElementTree = self.etree.ElementTree
    2874          Element = self.etree.Element
    2875
    2876          a = Element('a')
    2877          a.text = _str('Søk på nettet')
    2878
    2879          f = BytesIO()
    2880          tree = ElementTree(element=a)
    2881          tree.write(f)
    2882          data = f.getvalue().replace(_bytes('\n'),_bytes(''))
    2883          self.assertEquals(
    2884              _str('<a>Søk på nettet</a>').encode('ASCII', 'xmlcharrefreplace'),
    2885              data)
    2886
    2887 -    def test_encoding_tostring(self):
    2888          Element = self.etree.Element
    2889          tostring = self.etree.tostring
    2890
    2891          a = Element('a')
    2892          a.text = _str('Søk på nettet')
    2893          self.assertEquals(_str('<a>Søk på nettet</a>').encode('UTF-8'),
    2894                           tostring(a, encoding='utf-8'))
    2895
    2896 -    def test_encoding_tostring_unknown(self):
    2897          Element = self.etree.Element
    2898          tostring = self.etree.tostring
    2899
    2900          a = Element('a')
    2901          a.text = _str('Søk på nettet')
    2902          self.assertRaises(LookupError, tostring, a,
    2903                            encoding='Invalid Encoding')
    2904
    2905 -    def test_encoding_tostring_sub(self):
    2906          Element = self.etree.Element
    2907          SubElement = self.etree.SubElement
    2908          tostring = self.etree.tostring
    2909
    2910          a = Element('a')
    2911          b = SubElement(a, 'b')
    2912          b.text = _str('Søk på nettet')
    2913          self.assertEquals(_str('<b>Søk på nettet</b>').encode('UTF-8'),
    2914                           tostring(b, encoding='utf-8'))
    2915
    2916 -    def test_encoding_tostring_sub_tail(self):
    2917          Element = self.etree.Element
    2918          SubElement = self.etree.SubElement
    2919          tostring = self.etree.tostring
    2920
    2921          a = Element('a')
    2922          b = SubElement(a, 'b')
    2923          b.text = _str('Søk på nettet')
    2924          b.tail = _str('Søk')
    2925          self.assertEquals(_str('<b>Søk på nettet</b>Søk').encode('UTF-8'),
    2926                           tostring(b, encoding='utf-8'))
    2927
    2928 -    def test_encoding_tostring_default_encoding(self):
    2929          Element = self.etree.Element
    2930          SubElement = self.etree.SubElement
    2931          tostring = self.etree.tostring
    2932
    2933          a = Element('a')
    2934          a.text = _str('Søk på nettet')
    2935
    2936          expected = _bytes('<a>S&#248;k p&#229; nettet</a>')
    2937          self.assertEquals(
    2938              expected,
    2939              tostring(a))
    2940
    2941 -    def test_encoding_sub_tostring_default_encoding(self):
    2942          Element = self.etree.Element
    2943          SubElement = self.etree.SubElement
    2944          tostring = self.etree.tostring
    2945
    2946          a = Element('a')
    2947          b = SubElement(a, 'b')
    2948          b.text = _str('Søk på nettet')
    2949
    2950          expected = _bytes('<b>S&#248;k p&#229; nettet</b>')
    2951          self.assertEquals(
    2952              expected,
    2953              tostring(b))
    2954
    2955 -    def test_encoding_8bit_xml(self):
    2956          utext = _str('Søk på nettet')
    2957          uxml = _str('<p>%s</p>') % utext
    2958          prologue = _bytes('<?xml version="1.0" encoding="iso-8859-1" ?>')
    2959          isoxml = prologue + uxml.encode('iso-8859-1')
    2960          tree = self.etree.XML(isoxml)
    2961          self.assertEquals(utext, tree.text)
    2962
    2963 -    def test_encoding_utf8_bom(self):
    2964          utext = _str('Søk på nettet')
    2965          uxml = (_str('<?xml version="1.0" encoding="UTF-8"?>') +
    2966                  _str('<p>%s</p>') % utext)
    2967          bom = _bytes('\\xEF\\xBB\\xBF').decode("unicode_escape").encode("latin1")
    2968          xml = bom + uxml.encode("utf-8")
    2969          tree = etree.XML(xml)
    2970          self.assertEquals(utext, tree.text)
    2971
    2972 -    def test_encoding_8bit_parse_stringio(self):
    2973          utext = _str('Søk på nettet')
    2974          uxml = _str('<p>%s</p>') % utext
    2975          prologue = _bytes('<?xml version="1.0" encoding="iso-8859-1" ?>')
    2976          isoxml = prologue + uxml.encode('iso-8859-1')
    2977          el = self.etree.parse(BytesIO(isoxml)).getroot()
    2978          self.assertEquals(utext, el.text)
    2979
    2980 -    def test_deepcopy_elementtree(self):
    2981          Element = self.etree.Element
    2982          ElementTree = self.etree.ElementTree
    2983
    2984          a = Element('a')
    2985          a.text = "Foo"
    2986          atree = ElementTree(a)
    2987
    2988          btree = copy.deepcopy(atree)
    2989          self.assertEqual("Foo", atree.getroot().text)
    2990          self.assertEqual("Foo", btree.getroot().text)
    2991          self.assertFalse(btree is atree)
    2992          self.assertFalse(btree.getroot() is atree.getroot())
    2993
    2994 -    def test_deepcopy(self):
    2995          Element = self.etree.Element
    2996
    2997          a = Element('a')
    2998          a.text = 'Foo'
    2999
    3000          b = copy.deepcopy(a)
    3001          self.assertEquals('Foo', b.text)
    3002
    3003          b.text = 'Bar'
    3004          self.assertEquals('Bar', b.text)
    3005          self.assertEquals('Foo', a.text)
    3006
    3007          del a
    3008          self.assertEquals('Bar', b.text)
    3009
    3010 -    def test_deepcopy_tail(self):
    3011          Element = self.etree.Element
    3012
    3013          a = Element('a')
    3014          a.tail = 'Foo'
    3015
    3016          b = copy.deepcopy(a)
    3017          self.assertEquals('Foo', b.tail)
    3018
    3019          b.tail = 'Bar'
    3020          self.assertEquals('Bar', b.tail)
    3021          self.assertEquals('Foo', a.tail)
    3022
    3023          del a
    3024          self.assertEquals('Bar', b.tail)
    3025
    3026 -    def test_deepcopy_subelement(self):
    3027          Element = self.etree.Element
    3028          SubElement = self.etree.SubElement
    3029
    3030          root = Element('root')
    3031          a = SubElement(root, 'a')
    3032          a.text = 'FooText'
    3033          a.tail = 'FooTail'
    3034
    3035          b = copy.deepcopy(a)
    3036          self.assertEquals('FooText', b.text)
    3037          self.assertEquals('FooTail', b.tail)
    3038
    3039          b.text = 'BarText'
    3040          b.tail = 'BarTail'
    3041          self.assertEquals('BarTail', b.tail)
    3042          self.assertEquals('FooTail', a.tail)
    3043          self.assertEquals('BarText', b.text)
    3044          self.assertEquals('FooText', a.text)
    3045
    3046          del a
    3047          self.assertEquals('BarTail', b.tail)
    3048          self.assertEquals('BarText', b.text)
    3049
    3050 -    def test_deepcopy_namespaces(self):
    3051          root = self.etree.XML(_bytes('''<doc xmlns="dns" xmlns:t="tns">
    3052          <parent><node t:foo="bar" /></parent>
    3053          </doc>'''))
    3054          self.assertEquals(
    3055              root[0][0].get('{tns}foo'),
    3056              copy.deepcopy(root[0])[0].get('{tns}foo') )
    3057          self.assertEquals(
    3058              root[0][0].get('{tns}foo'),
    3059              copy.deepcopy(root[0][0]).get('{tns}foo') )
    3060
    3061 -    def test_deepcopy_append(self):
    3062          # previously caused a crash
    3063          Element = self.etree.Element
    3064          tostring = self.etree.tostring
    3065
    3066          a = Element('a')
    3067          b = copy.deepcopy(a)
    3068          a.append( Element('C') )
    3069          b.append( Element('X') )
    3070
    3071          self.assertEquals(_bytes('<a><C/></a>'),
    3072                            tostring(a).replace(_bytes(' '), _bytes('')))
    3073          self.assertEquals(_bytes('<a><X/></a>'),
    3074                            tostring(b).replace(_bytes(' '), _bytes('')))
    3075
    3076 -    def test_deepcopy_comment(self):
    3077          # previously caused a crash
    3078          # not supported by ET < 1.3!
    3079          Comment = self.etree.Comment
    3080
    3081          a = Comment("ONE")
    3082          b = copy.deepcopy(a)
    3083          b.text = "ANOTHER"
    3084
    3085          self.assertEquals('ONE',     a.text)
    3086          self.assertEquals('ANOTHER', b.text)
    3087
    3088 -    def test_shallowcopy(self):
    3089          Element = self.etree.Element
    3090
    3091          a = Element('a')
    3092          a.text = 'Foo'
    3093
    3094          b = copy.copy(a)
    3095          self.assertEquals('Foo', b.text)
    3096
    3097          b.text = 'Bar'
    3098          self.assertEquals('Bar', b.text)
    3099          self.assertEquals('Foo', a.text)
    3100          # XXX ElementTree will share nodes, but lxml.etree won't..
    3101
    3102 -    def test_shallowcopy_elementtree(self):
    3103          Element = self.etree.Element
    3104          ElementTree = self.etree.ElementTree
    3105
    3106          a = Element('a')
    3107          a.text = 'Foo'
    3108          atree = ElementTree(a)
    3109
    3110          btree = copy.copy(atree)
    3111          self.assertFalse(btree is atree)
    3112          self.assert_(btree.getroot() is atree.getroot())
    3113          self.assertEquals('Foo', atree.getroot().text)
    3114
    3115 -    def _test_element_boolean(self):
    3116          # deprecated as of ET 1.3/lxml 2.0
    3117          etree = self.etree
    3118          e = etree.Element('foo')
    3119          self.assertEquals(False, bool(e))
    3120          etree.SubElement(e, 'bar')
    3121          self.assertEquals(True, bool(e))
    3122          e = etree.Element('foo')
    3123          e.text = 'hey'
    3124          self.assertEquals(False, bool(e))
    3125          e = etree.Element('foo')
    3126          e.tail = 'bar'
    3127          self.assertEquals(False, bool(e))
    3128          e = etree.Element('foo')
    3129          e.set('bar', 'Bar')
    3130          self.assertEquals(False, bool(e))
    3131
    3132 -    def test_multiple_elementrees(self):
    3133          etree = self.etree
    3134
    3135          a = etree.Element('a')
    3136          b = etree.SubElement(a, 'b')
    3137
    3138          t = etree.ElementTree(a)
    3139          self.assertEquals(self._rootstring(t), _bytes('<a><b/></a>'))
    3140
    3141          t1 = etree.ElementTree(a)
    3142          self.assertEquals(self._rootstring(t1), _bytes('<a><b/></a>'))
    3143          self.assertEquals(self._rootstring(t),  _bytes('<a><b/></a>'))
    3144
    3145          t2 = etree.ElementTree(b)
    3146          self.assertEquals(self._rootstring(t2), _bytes('<b/>'))
    3147          self.assertEquals(self._rootstring(t1), _bytes('<a><b/></a>'))
    3148          self.assertEquals(self._rootstring(t),  _bytes('<a><b/></a>'))
    3149
    3150 -    def test_qname(self):
    3151          etree = self.etree
    3152          qname = etree.QName('myns', 'a')
    3153          a1 = etree.Element(qname)
    3154          a2 = etree.SubElement(a1, qname)
    3155          self.assertEquals(a1.tag, "{myns}a")
    3156          self.assertEquals(a2.tag, "{myns}a")
    3157
    3158 -    def test_qname_cmp(self):
    3159          etree = self.etree
    3160          qname1 = etree.QName('myns', 'a')
    3161          qname2 = etree.QName('myns', 'a')
    3162          self.assertEquals(qname1, "{myns}a")
    3163          self.assertEquals("{myns}a", qname2)
    3164          self.assertEquals(qname1, qname1)
    3165          self.assertEquals(qname1, qname2)
    3166
    3167 -    def test_qname_attribute_getset(self):
    3168          etree = self.etree
    3169          qname = etree.QName('myns', 'a')
    3170
    3171          a = etree.Element(qname)
    3172          a.set(qname, "value")
    3173
    3174          self.assertEquals(a.get(qname), "value")
    3175          self.assertEquals(a.get("{myns}a"), "value")
    3176
    3177 -    def test_qname_attrib(self):
    3178          etree = self.etree
    3179          qname = etree.QName('myns', 'a')
    3180
    3181          a = etree.Element(qname)
    3182          a.attrib[qname] = "value"
    3183
    3184          self.assertEquals(a.attrib[qname], "value")
    3185          self.assertEquals(a.attrib.get(qname), "value")
    3186
    3187          self.assertEquals(a.attrib["{myns}a"], "value")
    3188          self.assertEquals(a.attrib.get("{myns}a"), "value")
    3189
    3190 -    def test_qname_attribute_resolve(self):
    3191          etree = self.etree
    3192          qname = etree.QName('http://myns', 'a')
    3193          a = etree.Element(qname)
    3194          a.set(qname, qname)
    3195
    3196          self.assertXML(
    3197              _bytes('<ns0:a xmlns:ns0="http://myns" ns0:a="ns0:a"></ns0:a>'),
    3198              a)
    3199
    3200 -    def test_qname_attribute_resolve_new(self):
    3201          etree = self.etree
    3202          qname = etree.QName('http://myns', 'a')
    3203          a = etree.Element('a')
    3204          a.set('a', qname)
    3205
    3206          self.assertXML(
    3207              _bytes('<a xmlns:ns0="http://myns" a="ns0:a"></a>'),
    3208              a)
    3209
    3210 -    def test_qname_attrib_resolve(self):
    3211          etree = self.etree
    3212          qname = etree.QName('http://myns', 'a')
    3213          a = etree.Element(qname)
    3214          a.attrib[qname] = qname
    3215
    3216          self.assertXML(
    3217              _bytes('<ns0:a xmlns:ns0="http://myns" ns0:a="ns0:a"></ns0:a>'),
    3218              a)
    3219
    3220 -    def test_parser_version(self):
    3221          etree = self.etree
    3222          parser = etree.XMLParser()
    3223          if hasattr(parser, "version"):
    3224              # ElementTree 1.3+, cET
    3225              self.assert_(re.match("[^ ]+ [0-9.]+", parser.version))
    3226
    3227      # feed parser interface
    3228
    3229 -    def test_feed_parser(self):
    3230          parser = self.etree.XMLParser()
    3231
    3232          parser.feed('<?xml version=')
    3233          parser.feed('"1.0"?><ro')
    3234          parser.feed('ot><')
    3235          parser.feed('a test="works"/')
    3236          parser.feed('></root')
    3237          parser.feed('>')
    3238
    3239          root = parser.close()
    3240
    3241          self.assertEquals(root.tag, "root")
    3242          self.assertEquals(root[0].tag, "a")
    3243          self.assertEquals(root[0].get("test"), "works")
    3244
    3245 -    def test_feed_parser_error_close_empty(self):
    3246          ParseError = self.etree.ParseError
    3247          parser = self.etree.XMLParser()
    3248          self.assertRaises(ParseError, parser.close)
    3249
    3250 -    def test_feed_parser_error_close_incomplete(self):
    3251          ParseError = self.etree.ParseError
    3252          parser = self.etree.XMLParser()
    3253
    3254          parser.feed('<?xml version=')
    3255          parser.feed('"1.0"?><ro')
    3256
    3257          self.assertRaises(ParseError, parser.close)
    3258
    3259 -    def test_feed_parser_error_broken(self):
    3260          ParseError = self.etree.ParseError
    3261          parser = self.etree.XMLParser()
    3262
    3263          parser.feed('<?xml version=')
    3264          parser.feed('"1.0"?><ro')
    3265          try:
    3266              parser.feed('<><><><><><><')
    3267          except ParseError:
    3268              # can raise, but not required before close()
    3269              pass
    3270
    3271          self.assertRaises(ParseError, parser.close)
    3272
    3273 -    def test_feed_parser_error_position(self):
    3274          ParseError = self.etree.ParseError
    3275          parser = self.etree.XMLParser()
    3276          try:
    3277              parser.close()
    3278          except ParseError:
    3279              e = sys.exc_info()[1]
    3280              self.assertNotEquals(None, e.code)
    3281              self.assertNotEquals(0, e.code)
    3282              self.assert_(isinstance(e.position, tuple))
    3283              self.assert_(e.position >= (0, 0))
    3284
    3285      # parser target interface
    3286
    3287 -    def test_parser_target_tag(self):
    3288          assertEquals = self.assertEquals
    3289          assertFalse  = self.assertFalse
    3290
    3291          events = []
    3292          class Target(object):
    3293              def start(self, tag, attrib):
    3294                  events.append("start")
    3295                  assertFalse(attrib)
    3296                  assertEquals("TAG", tag)
    3297              def end(self, tag):
    3298                  events.append("end")
    3299                  assertEquals("TAG", tag)
    3300              def close(self):
    3301                  return "DONE"
    3302
    3303          parser = self.etree.XMLParser(target=Target())
    3304
    3305          parser.feed("<TAG/>")
    3306          done = parser.close()
    3307
    3308          self.assertEquals("DONE", done)
    3309          self.assertEquals(["start", "end"], events)
    3310
    3311 -    def test_elementtree_parser_target(self):
    3312          assertEquals = self.assertEquals
    3313          assertFalse  = self.assertFalse
    3314          Element = self.etree.Element
    3315
    3316          events = []
    3317          class Target(object):
    3318              def start(self, tag, attrib):
    3319                  events.append("start")
    3320                  assertFalse(attrib)
    3321                  assertEquals("TAG", tag)
    3322              def end(self, tag):
    3323                  events.append("end")
    3324                  assertEquals("TAG", tag)
    3325              def close(self):
    3326                  return Element("DONE")
    3327
    3328          parser = self.etree.XMLParser(target=Target())
    3329          tree = self.etree.ElementTree()
    3330          tree.parse(BytesIO("<TAG/>"), parser=parser)
    3331
    3332          self.assertEquals("DONE", tree.getroot().tag)
    3333          self.assertEquals(["start", "end"], events)
    3334
    3335 -    def test_parser_target_attrib(self):
    3336          assertEquals = self.assertEquals
    3337
    3338          events = []
    3339          class Target(object):
    3340              def start(self, tag, attrib):
    3341                  events.append("start-" + tag)
    3342                  for name, value in attrib.items():
    3343                      assertEquals(tag + name, value)
    3344              def end(self, tag):
    3345                  events.append("end-" + tag)
    3346              def close(self):
    3347                  return "DONE"
    3348
    3349          parser = self.etree.XMLParser(target=Target())
    3350
    3351          parser.feed('<root a="roota" b="rootb"><sub c="subc"/></root>')
    3352          done = parser.close()
    3353
    3354          self.assertEquals("DONE", done)
    3355          self.assertEquals(["start-root", "start-sub", "end-sub", "end-root"],
    3356                            events)
    3357
    3358 -    def test_parser_target_data(self):
    3359          events = []
    3360          class Target(object):
    3361              def start(self, tag, attrib):
    3362                  events.append("start-" + tag)
    3363              def end(self, tag):
    3364                  events.append("end-" + tag)
    3365              def data(self, data):
    3366                  events.append("data-" + data)
    3367              def close(self):
    3368                  return "DONE"
    3369
    3370          parser = self.etree.XMLParser(target=Target())
    3371
    3372          parser.feed('<root>A<sub/>B</root>')
    3373          done = parser.close()
    3374
    3375          self.assertEquals("DONE", done)
    3376          self.assertEquals(["start-root", "data-A", "start-sub",
    3377                             "end-sub", "data-B", "end-root"],
    3378                            events)
    3379
    3380 -    def test_parser_target_entity(self):
    3381          events = []
    3382          class Target(object):
    3383              def __init__(self):
    3384                  self._data = []
    3385              def _flush_data(self):
    3386                  if self._data:
    3387                      events.append("data-" + ''.join(self._data))
    3388                      del self._data[:]
    3389              def start(self, tag, attrib):
    3390                  self._flush_data()
    3391                  events.append("start-" + tag)
    3392              def end(self, tag):
    3393                  self._flush_data()
    3394                  events.append("end-" + tag)
    3395              def data(self, data):
    3396                  self._data.append(data)
    3397              def close(self):
    3398                  self._flush_data()
    3399                  return "DONE"
    3400
    3401          parser = self.etree.XMLParser(target=Target())
    3402
    3403          dtd = '''
    3404              <!DOCTYPE root [
    3405              <!ELEMENT root (sub*)>
    3406              <!ELEMENT sub (#PCDATA)>
    3407              <!ENTITY ent "an entity">
    3408          ]>
    3409          '''
    3410          parser.feed(dtd+'<root><sub/><sub>this is &ent;</sub><sub/></root>')
    3411          done = parser.close()
    3412
    3413          self.assertEquals("DONE", done)
    3414          self.assertEquals(["start-root", "start-sub", "end-sub", "start-sub",
    3415                             "data-this is an entity",
    3416                             "end-sub", "start-sub", "end-sub", "end-root"],
    3417                            events)
    3418
    3419 -    def test_parser_target_entity_unknown(self):
    3420          events = []
    3421          class Target(object):
    3422              def __init__(self):
    3423                  self._data = []
    3424              def _flush_data(self):
    3425                  if self._data:
    3426                      events.append("data-" + ''.join(self._data))
    3427                      del self._data[:]
    3428              def start(self, tag, attrib):
    3429                  self._flush_data()
    3430                  events.append("start-" + tag)
    3431              def end(self, tag):
    3432                  self._flush_data()
    3433                  events.append("end-" + tag)
    3434              def data(self, data):
    3435                  self._data.append(data)
    3436              def close(self):
    3437                  self._flush_data()
    3438                  return "DONE"
    3439
    3440          parser = self.etree.XMLParser(target=Target())
    3441
    3442          def feed():
    3443              parser.feed('<root><sub/><sub>some &ent;</sub><sub/></root>')
    3444              parser.close()
    3445
    3446          self.assertRaises(self.etree.ParseError, feed)
    3447
    3448 -    def test_treebuilder(self):
    3449          builder = self.etree.TreeBuilder()
    3450          el = builder.start("root", {'a':'A', 'b':'B'})
    3451          self.assertEquals("root", el.tag)
    3452          self.assertEquals({'a':'A', 'b':'B'}, el.attrib)
    3453          builder.data("ROOTTEXT")
    3454          el = builder.start("child", {'x':'X', 'y':'Y'})
    3455          self.assertEquals("child", el.tag)
    3456          self.assertEquals({'x':'X', 'y':'Y'}, el.attrib)
    3457          builder.data("CHILDTEXT")
    3458          el = builder.end("child")
    3459          self.assertEquals("child", el.tag)
    3460          self.assertEquals({'x':'X', 'y':'Y'}, el.attrib)
    3461          self.assertEquals("CHILDTEXT", el.text)
    3462          self.assertEquals(None, el.tail)
    3463          builder.data("CHILDTAIL")
    3464          root = builder.end("root")
    3465
    3466          self.assertEquals("root", root.tag)
    3467          self.assertEquals("ROOTTEXT", root.text)
    3468          self.assertEquals("CHILDTEXT", root[0].text)
    3469          self.assertEquals("CHILDTAIL", root[0].tail)
    3470
    3471 -    def test_treebuilder_target(self):
    3472          parser = self.etree.XMLParser(target=self.etree.TreeBuilder())
    3473          parser.feed('<root>ROOTTEXT<child>CHILDTEXT</child>CHILDTAIL</root>')
    3474          root = parser.close()
    3475
    3476          self.assertEquals("root", root.tag)
    3477          self.assertEquals("ROOTTEXT", root.text)
    3478          self.assertEquals("CHILDTEXT", root[0].text)
    3479          self.assertEquals("CHILDTAIL", root[0].tail)
    3480
    3481      # helper methods
    3482
    3483 -    def _writeElement(self, element, encoding='us-ascii'):
    3484          """Write out element for comparison.
    3485          """
    3486          data = self.etree.tostring(element, encoding=encoding)
    3487          if encoding != 'us-ascii':
    3488              data = data.decode(encoding)
    3489          return canonicalize(data)
    3490
    3491 -    def _writeElementFile(self, element, encoding='us-ascii'):
    3492          """Write out element for comparison, using real file.
    3493          """
    3494          ElementTree = self.etree.ElementTree
    3495          handle, filename = tempfile.mkstemp()
    3496          try:
    3497              f = open(filename, 'wb')
    3498              tree = ElementTree(element=element)
    3499              tree.write(f, encoding=encoding)
    3500              f.close()
    3501              f = open(filename, 'rb')
    3502              data = f.read()
    3503              f.close()
    3504          finally:
    3505              os.close(handle)
    3506              os.remove(filename)
    3507          if encoding != 'us-ascii':
    3508              data = data.decode(encoding)
    3509          return canonicalize(data)
    3510
    3511 -    def assertXML(self, expected, element, encoding='us-ascii'):
    3512          """Writes element out and checks whether it is expected.
    3513
    3514          Does this two ways; once using BytesIO, once using a real file.
    3515          """
    3516          self.assertEquals(expected, self._writeElement(element, encoding))
    3517          self.assertEquals(expected, self._writeElementFile(element, encoding))
    3518
    3519 -    def assertEncodingDeclaration(self, result, encoding):
    3520          "Checks if the result XML byte string specifies the encoding."
    3521          has_encoding = re.compile(r"<\?xml[^>]+ encoding=[\"']([^\"']+)[\"']").match
    3522          self.assert_(has_encoding(result))
    3523          result_encoding = has_encoding(result).group(1)
    3524          self.assertEquals(result_encoding.upper(), encoding.upper())
    3525
    3526 -    def _rootstring(self, tree):
    3527          return self.etree.tostring(tree.getroot()).replace(
    3528              _bytes(' '), _bytes('')).replace(_bytes('\n'), _bytes(''))
    3529
    3530 -    def _check_element_tree(self, tree):
    3531          self._check_element(tree.getroot())
    3532
    3533 -    def _check_element(self, element):
    3534          self.assert_(hasattr(element, 'tag'))
    3535          self.assert_(hasattr(element, 'attrib'))
    3536          self.assert_(hasattr(element, 'text'))
    3537          self.assert_(hasattr(element, 'tail'))
    3538          self._check_string(element.tag)
    3539          self._check_mapping(element.attrib)
    3540          if element.text != None:
    3541              self._check_string(element.text)
    3542          if element.tail != None:
    3543              self._check_string(element.tail)
    3544
    3545 -    def _check_string(self, string):
    3546          len(string)
    3547          for char in string:
    3548              self.assertEquals(1, len(char))
    3549          new_string = string + ""
    3550          new_string = string + " "
    3551          string[:0]
    3552
    3553 -    def _check_mapping(self, mapping):
    3554          len(mapping)
    3555          keys = mapping.keys()
    3556          values = mapping.values()
    3557          items = mapping.items()
    3558          for key in keys:
    3559              item = mapping[key]
    3560          mapping["key"] = "value"
    3561          self.assertEquals("value", mapping["key"])
    3562
    3563
    3564  if etree:
    3565 -    class ETreeTestCase(ETreeTestCaseBase):
    3566          etree = etree
    3567
    3568  if ElementTree:
    3569 -    class ElementTreeTestCase(ETreeTestCaseBase):
    3570          etree = ElementTree
    3571
    3572  if cElementTree:
    3573 -    class CElementTreeTestCase(ETreeTestCaseBase):
    3574          etree = cElementTree
    3575
    3576 -def test_suite():
    3577      suite = unittest.TestSuite()
    3578      if etree:
    3579          suite.addTests([unittest.makeSuite(ETreeTestCase)])
    3580      if ElementTree:
    3581          suite.addTests([unittest.makeSuite(ElementTreeTestCase)])
    3582      if cElementTree:
    3583          suite.addTests([unittest.makeSuite(CElementTreeTestCase)])
    3584      return suite
    3585
    3586  if __name__ == '__main__':
    3587      print('to test use test.py %s' % __file__)
    3588