Package lxml :: Package tests :: Module test_elementtree |
[hide private]
[frames] | no frames]

# Source Code for Module lxml.tests.test_elementtree

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