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