validSchemas.py 2.0 KB

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