xpathret.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/python -u
  2. import sys
  3. import libxml2
  4. #memory debug specific
  5. libxml2.debugMemory(1)
  6. #
  7. # A document hosting the nodes returned from the extension function
  8. #
  9. mydoc = libxml2.newDoc("1.0")
  10. def foo(ctx, str):
  11. global mydoc
  12. #
  13. # test returning a node set works as expected
  14. #
  15. parent = mydoc.newDocNode(None, 'p', None)
  16. mydoc.addChild(parent)
  17. node = mydoc.newDocText(str)
  18. parent.addChild(node)
  19. return [parent]
  20. doc = libxml2.parseFile("tst.xml")
  21. ctxt = doc.xpathNewContext()
  22. libxml2.registerXPathFunction(ctxt._o, "foo", None, foo)
  23. res = ctxt.xpathEval("foo('hello')")
  24. if type(res) != type([]):
  25. print "Failed to return a nodeset"
  26. sys.exit(1)
  27. if len(res) != 1:
  28. print "Unexpected nodeset size"
  29. sys.exit(1)
  30. node = res[0]
  31. if node.name != 'p':
  32. print "Unexpected nodeset element result"
  33. sys.exit(1)
  34. node = node.children
  35. if node.type != 'text':
  36. print "Unexpected nodeset element children type"
  37. sys.exit(1)
  38. if node.content != 'hello':
  39. print "Unexpected nodeset element children content"
  40. sys.exit(1)
  41. doc.freeDoc()
  42. mydoc.freeDoc()
  43. ctxt.xpathFreeContext()
  44. #memory debug specific
  45. libxml2.cleanupParser()
  46. if libxml2.debugMemory(1) == 0:
  47. print "OK"
  48. else:
  49. print "Memory leak %d bytes" % (libxml2.debugMemory(1))
  50. libxml2.dumpMemory()