1
2
3 """
4 IO test cases that apply to both etree and ElementTree
5 """
6
7 import unittest
8 import tempfile, gzip, os, os.path, sys, gc, shutil
9
10 this_dir = os.path.dirname(__file__)
11 if this_dir not in sys.path:
12 sys.path.insert(0, this_dir)
13
14 from common_imports import etree, ElementTree, _str, _bytes
15 from common_imports import SillyFileLike, LargeFileLike, HelperTestCase
16 from common_imports import read_file, write_to_file, BytesIO
17
18
20 """(c)ElementTree compatibility for IO functions/methods
21 """
22 etree = None
23
31
33 gc.collect()
34 shutil.rmtree(self._temp_dir)
35
37 return os.path.join(self._temp_dir, name)
38
48
50 Element = self.etree.Element
51 ElementTree = self.etree.ElementTree
52
53 element = Element('top')
54 element.text = _str("qwrtioüöä\uAABB")
55 tree = ElementTree(element)
56 self.buildNodes(element, 10, 3)
57 f = open(self.getTestFilePath('testdump.xml'), 'wb')
58 tree.write(f, encoding='UTF-8')
59 f.close()
60 f = open(self.getTestFilePath('testdump.xml'), 'rb')
61 tree = ElementTree(file=f)
62 f.close()
63 f = open(self.getTestFilePath('testdump2.xml'), 'wb')
64 tree.write(f, encoding='UTF-8')
65 f.close()
66 f = open(self.getTestFilePath('testdump.xml'), 'rb')
67 data1 = f.read()
68 f.close()
69 f = open(self.getTestFilePath('testdump2.xml'), 'rb')
70 data2 = f.read()
71 f.close()
72 self.assertEqual(data1, data2)
73
75 Element = self.etree.Element
76 ElementTree = self.etree.ElementTree
77
78 element = Element('top')
79 element.text = _str("qwrtioüöäßá")
80 tree = ElementTree(element)
81 self.buildNodes(element, 10, 3)
82 f = open(self.getTestFilePath('testdump.xml'), 'wb')
83 tree.write(f, encoding='iso-8859-1')
84 f.close()
85 f = open(self.getTestFilePath('testdump.xml'), 'rb')
86 tree = ElementTree(file=f)
87 f.close()
88 f = open(self.getTestFilePath('testdump2.xml'), 'wb')
89 tree.write(f, encoding='iso-8859-1')
90 f.close()
91 f = open(self.getTestFilePath('testdump.xml'), 'rb')
92 data1 = f.read()
93 f.close()
94 f = open(self.getTestFilePath('testdump2.xml'), 'rb')
95 data2 = f.read()
96 f.close()
97 self.assertEqual(data1, data2)
98
110
112 filename = os.path.join(
113 os.path.join('hopefullynonexistingpathname'),
114 'invalid_file.xml')
115 try:
116 self.tree.write(filename)
117 except IOError:
118 pass
119 else:
120 self.assertTrue(
121 False, "writing to an invalid file path should fail")
122
137
153
174
192
201
208
210 class LocalError(Exception):
211 pass
212 class TestFile:
213 def read(*args):
214 raise LocalError
215 f = TestFile()
216 self.assertRaises(LocalError, self.etree.parse, f)
217
219 class LocalError(Exception):
220 pass
221 class TestFile:
222 data = '<root>test</'
223 try:
224 next_char = iter(data).next
225 except AttributeError:
226
227 next_char = iter(data).__next__
228 counter = 0
229 def read(self, amount=None):
230 if amount is None:
231 while True:
232 self.read(1)
233 else:
234 try:
235 self.counter += 1
236 return _bytes(self.next_char())
237 except StopIteration:
238 raise LocalError
239 f = TestFile()
240 self.assertRaises(LocalError, self.etree.parse, f)
241 self.assertEqual(f.counter, len(f.data)+1)
242
244 class TestFile:
245 def read(*args):
246 return 1
247 f = TestFile()
248
249 try:
250 expect_exc = (TypeError, self.etree.ParseError)
251 except AttributeError:
252 expect_exc = TypeError
253 self.assertRaises(expect_exc, self.etree.parse, f)
254
256
257 dirnameEN = _str('Directory')
258 dirnameRU = _str('Каталог')
259 filename = _str('nosuchfile.xml')
260 dn = tempfile.mkdtemp(prefix=dirnameEN)
261 try:
262 self.assertRaises(IOError, self.etree.parse, os.path.join(dn, filename))
263 finally:
264 os.rmdir(dn)
265 dn = tempfile.mkdtemp(prefix=dirnameRU)
266 try:
267 self.assertRaises(IOError, self.etree.parse, os.path.join(dn, filename))
268 finally:
269 os.rmdir(dn)
270
272 utext = _str('Søk på nettet')
273 uxml = '<?xml version="1.0" encoding="UTF-8"?><p>%s</p>' % utext
274 bom = _bytes('\\xEF\\xBB\\xBF').decode(
275 "unicode_escape").encode("latin1")
276 self.assertEqual(3, len(bom))
277 f = tempfile.NamedTemporaryFile(delete=False)
278 try:
279 try:
280 f.write(bom)
281 f.write(uxml.encode("utf-8"))
282 finally:
283 f.close()
284 tree = self.etree.parse(f.name)
285 finally:
286 os.unlink(f.name)
287 self.assertEqual(utext, tree.getroot().text)
288
290 utext = _str('Søk på nettet')
291 uxml = '<?xml version="1.0" encoding="UTF-8"?><p>%s</p>' % utext
292 bom = _bytes('\\xEF\\xBB\\xBF').decode(
293 "unicode_escape").encode("latin1")
294 self.assertEqual(3, len(bom))
295 f = tempfile.NamedTemporaryFile(delete=False)
296 try:
297 try:
298 f.write(bom)
299 f.write(uxml.encode("utf-8"))
300 finally:
301 f.close()
302 elements = [el for _, el in self.etree.iterparse(f.name)]
303 self.assertEqual(1, len(elements))
304 root = elements[0]
305 finally:
306 os.unlink(f.name)
307 self.assertEqual(utext, root.text)
308
310 utext = _str('Søk på nettet')
311 uxml = '<?xml version="1.0" encoding="UTF-16"?><p>%s</p>' % utext
312 boms = _bytes('\\xFE\\xFF \\xFF\\xFE').decode(
313 "unicode_escape").encode("latin1")
314 self.assertEqual(5, len(boms))
315 xml = uxml.encode("utf-16")
316 self.assertTrue(xml[:2] in boms, repr(xml[:2]))
317
318 f = tempfile.NamedTemporaryFile(delete=False)
319 try:
320 try:
321 f.write(xml)
322 finally:
323 f.close()
324 elements = [el for _, el in self.etree.iterparse(f.name)]
325 self.assertEqual(1, len(elements))
326 root = elements[0]
327 finally:
328 os.unlink(f.name)
329 self.assertEqual(utext, root.text)
330
331
359
360
361 if ElementTree:
364
365
372
373
374 if __name__ == '__main__':
375 print('to test use test.py %s' % __file__)
376