nsdel.py 1.5 KB

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