validDTD.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #!/usr/bin/python -u
  2. import libxml2
  3. import sys
  4. ARG = 'test string'
  5. class ErrorHandler:
  6. def __init__(self):
  7. self.errors = []
  8. def handler(self, msg, data):
  9. if data != ARG:
  10. raise Exception, "Error handler did not receive correct argument"
  11. self.errors.append(msg)
  12. # Memory debug specific
  13. libxml2.debugMemory(1)
  14. dtd="""<!ELEMENT foo EMPTY>"""
  15. valid="""<?xml version="1.0"?>
  16. <foo></foo>"""
  17. invalid="""<?xml version="1.0"?>
  18. <foo><bar/></foo>"""
  19. dtd = libxml2.parseDTD(None, 'test.dtd')
  20. ctxt = libxml2.newValidCtxt()
  21. e = ErrorHandler()
  22. ctxt.setValidityErrorHandler(e.handler, e.handler, ARG)
  23. # Test valid document
  24. doc = libxml2.parseDoc(valid)
  25. ret = doc.validateDtd(ctxt, dtd)
  26. if ret != 1 or e.errors:
  27. print "error doing DTD validation"
  28. sys.exit(1)
  29. doc.freeDoc()
  30. # Test invalid document
  31. doc = libxml2.parseDoc(invalid)
  32. ret = doc.validateDtd(ctxt, dtd)
  33. if ret != 0 or not e.errors:
  34. print "Error: document supposed to be invalid"
  35. doc.freeDoc()
  36. dtd.freeDtd()
  37. del dtd
  38. del ctxt
  39. # Memory debug specific
  40. libxml2.cleanupParser()
  41. if libxml2.debugMemory(1) == 0:
  42. print "OK"
  43. else:
  44. print "Memory leak %d bytes" % (libxml2.debugMemory(1))
  45. libxml2.dumpMemory()