1#!/usr/bin/env python3 2import setup_test 3import libxml2 4import sys 5 6ARG = 'test string' 7 8class ErrorHandler: 9 10 def __init__(self): 11 self.errors = [] 12 13 def handler(self, msg, data): 14 if data != ARG: 15 raise Exception("Error handler did not receive correct argument") 16 self.errors.append(msg) 17 18# Memory debug specific 19libxml2.debugMemory(1) 20 21schema="""<?xml version="1.0" encoding="iso-8859-1"?> 22<schema xmlns = "http://www.w3.org/2001/XMLSchema"> 23 <element name = "Customer"> 24 <complexType> 25 <sequence> 26 <element name = "FirstName" type = "string" /> 27 <element name = "MiddleInitial" type = "string" /> 28 <element name = "LastName" type = "string" /> 29 </sequence> 30 <attribute name = "customerID" type = "integer" /> 31 </complexType> 32 </element> 33</schema>""" 34 35valid="""<?xml version="1.0" encoding="iso-8859-1"?> 36<Customer customerID = "24332"> 37 <FirstName>Raymond</FirstName> 38 <MiddleInitial>G</MiddleInitial> 39 <LastName>Bayliss</LastName> 40</Customer> 41""" 42 43invalid="""<?xml version="1.0" encoding="iso-8859-1"?> 44<Customer customerID = "24332"> 45 <MiddleInitial>G</MiddleInitial> 46 <LastName>Bayliss</LastName> 47</Customer> 48""" 49 50e = ErrorHandler() 51ctxt_parser = libxml2.schemaNewMemParserCtxt(schema, len(schema)) 52ctxt_schema = ctxt_parser.schemaParse() 53ctxt_valid = ctxt_schema.schemaNewValidCtxt() 54ctxt_valid.setValidityErrorHandler(e.handler, e.handler, ARG) 55 56# Test valid document 57doc = libxml2.parseDoc(valid) 58ret = doc.schemaValidateDoc(ctxt_valid) 59if ret != 0 or e.errors: 60 print("error doing schema validation") 61 sys.exit(1) 62doc.freeDoc() 63 64# Test invalid document 65doc = libxml2.parseDoc(invalid) 66ret = doc.schemaValidateDoc(ctxt_valid) 67if ret == 0 or not e.errors: 68 print("Error: document supposer to be schema invalid") 69 sys.exit(1) 70doc.freeDoc() 71 72del ctxt_parser 73del ctxt_schema 74del ctxt_valid 75libxml2.schemaCleanupTypes() 76 77# Memory debug specific 78libxml2.cleanupParser() 79if libxml2.debugMemory(1) == 0: 80 print("OK") 81else: 82 print("Memory leak %d bytes" % (libxml2.debugMemory(1))) 83 84