1#!/usr/bin/python -u 2import sys, unittest 3 4import libxml2 5 6class TestCase(unittest.TestCase): 7 8 def runTest(self): 9 self.test1() 10 self.test2() 11 12 def setUp(self): 13 libxml2.debugMemory(1) 14 15 def tearDown(self): 16 libxml2.cleanupParser() 17 if libxml2.debugMemory(1) != 0: 18 libxml2.dumpMemory() 19 self.fail("Memory leak %d bytes" % (libxml2.debugMemory(1),)) 20 else: 21 print("OK") 22 23 def failUnlessXmlError(self,f,args,exc,domain,code,message,level,file,line): 24 """Run function f, with arguments args and expect an exception exc; 25 when the exception is raised, check the libxml2.lastError for 26 expected values.""" 27 # disable the default error handler 28 def noerr(ctx, str): 29 pass 30 # None is not acceptable as function. 31 libxml2.registerErrorHandler(noerr,None) 32 try: 33 f(*args) 34 except exc: 35 e = libxml2.lastError() 36 if e is None: 37 self.fail("lastError not set") 38 if 0: 39 print("domain = ",e.domain()) 40 print("code = ",e.code()) 41 print("message =",repr(e.message())) 42 print("level =",e.level()) 43 print("file =",e.file()) 44 print("line =",e.line()) 45 print() 46 self.assertEqual(domain,e.domain()) 47 self.assertEqual(code,e.code()) 48 self.assertEqual(message,e.message()) 49 self.assertEqual(level,e.level()) 50 self.assertEqual(file,e.file()) 51 self.assertEqual(line,e.line()) 52 else: 53 self.fail("exception %s should have been raised" % exc) 54 55 def test1(self): 56 """Test readFile with a file that does not exist""" 57 self.failUnlessXmlError(libxml2.readFile, 58 ("dummy.xml",None,0), 59 libxml2.treeError, 60 domain=libxml2.XML_FROM_IO, 61 code=libxml2.XML_IO_LOAD_ERROR, 62 message='failed to load external entity "dummy.xml"\n', 63 level=libxml2.XML_ERR_WARNING, 64 file=None, 65 line=0) 66 67 def test2(self): 68 """Test a well-formedness error: we get the last error only""" 69 s = "<x>\n<a>\n</x>" 70 self.failUnlessXmlError(libxml2.readMemory, 71 (s,len(s),"dummy.xml",None,0), 72 libxml2.treeError, 73 domain=libxml2.XML_FROM_PARSER, 74 code=libxml2.XML_ERR_TAG_NOT_FINISHED, 75 message='Premature end of data in tag x line 1\n', 76 level=libxml2.XML_ERR_FATAL, 77 file='dummy.xml', 78 line=3) 79 80if __name__ == "__main__": 81 test = TestCase() 82 test.setUp() 83 test.test1() 84 test.test2() 85 test.tearDown() 86