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 libxml2.registerErrorHandler(None,None) 29 try: 30 f(*args) 31 except exc: 32 e = libxml2.lastError() 33 if e is None: 34 self.fail("lastError not set") 35 if 0: 36 print("domain = ",e.domain()) 37 print("code = ",e.code()) 38 print("message =",repr(e.message())) 39 print("level =",e.level()) 40 print("file =",e.file()) 41 print("line =",e.line()) 42 print() 43 self.failUnlessEqual(domain,e.domain()) 44 self.failUnlessEqual(code,e.code()) 45 self.failUnlessEqual(message,e.message()) 46 self.failUnlessEqual(level,e.level()) 47 self.failUnlessEqual(file,e.file()) 48 self.failUnlessEqual(line,e.line()) 49 else: 50 self.fail("exception %s should have been raised" % exc) 51 52 def test1(self): 53 """Test readFile with a file that does not exist""" 54 self.failUnlessXmlError(libxml2.readFile, 55 ("dummy.xml",None,0), 56 libxml2.treeError, 57 domain=libxml2.XML_FROM_IO, 58 code=libxml2.XML_IO_LOAD_ERROR, 59 message='failed to load external entity "dummy.xml"\n', 60 level=libxml2.XML_ERR_WARNING, 61 file=None, 62 line=0) 63 64 def test2(self): 65 """Test a well-formedness error: we get the last error only""" 66 s = "<x>\n<a>\n</x>" 67 self.failUnlessXmlError(libxml2.readMemory, 68 (s,len(s),"dummy.xml",None,0), 69 libxml2.treeError, 70 domain=libxml2.XML_FROM_PARSER, 71 code=libxml2.XML_ERR_TAG_NOT_FINISHED, 72 message='Premature end of data in tag x line 1\n', 73 level=libxml2.XML_ERR_FATAL, 74 file='dummy.xml', 75 line=3) 76 77if __name__ == "__main__": 78 test = TestCase() 79 test.setUp() 80 test.test1() 81 test.test2() 82 test.tearDown() 83