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# Memory debug specific 18libxml2.debugMemory(1) 19 20schema="""<?xml version="1.0"?> 21<element name="foo" 22 xmlns="http://relaxng.org/ns/structure/1.0" 23 xmlns:a="http://relaxng.org/ns/annotation/1.0" 24 xmlns:ex1="http://www.example.com/n1" 25 xmlns:ex2="http://www.example.com/n2"> 26 <a:documentation>A foo element.</a:documentation> 27 <element name="ex1:bar1"> 28 <empty/> 29 </element> 30 <element name="ex2:bar2"> 31 <empty/> 32 </element> 33</element> 34""" 35 36valid="""<?xml version="1.0"?> 37<foo><pre1:bar1 xmlns:pre1="http://www.example.com/n1"/><pre2:bar2 xmlns:pre2="http://www.example.com/n2"/></foo>""" 38 39invalid="""<?xml version="1.0"?> 40<foo><pre1:bar1 xmlns:pre1="http://www.example.com/n1">bad</pre1:bar1><pre2:bar2 xmlns:pre2="http://www.example.com/n2"/></foo>""" 41 42rngp = libxml2.relaxNGNewMemParserCtxt(schema, len(schema)) 43rngs = rngp.relaxNGParse() 44ctxt = rngs.relaxNGNewValidCtxt() 45e = ErrorHandler() 46ctxt.setValidityErrorHandler(e.handler, e.handler, ARG) 47 48# Test valid document 49doc = libxml2.parseDoc(valid) 50ret = doc.relaxNGValidateDoc(ctxt) 51if ret != 0 or e.errors: 52 print("error doing RelaxNG validation") 53 sys.exit(1) 54doc.freeDoc() 55 56# Test invalid document 57doc = libxml2.parseDoc(invalid) 58ret = doc.relaxNGValidateDoc(ctxt) 59if ret == 0 or not e.errors: 60 print("Error: document supposed to be RelaxNG invalid") 61 sys.exit(1) 62doc.freeDoc() 63 64del rngp 65del rngs 66del ctxt 67libxml2.relaxNGCleanupTypes() 68 69# Memory debug specific 70libxml2.cleanupParser() 71if libxml2.debugMemory(1) == 0: 72 print("OK") 73else: 74 print("Memory leak %d bytes" % (libxml2.debugMemory(1))) 75 libxml2.dumpMemory() 76 77