tstLastError.py 2.8 KB

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