validRNG.py 1.9 KB

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