lxml.tests.test_io

Package lxml :: Package tests :: Module test_io |
[frames] | no frames]

# Source Code for Module lxml.tests.test_io

      1  # -*- coding: utf-8 -*-
      2
      3  """
      4  IO test cases that apply to both etree and ElementTree
      5  """
      6
      7  import unittest
      8  import tempfile, gzip, os, gc, shutil
      9
     10  from common_imports import etree, ElementTree, fileInTestDir
     11  from common_imports import SillyFileLike, LargeFileLike, HelperTestCase
     12
     13 -class IOTestCaseBase(HelperTestCase):
     14      """(c)ElementTree compatibility for IO functions/methods
     15      """
     16      etree = None
     17
     18 -    def setUp(self):
     19          """Setting up a minimal tree
     20          """
     21          self.root = self.etree.Element('a')
     22          self.root_str = self.etree.tostring(self.root)
     23          self.tree = self.etree.ElementTree(self.root)
     24          self._temp_dir = tempfile.mkdtemp()
     25
     26 -    def tearDown(self):
     27          gc.collect()
     28          shutil.rmtree(self._temp_dir)
     29
     30 -    def getTestFilePath(self, name):
     31          return os.path.join(self._temp_dir, name)
     32
     33 -    def buildNodes(self, element, children, depth):
     34          Element = self.etree.Element
     35
     36          if depth == 0:
     37              return
     38          for i in range(children):
     39              new_element = Element('element_%s_%s' % (depth, i))
     40              self.buildNodes(new_element, children, depth - 1)
     41              element.append(new_element)
     42
     43 -    def test_tree_io(self):
     44          Element = self.etree.Element
     45          ElementTree = self.etree.ElementTree
     46
     47          element = Element('top')
     48          tree = ElementTree(element)
     49          self.buildNodes(element, 10, 3)
     50          f = open(self.getTestFilePath('testdump.xml'), 'w')
     51          tree.write(f, encoding='UTF-8')
     52          f.close()
     53          f = open(self.getTestFilePath('testdump.xml'), 'r')
     54          tree = ElementTree(file=f)
     55          f.close()
     56          f = open(self.getTestFilePath('testdump2.xml'), 'w')
     57          tree.write(f, encoding='UTF-8')
     58          f.close()
     59          f = open(self.getTestFilePath('testdump.xml'), 'r')
     60          data1 = f.read()
     61          f.close()
     62          f = open(self.getTestFilePath('testdump2.xml'), 'r')
     63          data2 = f.read()
     64          f.close()
     65          self.assertEquals(data1, data2)
     66
     67 -    def test_write_filename(self):
     68          # (c)ElementTree  supports filename strings as write argument
     69
     70          handle, filename = tempfile.mkstemp(suffix=".xml")
     71          self.tree.write(filename)
     72          try:
     73              self.assertEqual(open(filename).read().replace('\n', ''),
     74                               self.root_str)
     75          finally:
     76              os.close(handle)
     77              os.remove(filename)
     78
     79 -    def test_module_parse_gzipobject(self):
     80          # (c)ElementTree supports gzip instance as parse argument
     81          handle, filename = tempfile.mkstemp(suffix=".xml.gz")
     82          f = gzip.open(filename, 'wb')
     83          f.write(self.root_str)
     84          f.close()
     85          try:
     86              f_gz = gzip.open(filename, 'r')
     87              tree = self.etree.parse(f_gz)
     88              f_gz.close()
     89              self.assertEqual(self.etree.tostring(tree.getroot()), self.root_str)
     90          finally:
     91              os.close(handle)
     92              os.remove(filename)
     93
     94 -    def test_class_parse_filename(self):
     95          # (c)ElementTree class ElementTree has a 'parse' method that returns
     96          # the root of the tree
     97
     98          # parse from filename
     99
    100          handle, filename = tempfile.mkstemp(suffix=".xml")
    101          open(filename, 'wb').write(self.root_str)
    102          try:
    103              tree = self.etree.ElementTree()
    104              root = tree.parse(filename)
    105              self.assertEqual(self.etree.tostring(root), self.root_str)
    106          finally:
    107              os.close(handle)
    108              os.remove(filename)
    109
    110 -    def test_class_parse_filename_remove_previous(self):
    111          handle, filename = tempfile.mkstemp(suffix=".xml")
    112          open(filename, 'wb').write(self.root_str)
    113          try:
    114              tree = self.etree.ElementTree()
    115              root = tree.parse(filename)
    116              # and now do it again; previous content should still be there
    117              root2 = tree.parse(filename)
    118              self.assertEquals('a', root.tag)
    119              self.assertEquals('a', root2.tag)
    120              # now remove all references to root2, and parse again
    121              del root2
    122              root3 = tree.parse(filename)
    123              self.assertEquals('a', root.tag)
    124              self.assertEquals('a', root3.tag)
    125              # root2's memory should've been freed here
    126              # XXX how to check?
    127          finally:
    128              os.close(handle)
    129              os.remove(filename)
    130
    131 -    def test_class_parse_fileobject(self):
    132          # (c)ElementTree class ElementTree has a 'parse' method that returns
    133          # the root of the tree
    134
    135          # parse from file object
    136
    137          handle, filename = tempfile.mkstemp(suffix=".xml")
    138          os.write(handle, self.root_str)
    139          try:
    140              f = open(filename, 'r')
    141              tree = self.etree.ElementTree()
    142              root = tree.parse(f)
    143              f.close()
    144              self.assertEqual(self.etree.tostring(root), self.root_str)
    145          finally:
    146              os.close(handle)
    147              os.remove(filename)
    148
    149 -    def test_class_parse_unamed_fileobject(self):
    150          # (c)ElementTree class ElementTree has a 'parse' method that returns
    151          # the root of the tree
    152
    153          # parse from unamed file object
    154          f = SillyFileLike()
    155          root = self.etree.ElementTree().parse(f)
    156          self.assert_(root.tag.endswith('foo'))
    157
    158 -    def test_module_parse_large_fileobject(self):
    159          # parse from unamed file object
    160          f = LargeFileLike()
    161          tree = self.etree.parse(f)
    162          root = tree.getroot()
    163          self.assert_(root.tag.endswith('root'))
    164
    165 -    def test_module_parse_fileobject_error(self):
    166          class LocalError(Exception):
    167              pass
    168          class TestFile:
    169              def read(*args):
    170                  raise LocalError
    171          f = TestFile()
    172          self.assertRaises(LocalError, self.etree.parse, f)
    173
    174 -    def test_module_parse_fileobject_late_error(self):
    175          class LocalError(Exception):
    176              pass
    177          class TestFile:
    178              data = '<root>test</'
    179              next_char = iter(data).next
    180              counter = 0
    181              def read(self, amount=None):
    182                  if amount is None:
    183                      while True:
    184                          self.read(1)
    185                  else:
    186                      try:
    187                          self.counter += 1
    188                          return self.next_char()
    189                      except StopIteration:
    190                          raise LocalError
    191          f = TestFile()
    192          self.assertRaises(LocalError, self.etree.parse, f)
    193          self.assertEquals(f.counter, len(f.data)+1)
    194
    195 -    def test_module_parse_fileobject_type_error(self):
    196          class TestFile:
    197              def read(*args):
    198                  return 1
    199          f = TestFile()
    200          self.assertRaises(TypeError, self.etree.parse, f)
    201
    202
    203 -class ETreeIOTestCase(IOTestCaseBase):
    204      etree = etree
    205
    206  if ElementTree:
    207 -    class ElementTreeIOTestCase(IOTestCaseBase):
    208          etree = ElementTree
    209
    210 -def test_suite():
    211      suite = unittest.TestSuite()
    212      suite.addTests([unittest.makeSuite(ETreeIOTestCase)])
    213      if ElementTree:
    214          suite.addTests([unittest.makeSuite(ElementTreeIOTestCase)])
    215      return suite
    216
    217  if __name__ == '__main__':
    218      print 'to test use test.py %s' % __file__
    219