tstxpath.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/python -u
  2. import sys
  3. import libxml2
  4. #memory debug specific
  5. libxml2.debugMemory(1)
  6. called = ""
  7. def foo(ctx, x):
  8. global called
  9. #
  10. # test that access to the XPath evaluation contexts
  11. #
  12. pctxt = libxml2.xpathParserContext(_obj=ctx)
  13. ctxt = pctxt.context()
  14. called = ctxt.function()
  15. return x + 1
  16. def bar(ctxt, x):
  17. return "%d" % (x + 2)
  18. doc = libxml2.parseFile("tst.xml")
  19. ctxt = doc.xpathNewContext()
  20. res = ctxt.xpathEval("//*")
  21. if len(res) != 2:
  22. print "xpath query: wrong node set size"
  23. sys.exit(1)
  24. if res[0].name != "doc" or res[1].name != "foo":
  25. print "xpath query: wrong node set value"
  26. sys.exit(1)
  27. libxml2.registerXPathFunction(ctxt._o, "foo", None, foo)
  28. libxml2.registerXPathFunction(ctxt._o, "bar", None, bar)
  29. i = 10000
  30. while i > 0:
  31. res = ctxt.xpathEval("foo(1)")
  32. if res != 2:
  33. print "xpath extension failure"
  34. sys.exit(1)
  35. i = i - 1
  36. i = 10000
  37. while i > 0:
  38. res = ctxt.xpathEval("bar(1)")
  39. if res != "3":
  40. print "xpath extension failure got %s expecting '3'"
  41. sys.exit(1)
  42. i = i - 1
  43. doc.freeDoc()
  44. ctxt.xpathFreeContext()
  45. if called != "foo":
  46. print "xpath function: failed to access the context"
  47. print "xpath function: %s" % (called)
  48. sys.exit(1)
  49. #memory debug specific
  50. libxml2.cleanupParser()
  51. if libxml2.debugMemory(1) == 0:
  52. print "OK"
  53. else:
  54. print "Memory leak %d bytes" % (libxml2.debugMemory(1))
  55. libxml2.dumpMemory()