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