1# -*- coding: utf-8 -*- 2importunittest,doctest 3 4# These tests check that error handling in the Pyrex code is 5# complete. 6# It is likely that if there are errors, instead of failing the code 7# will simply crash. 8 9importsys,gc,os.path10fromlxmlimportetree1112this_dir=os.path.dirname(__file__)13ifthis_dirnotinsys.path:14sys.path.insert(0,this_dir)# needed for Py31516fromcommon_importsimportHelperTestCase1718
23# attrib argument of Element() should be a dictionary, so if24# we pass a string we should get an error.25self.assertRaises(TypeError,self.etree.Element,'a','b')
31# test if cyclic reference can crash etree32Element=self.etree.Element3334# must disable tracing as it could change the refcounts35trace_func=sys.gettrace()36try:37sys.settrace(None)38gc.collect()3940count=sys.getrefcount(None)4142l=[Element('name'),Element('name')]43l.append(l)4445dell46gc.collect()4748self.assertEqual(sys.getrefcount(None),count)49finally:50sys.settrace(trace_func)
53broken_xml_name='test_broken.xml'54broken_xml_path=os.path.join(this_dir,broken_xml_name)55fail_msg='test_broken.xml should raise an etree.XMLSyntaxError'56try:57etree.parse(broken_xml_path)58exceptetree.XMLSyntaxErrorase:59# invariant60self.assertEqual(e.position,(e.lineno,e.offset+1),'position and lineno/offset out of sync')61# SyntaxError info derived from file & contents62self.assertTrue(e.filename.endswith(broken_xml_name),'filename must be preserved')63self.assertEqual(e.lineno,1)64self.assertEqual(e.offset,10)65exceptExceptionase:66self.fail('{0}, not {1}'.format(fail_msg,type(e)))67else:68self.fail('test_broken.xml should raise an etree.XMLSyntaxError')