lxml.tests.test_incremental_xmlfile

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

# Source Code for Module lxml.tests.test_incremental_xmlfile

      1  # -*- coding: utf-8 -*-
      2
      3  """
      4  Tests for the incremental XML serialisation API.
      5
      6  Tests require Python 2.5 or later.
      7  """
      8
      9  from __future__ import with_statement
     10
     11  import unittest
     12  import tempfile, os, sys
     13
     14  this_dir = os.path.dirname(__file__)
     15  if this_dir not in sys.path:
     16      sys.path.insert(0, this_dir) # needed for Py3
     17
     18  from common_imports import etree, BytesIO
     19  from common_imports import HelperTestCase
     20
     21 -class _XmlFileTestCaseBase(HelperTestCase):
     22      _file = None  # to be set by specific subtypes below
     23
     24 -    def test_element(self):
     25          with etree.xmlfile(self._file) as xf:
     26              with xf.element('test'):
     27                  pass
     28          self.assertXml('<test></test>')
     29
     30 -    def test_element_write_text(self):
     31          with etree.xmlfile(self._file) as xf:
     32              with xf.element('test'):
     33                  xf.write('toast')
     34          self.assertXml('<test>toast</test>')
     35
     36 -    def test_element_nested(self):
     37          with etree.xmlfile(self._file) as xf:
     38              with xf.element('test'):
     39                  with xf.element('toast'):
     40                      with xf.element('taste'):
     41                          xf.write('conTent')
     42          self.assertXml('<test><toast><taste>conTent</taste></toast></test>')
     43
     44 -    def test_element_nested_with_text(self):
     45          with etree.xmlfile(self._file) as xf:
     46              with xf.element('test'):
     47                  xf.write('con')
     48                  with xf.element('toast'):
     49                      xf.write('tent')
     50                      with xf.element('taste'):
     51                          xf.write('inside')
     52                      xf.write('tnet')
     53                  xf.write('noc')
     54          self.assertXml('<test>con<toast>tent<taste>inside</taste>'
     55                         'tnet</toast>noc</test>')
     56
     57 -    def test_write_Element(self):
     58          with etree.xmlfile(self._file) as xf:
     59              xf.write(etree.Element('test'))
     60          self.assertXml('<test/>')
     61
     62 -    def test_write_Element_repeatedly(self):
     63          element = etree.Element('test')
     64          with etree.xmlfile(self._file) as xf:
     65              with xf.element('test'):
     66                  for i in range(100):
     67                      xf.write(element)
     68
     69          tree = self._parse_file()
     70          self.assertTrue(tree is not None)
     71          self.assertEqual(100, len(tree.getroot()))
     72          self.assertEqual(set(['test']), set(el.tag for el in tree.getroot()))
     73
     74 -    def test_namespace_nsmap(self):
     75          with etree.xmlfile(self._file) as xf:
     76              with xf.element('{nsURI}test', nsmap={'x': 'nsURI'}):
     77                  pass
     78          self.assertXml('<x:test xmlns:x="nsURI"></x:test>')
     79
     80 -    def test_namespace_nested_nsmap(self):
     81          with etree.xmlfile(self._file) as xf:
     82              with xf.element('test', nsmap={'x': 'nsURI'}):
     83                  with xf.element('{nsURI}toast'):
     84                      pass
     85          self.assertXml('<test xmlns:x="nsURI"><x:toast></x:toast></test>')
     86
     87 -    def test_anonymous_namespace(self):
     88          with etree.xmlfile(self._file) as xf:
     89              with xf.element('{nsURI}test'):
     90                  pass
     91          self.assertXml('<ns0:test xmlns:ns0="nsURI"></ns0:test>')
     92
     93 -    def test_namespace_nested_anonymous(self):
     94          with etree.xmlfile(self._file) as xf:
     95              with xf.element('test'):
     96                  with xf.element('{nsURI}toast'):
     97                      pass
     98          self.assertXml('<test><ns0:toast xmlns:ns0="nsURI"></ns0:toast></test>')
     99
    100 -    def test_default_namespace(self):
    101          with etree.xmlfile(self._file) as xf:
    102              with xf.element('{nsURI}test', nsmap={None: 'nsURI'}):
    103                  pass
    104          self.assertXml('<test xmlns="nsURI"></test>')
    105
    106 -    def test_nested_default_namespace(self):
    107          with etree.xmlfile(self._file) as xf:
    108              with xf.element('{nsURI}test', nsmap={None: 'nsURI'}):
    109                  with xf.element('{nsURI}toast'):
    110                      pass
    111          self.assertXml('<test xmlns="nsURI"><toast></toast></test>')
    112
    113 -    def test_pi(self):
    114          with etree.xmlfile(self._file) as xf:
    115              xf.write(etree.ProcessingInstruction('pypi'))
    116              with xf.element('test'):
    117                  pass
    118          self.assertXml('<?pypi ?><test></test>')
    119
    120 -    def test_comment(self):
    121          with etree.xmlfile(self._file) as xf:
    122              xf.write(etree.Comment('a comment'))
    123              with xf.element('test'):
    124                  pass
    125          self.assertXml('<!--a comment--><test></test>')
    126
    127 -    def test_attribute(self):
    128          with etree.xmlfile(self._file) as xf:
    129              with xf.element('test', attrib={'k': 'v'}):
    130                  pass
    131          self.assertXml('<test k="v"></test>')
    132
    133 -    def test_escaping(self):
    134          with etree.xmlfile(self._file) as xf:
    135              with xf.element('test'):
    136                  xf.write('Comments: <!-- text -->\n')
    137                  xf.write('Entities: &amp;')
    138          self.assertXml(
    139              '<test>Comments: &lt;!-- text --&gt;\nEntities: &amp;amp;</test>')
    140
    141 -    def test_encoding(self):
    142          with etree.xmlfile(self._file, encoding='utf16') as xf:
    143              with xf.element('test'):
    144                  xf.write('toast')
    145          self.assertXml('<test>toast</test>', encoding='utf16')
    146
    147 -    def test_failure_preceding_text(self):
    148          try:
    149              with etree.xmlfile(self._file) as xf:
    150                  xf.write('toast')
    151          except etree.LxmlSyntaxError:
    152              self.assertTrue(True)
    153          else:
    154              self.assertTrue(False)
    155
    156 -    def test_failure_trailing_text(self):
    157          with etree.xmlfile(self._file) as xf:
    158              with xf.element('test'):
    159                  pass
    160              try:
    161                  xf.write('toast')
    162              except etree.LxmlSyntaxError:
    163                  self.assertTrue(True)
    164              else:
    165                  self.assertTrue(False)
    166
    167 -    def test_failure_trailing_Element(self):
    168          with etree.xmlfile(self._file) as xf:
    169              with xf.element('test'):
    170                  pass
    171              try:
    172                  xf.write(etree.Element('test'))
    173              except etree.LxmlSyntaxError:
    174                  self.assertTrue(True)
    175              else:
    176                  self.assertTrue(False)
    177
    178 -    def test_closing_out_of_order_in_error_case(self):
    179          cm_exit = None
    180          try:
    181              with etree.xmlfile(self._file) as xf:
    182                  x = xf.element('test')
    183                  cm_exit = x.__exit__
    184                  x.__enter__()
    185                  raise ValueError('123')
    186          except ValueError:
    187              self.assertTrue(cm_exit)
    188              try:
    189                  cm_exit(ValueError, ValueError("huhu"), None)
    190              except etree.LxmlSyntaxError:
    191                  self.assertTrue(True)
    192              else:
    193                  self.assertTrue(False)
    194          else:
    195              self.assertTrue(False)
    196
    197 -    def _read_file(self):
    198          self._file.seek(0)
    199          return self._file.read()
    200
    201 -    def _parse_file(self):
    202          self._file.seek(0)
    203          return etree.parse(self._file)
    204
    205 -    def tearDown(self):
    206          self._file.close()
    207
    208 -    def assertXml(self, expected, encoding='utf8'):
    209          self.assertEqual(self._read_file().decode(encoding), expected)
    210
    211
    212 -class BytesIOXmlFileTestCase(_XmlFileTestCaseBase):
    213 -    def setUp(self):
    214          self._file = BytesIO()
    215
    216 -class TempXmlFileTestCase(_XmlFileTestCaseBase):
    217 -    def setUp(self):
    218          self._file = tempfile.NamedTemporaryFile()
    219
    220 -class SimpleFileLikeXmlFileTestCase(_XmlFileTestCaseBase):
    221 -    class SimpleFileLike(object):
    222 -        def __init__(self, target):
    223              self._target = target
    224              self.write = target.write
    225              self.close = target.close
    226
    227 -    def setUp(self):
    228          self._target = BytesIO()
    229          self._file = self.SimpleFileLike(self._target)
    230
    231 -    def _read_file(self):
    232          return self._target.getvalue()
    233
    234 -    def _parse_file(self):
    235          self._target.seek(0)
    236          return etree.parse(self._target)
    237
    238
    239 -def test_suite():
    240      suite = unittest.TestSuite()
    241      suite.addTests([unittest.makeSuite(BytesIOXmlFileTestCase),
    242                      unittest.makeSuite(TempXmlFileTestCase),
    243                      unittest.makeSuite(SimpleFileLikeXmlFileTestCase),
    244                      ])
    245      return suite
    246
    247  if __name__ == '__main__':
    248      print('to test use test.py %s' % __file__)
    249