1
2
3 """
4 IO test cases that apply to both etree and ElementTree
5 """
6
7 import unittest
8 import tempfile, gzip, os, gc
9
10 from common_imports import etree, ElementTree, fileInTestDir
11 from common_imports import SillyFileLike, LargeFileLike
12
14 """(c)ElementTree compatibility for IO functions/methods
15 """
16 etree = None
17
24
27
29
30
31 handle, filename = tempfile.mkstemp(suffix=".xml")
32 self.tree.write(filename)
33 try:
34 self.assertEqual(open(filename).read(), self.root_str)
35 finally:
36 os.close(handle)
37 os.remove(filename)
38
40
41 handle, filename = tempfile.mkstemp(suffix=".xml.gz")
42 f = gzip.open(filename, 'wb')
43 f.write(self.root_str)
44 f.close()
45 try:
46 f_gz = gzip.open(filename, 'r')
47 tree = self.etree.parse(f_gz)
48 f_gz.close()
49 self.assertEqual(self.etree.tostring(tree.getroot()), self.root_str)
50 finally:
51 os.close(handle)
52 os.remove(filename)
53
55
56
57
58
59
60 handle, filename = tempfile.mkstemp(suffix=".xml")
61 open(filename, 'wb').write(self.root_str)
62 try:
63 tree = self.etree.ElementTree()
64 root = tree.parse(filename)
65 self.assertEqual(self.etree.tostring(root), self.root_str)
66 finally:
67 os.close(handle)
68 os.remove(filename)
69
71 handle, filename = tempfile.mkstemp(suffix=".xml")
72 open(filename, 'wb').write(self.root_str)
73 try:
74 tree = self.etree.ElementTree()
75 root = tree.parse(filename)
76
77 root2 = tree.parse(filename)
78 self.assertEquals('a', root.tag)
79 self.assertEquals('a', root2.tag)
80
81 del root2
82 root3 = tree.parse(filename)
83 self.assertEquals('a', root.tag)
84 self.assertEquals('a', root3.tag)
85
86
87 finally:
88 os.close(handle)
89 os.remove(filename)
90
92
93
94
95
96
97 handle, filename = tempfile.mkstemp(suffix=".xml")
98 os.write(handle, self.root_str)
99 try:
100 f = open(filename, 'r')
101 tree = self.etree.ElementTree()
102 root = tree.parse(f)
103 f.close()
104 self.assertEqual(self.etree.tostring(root), self.root_str)
105 finally:
106 os.close(handle)
107 os.remove(filename)
108
117
124
126 class LocalError(Exception):
127 pass
128 class TestFile:
129 def read(*args):
130 raise LocalError
131 f = TestFile()
132 self.assertRaises(LocalError, self.etree.parse, f)
133
135 class LocalError(Exception):
136 pass
137 class TestFile:
138 data = '<root>test</'
139 next_char = iter(data).next
140 counter = 0
141 def read(self, amount=None):
142 if amount is None:
143 while True:
144 self.read(1)
145 else:
146 try:
147 self.counter += 1
148 return self.next_char()
149 except StopIteration:
150 raise LocalError
151 f = TestFile()
152 self.assertRaises(LocalError, self.etree.parse, f)
153 self.assertEquals(f.counter, len(f.data)+1)
154
156 class TestFile:
157 def read(*args):
158 return 1
159 f = TestFile()
160 self.assertRaises(TypeError, self.etree.parse, f)
161
162
165
166 if ElementTree:
169
176
177 if __name__ == '__main__':
178 unittest.main()
179