• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2#
3# this test exercise the XPath basic engine, parser, etc, and
4# allows to detect memory leaks
5#
6import sys
7import libxml2
8
9instance="""<?xml version="1.0"?>
10<tag xmlns:foo='urn:foo' xmlns:bar='urn:bar' xmlns:baz='urn:baz' />"""
11
12def namespaceDefs(node):
13    n = node.nsDefs()
14    while n:
15        yield n
16        n = n.next
17
18def checkNamespaceDefs(node, count):
19    nsList = list(namespaceDefs(node))
20    #print nsList
21    if len(nsList) != count :
22        raise Exception("Error: saw %d namespace declarations.  Expected %d" % (len(nsList), count))
23
24# Memory debug specific
25libxml2.debugMemory(1)
26
27# Remove single namespace
28doc = libxml2.parseDoc(instance)
29node = doc.getRootElement()
30checkNamespaceDefs(node, 3)
31ns = node.removeNsDef('urn:bar')
32checkNamespaceDefs(node, 2)
33ns.freeNsList()
34doc.freeDoc()
35
36# Remove all namespaces
37doc = libxml2.parseDoc(instance)
38node = doc.getRootElement()
39checkNamespaceDefs(node, 3)
40ns = node.removeNsDef(None)
41checkNamespaceDefs(node, 0)
42ns.freeNsList()
43doc.freeDoc()
44
45# Remove a namespace referred to by a child
46doc = libxml2.newDoc("1.0")
47root = doc.newChild(None, "root", None)
48namespace = root.newNs("http://example.com/sample", "s")
49child = root.newChild(namespace, "child", None)
50root.removeNsDef("http://example.com/sample")
51doc.reconciliateNs(root)
52namespace.freeNsList()
53doc.serialize() # This should not segfault
54doc.freeDoc()
55
56# Memory debug specific
57libxml2.cleanupParser()
58if libxml2.debugMemory(1) == 0:
59    print("OK")
60else:
61    print("Memory leak %d bytes" % (libxml2.debugMemory(1)))
62    libxml2.dumpMemory()
63