1 #!/usr/bin/env python 2 3 """ 4 A test of macros. This file must be compiled using libxml2macro.py. It may then 5 be imported normally in Python, but if run then the compiled module should be 6 invoked directly - ie. as macrotest.pyc. 7 """ 8 9 import libxml2macro as x2_ 10 import xml.dom 11 12 class Container: 13 pass 14 15 doc = """<?xml version="1.0"?> 16 <doc> 17 <element attr="value"> 18 <subelement/> 19 </element> 20 </doc> 21 """ 22 23 def find_root(x2_d): 24 x2_root = None 25 26 # Property access should be transformed. 27 28 for x2_n in x2_d.childNodes: 29 if x2_n.nodeType == xml.dom.Node.ELEMENT_NODE: 30 x2_root = x2_n 31 break 32 33 return x2_root 34 35 def test(): 36 global doc 37 38 # Assignment should not be transformed. 39 40 x2_d = parseString(doc) 41 return process(x2_d) 42 43 def test_file(filename): 44 45 # Assignment should not be transformed. 46 47 x2_d = parseFile(filename) 48 return process(x2_d) 49 50 def process(x2_d): 51 52 # Not even within containers, and not special names alone. 53 54 c = Container() 55 c.x2_d = x2_d 56 57 # Find the root element. 58 59 x2_root = find_root(x2_d) 60 c.x2_root = x2_root 61 62 # Create new attributes. 63 # Method access should be transformed. 64 65 x2_root.setAttributeNS("ns", "xxx:yyy", "zzz") 66 c.x2_root.setAttributeNS("ns", "XXX:YYY", "ZZZ") 67 68 # Create new elements. 69 # Method access should be transformed. 70 71 x2_new = x2_d.createElementNS("ns2", "ppp:qqq") 72 x2_root.appendChild(x2_new) 73 x2_new2 = c.x2_d.createElementNS("ns2", "PPP:QQQ") 74 c.x2_root.appendChild(x2_new2) 75 76 # Create new elements using ownerDocument. 77 # Chaining properties is not 78 79 x2_new3 = x2_new.ownerDocument.createElement("fff") 80 x2_new.appendChild(x2_new3) 81 x2_new4 = x2_new2.ownerDocument.createElement("FFF") 82 x2_new2.appendChild(x2_new4) 83 84 return x2_d 85 86 def test_import(x2_d): 87 88 # Change the prefix. 89 90 import libxml2macro as node_ 91 node_d = x2_d 92 93 node_root = find_root(node_d) 94 95 # Create a new document. 96 97 node_d2 = createDocument("nsD", "newdoc", None) 98 node_root2 = find_root(node_d2) 99 100 # Attempt to import nodes from the original document. 101 102 node_imported = node_d2.importNode(node_root, 1) 103 node_d2.replaceChild(node_imported, node_root2) 104 105 return node_d, node_d2 106 107 if __name__ == "__main__": 108 import sys 109 if len(sys.argv) > 1: 110 print "Running a simple test on", sys.argv[1] 111 test_file(sys.argv[1]) 112 else: 113 print "Running a simple test on some built-in string." 114 test() 115 116 # vim: tabstop=4 expandtab shiftwidth=4