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