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

Source Code for Module lxml.tests.test_errors

 1  # -*- coding: utf-8 -*- 
 2  from __future__ import absolute_import 
 3   
 4  import unittest 
 5   
 6  # These tests check that error handling in the Pyrex code is 
 7  # complete. 
 8  # It is likely that if there are errors, instead of failing the code 
 9  # will simply crash. 
10   
11  import sys, gc, os.path 
12  from lxml import etree 
13   
14  from .common_imports import HelperTestCase 
15   
16   
17 -class ErrorTestCase(HelperTestCase):
18 etree = etree 19
20 - def test_bad_element(self):
21 # attrib argument of Element() should be a dictionary, so if 22 # we pass a string we should get an error. 23 self.assertRaises(TypeError, self.etree.Element, 'a', 'b')
24
25 - def test_empty_parse(self):
26 self.assertRaises(etree.XMLSyntaxError, etree.fromstring, '')
27
29 # test if cyclic reference can crash etree 30 Element = self.etree.Element 31 getrefcount = sys.getrefcount 32 33 # must disable tracing as it could change the refcounts 34 trace_func = sys.gettrace() 35 try: 36 sys.settrace(None) 37 gc.collect() 38 39 count = getrefcount(None) 40 41 l = [Element('name'), Element('name')] 42 l.append(l) 43 44 del l 45 gc.collect() 46 count = getrefcount(None) - count 47 48 self.assertEqual(count, 0) 49 finally: 50 sys.settrace(trace_func)
51
53 broken_xml_name = 'test_broken.xml' 54 broken_xml_path = os.path.join(os.path.dirname(__file__), broken_xml_name) 55 fail_msg = 'test_broken.xml should raise an etree.XMLSyntaxError' 56 try: 57 etree.parse(broken_xml_path) 58 except etree.XMLSyntaxError as e: 59 # invariant 60 self.assertEqual(e.position, (e.lineno, e.offset + 1), 'position and lineno/offset out of sync') 61 # SyntaxError info derived from file & contents 62 self.assertTrue(e.filename.endswith(broken_xml_name), 'filename must be preserved') 63 self.assertEqual(e.lineno, 1) 64 self.assertEqual(e.offset, 10) 65 except Exception as e: 66 self.fail('{0}, not {1}'.format(fail_msg, type(e))) 67 else: 68 self.fail('test_broken.xml should raise an etree.XMLSyntaxError')
69 70
71 -def test_suite():
72 suite = unittest.TestSuite() 73 suite.addTests([unittest.makeSuite(ErrorTestCase)]) 74 return suite
75 76 if __name__ == '__main__': 77 print('to test use test.py %s' % __file__) 78