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