| 1 |
#!/usr/bin/env python3 |
| 2 |
import setup_test |
| 3 |
import libxml2 |
| 4 |
import sys |
| 5 |
|
| 6 |
ARG = 'test string' |
| 7 |
|
| 8 |
class 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 |
| 19 |
libxml2.debugMemory(1) |
| 20 |
|
| 21 |
schema="""<?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 |
|
| 35 |
valid="""<?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 |
|
| 43 |
invalid="""<?xml version="1.0" encoding="iso-8859-1"?> |
| 44 |
<Customer customerID = "24332"> |
| 45 |
<MiddleInitial>G</MiddleInitial> |
| 46 |
<LastName>Bayliss</LastName> |
| 47 |
</Customer> |
| 48 |
""" |
| 49 |
|
| 50 |
e = ErrorHandler() |
| 51 |
ctxt_parser = libxml2.schemaNewMemParserCtxt(schema, len(schema)) |
| 52 |
ctxt_schema = ctxt_parser.schemaParse() |
| 53 |
ctxt_valid = ctxt_schema.schemaNewValidCtxt() |
| 54 |
ctxt_valid.setValidityErrorHandler(e.handler, e.handler, ARG) |
| 55 |
|
| 56 |
# Test valid document |
| 57 |
doc = libxml2.parseDoc(valid) |
| 58 |
ret = doc.schemaValidateDoc(ctxt_valid) |
| 59 |
if ret != 0 or e.errors: |
| 60 |
print("error doing schema validation") |
| 61 |
sys.exit(1) |
| 62 |
doc.freeDoc() |
| 63 |
|
| 64 |
# Test invalid document |
| 65 |
doc = libxml2.parseDoc(invalid) |
| 66 |
ret = doc.schemaValidateDoc(ctxt_valid) |
| 67 |
if ret == 0 or not e.errors: |
| 68 |
print("Error: document supposer to be schema invalid") |
| 69 |
sys.exit(1) |
| 70 |
doc.freeDoc() |
| 71 |
|
| 72 |
del ctxt_parser |
| 73 |
del ctxt_schema |
| 74 |
del ctxt_valid |
| 75 |
libxml2.schemaCleanupTypes() |
| 76 |
|
| 77 |
# Memory debug specific |
| 78 |
libxml2.cleanupParser() |
| 79 |
if libxml2.debugMemory(1) == 0: |
| 80 |
print("OK") |
| 81 |
else: |
| 82 |
print("Memory leak %d bytes" % (libxml2.debugMemory(1))) |
| 83 |
|