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