• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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" encoding="iso-8859-1"?>
21<schema xmlns = "http://www.w3.org/2001/XMLSchema">
22	<element name = "Customer">
23		<complexType>
24			<sequence>
25				<element name = "FirstName" type = "string" />
26				<element name = "MiddleInitial" type = "string" />
27				<element name = "LastName" type = "string" />
28			</sequence>
29			<attribute name = "customerID" type = "integer" />
30		</complexType>
31	</element>
32</schema>"""
33
34valid="""<?xml version="1.0" encoding="iso-8859-1"?>
35<Customer customerID = "24332">
36	<FirstName>Raymond</FirstName>
37	<MiddleInitial>G</MiddleInitial>
38	<LastName>Bayliss</LastName>
39</Customer>
40"""
41
42invalid="""<?xml version="1.0" encoding="iso-8859-1"?>
43<Customer customerID = "24332">
44	<MiddleInitial>G</MiddleInitial>
45	<LastName>Bayliss</LastName>
46</Customer>
47"""
48
49e = ErrorHandler()
50ctxt_parser = libxml2.schemaNewMemParserCtxt(schema, len(schema))
51ctxt_schema = ctxt_parser.schemaParse()
52ctxt_valid  = ctxt_schema.schemaNewValidCtxt()
53ctxt_valid.setValidityErrorHandler(e.handler, e.handler, ARG)
54
55# Test valid document
56doc = libxml2.parseDoc(valid)
57ret = doc.schemaValidateDoc(ctxt_valid)
58if ret != 0 or e.errors:
59    print("error doing schema validation")
60    sys.exit(1)
61doc.freeDoc()
62
63# Test invalid document
64doc = libxml2.parseDoc(invalid)
65ret = doc.schemaValidateDoc(ctxt_valid)
66if ret == 0 or not e.errors:
67    print("Error: document supposer to be schema invalid")
68    sys.exit(1)
69doc.freeDoc()
70
71del ctxt_parser
72del ctxt_schema
73del ctxt_valid
74libxml2.schemaCleanupTypes()
75
76# Memory debug specific
77libxml2.cleanupParser()
78if libxml2.debugMemory(1) == 0:
79    print("OK")
80else:
81    print("Memory leak %d bytes" % (libxml2.debugMemory(1)))
82    libxml2.dumpMemory()
83
84