Debian Codegraph @

petl/test/io/test_xml.py

raw
1 # -*- coding: utf-8 -*-
2 from __future__ import absolute_import, print_function, division
3
4 import sys
5 from tempfile import NamedTemporaryFile
6
7 import pytest
8
9 from petl.test.helpers import ieq
10 from petl.util import nrows, look
11 from petl.io.xml import fromxml, toxml
12 from petl.compat import urlopen
13
14 try:
15 from importlib.resources import files
16 except ImportError: # Python < 3.9
17 from importlib_resources import files
18
19
20 def test_fromxml():
21
22 # initial data
23 f = NamedTemporaryFile(delete=False, mode='wt')
24 data = """<table>
25 <tr>
26 <td>foo</td><td>bar</td>
27 </tr>
28 <tr>
29 <td>a</td><td>1</td>
30 </tr>
31 <tr>
32 <td>b</td><td>2</td>
33 </tr>
34 <tr>
35 <td>c</td><td>2</td>
36 </tr>
37 </table>"""
38 f.write(data)
39 f.close()
40
41 actual = fromxml(f.name, 'tr', 'td')
42 expect = (('foo', 'bar'),
43 ('a', '1'),
44 ('b', '2'),
45 ('c', '2'))
46 ieq(expect, actual)
47 ieq(expect, actual) # verify can iterate twice
48
49
50 def test_fromxml_2():
51
52 # initial data
53 f = NamedTemporaryFile(delete=False, mode='wt')
54 data = """<table>
55 <tr>
56 <td v='foo'/><td v='bar'/>
57 </tr>
58 <tr>
59 <td v='a'/><td v='1'/>
60 </tr>
61 <tr>
62 <td v='b'/><td v='2'/>
63 </tr>
64 <tr>
65 <td v='c'/><td v='2'/>
66 </tr>
67 </table>"""
68 f.write(data)
69 f.close()
70
71 actual = fromxml(f.name, 'tr', 'td', 'v')
72 expect = (('foo', 'bar'),
73 ('a', '1'),
74 ('b', '2'),
75 ('c', '2'))
76 ieq(expect, actual)
77 ieq(expect, actual) # verify can iterate twice
78
79
80 def test_fromxml_3():
81
82 # initial data
83 f = NamedTemporaryFile(delete=False, mode='wt')
84 data = """<table>
85 <row>
86 <foo>a</foo><baz><bar v='1'/></baz>
87 </row>
88 <row>
89 <foo>b</foo><baz><bar v='2'/></baz>
90 </row>
91 <row>
92 <foo>c</foo><baz><bar v='2'/></baz>
93 </row>
94 </table>"""
95 f.write(data)
96 f.close()
97
98 actual = fromxml(f.name, 'row', {'foo': 'foo', 'bar': ('baz/bar', 'v')})
99 # N.B., requested fields come out in name sorted order
100 expect = (('bar', 'foo'),
101 ('1', 'a'),
102 ('2', 'b'),
103 ('2', 'c'))
104 ieq(expect, actual)
105 ieq(expect, actual) # verify can iterate twice
106
107
108 def test_fromxml_4():
109
110 # initial data
111 f = NamedTemporaryFile(delete=False, mode='wt')
112 data = """<table>
113 <row>
114 <foo>a</foo><baz><bar>1</bar><bar>3</bar></baz>
115 </row>
116 <row>
117 <foo>b</foo><baz><bar>2</bar></baz>
118 </row>
119 <row>
120 <foo>c</foo><baz><bar>2</bar></baz>
121 </row>
122 </table>"""
123 f.write(data)
124 f.close()
125
126 actual = fromxml(f.name, 'row', {'foo': 'foo', 'bar': './/bar'})
127 # N.B., requested fields come out in name sorted order
128 expect = (('bar', 'foo'),
129 (('1', '3'), 'a'),
130 ('2', 'b'),
131 ('2', 'c'))
132 ieq(expect, actual)
133 ieq(expect, actual) # verify can iterate twice
134
135
136 def test_fromxml_5():
137
138 # initial data
139 f = NamedTemporaryFile(delete=False, mode='wt')
140 data = """<table>
141 <row>
142 <foo>a</foo><baz><bar v='1'/><bar v='3'/></baz>
143 </row>
144 <row>
145 <foo>b</foo><baz><bar v='2'/></baz>
146 </row>
147 <row>
148 <foo>c</foo><baz><bar v='2'/></baz>
149 </row>
150 </table>"""
151 f.write(data)
152 f.close()
153
154 actual = fromxml(f.name, 'row', {'foo': 'foo', 'bar': ('baz/bar', 'v')})
155 # N.B., requested fields come out in name sorted order
156 expect = (('bar', 'foo'),
157 (('1', '3'), 'a'),
158 ('2', 'b'),
159 ('2', 'c'))
160 ieq(expect, actual)
161 ieq(expect, actual) # verify can iterate twice
162
163
164 def test_fromxml_6():
165
166 data = """<table class='petl'>
167 <thead>
168 <tr>
169 <th>foo</th>
170 <th>bar</th>
171 </tr>
172 </thead>
173 <tbody>
174 <tr>
175 <td>a</td>
176 <td style='text-align: right'>2</td>
177 </tr>
178 <tr>
179 <td>b</td>
180 <td style='text-align: right'>1</td>
181 </tr>
182 <tr>
183 <td>c</td>
184 <td style='text-align: right'>3</td>
185 </tr>
186 </tbody>
187 </table>"""
188 f = NamedTemporaryFile(delete=False, mode='wt')
189 f.write(data)
190 f.close()
191
192 actual = fromxml(f.name, './/tr', ('th', 'td'))
193 print(look(actual))
194 expect = (('foo', 'bar'),
195 ('a', '2'),
196 ('b', '1'),
197 ('c', '3'))
198 ieq(expect, actual)
199 ieq(expect, actual) # verify can iterate twice
200
201
202 def test_fromxml_url():
203 # check internet connection
204 try:
205 url = 'http://raw.githubusercontent.com/petl-developers/petl/master/petl/test/resources/test.xml'
206 urlopen(url)
207 filename = str(files('petl') / 'test/resources/test.xml')
208 except Exception as e:
209 pytest.skip('SKIP test_fromxml_url: %s' % e)
210 else:
211 actual = fromxml(url, 'pydev_property', {'name': ( '.', 'name'), 'prop': '.'})
212 assert nrows(actual) > 0
213 expect = fromxml(filename, 'pydev_property', {'name': ( '.', 'name'), 'prop': '.'})
214 ieq(expect, actual)
215
216
217 def _write_temp_file(content, out=None):
218 with NamedTemporaryFile(delete=False, mode='wt') as f:
219 f.write(content)
220 res = f.name
221 f.close()
222 if out is not None:
223 outf = sys.stderr if out else sys.stdout
224 print('TEST %s:\n%s' % (res, content), file=outf)
225 return res
226
227
228 def _dump_file(filename, out=None):
229 if out is not None:
230 outf = sys.stderr if out else sys.stdout
231 print('FILE:\n%s' % open(filename).read(), file=outf)
232
233
234 def _dump_both(expected, actual, out=None):
235 if out is not None:
236 outf = sys.stderr if out else sys.stdout
237 print('EXPECTED:\n', look(expected), file=outf)
238 print('ACTUAL:\n', look(actual), file=outf)
239
240
241 def _compare(expected, actual, out=None):
242 try:
243 _dump_both(expected, actual, out)
244 ieq(expected, actual)
245 except Exception as ex:
246 _dump_both(expected, actual, False)
247 raise ex
248
249
250 def _write_test_file(data, pre='', pos=''):
251 content = pre + '<table>' + data + pos + '</table>'
252 return _write_temp_file(content)
253
254
255 def test_fromxml_entity():
256 _DATA1 = """
257 <tr><td>foo</td><td>bar</td></tr>
258 <tr><td>a</td><td>1</td></tr>
259 <tr><td>b</td><td>2</td></tr>
260 <tr><td>c</td><td>3</td></tr>
261 """
262
263 _DATA2 = '<td>X</td><td>9</td>'
264
265 _DOCTYPE = """<?xml version="1.0" encoding="ISO-8859-1"?>
266 <!DOCTYPE foo [
267 <!ELEMENT table ANY >
268 <!ENTITY inserted SYSTEM "file://%s" >]>
269 """
270
271 _INSERTED = '<tr>&inserted;</tr>'
272
273 _TABLE1 = (('foo', 'bar'),
274 ('a', '1'),
275 ('b', '2'),
276 ('c', '3'))
277
278 temp_file1 = _write_test_file(_DATA1)
279
280 actual11 = fromxml(temp_file1, 'tr', 'td')
281 _compare(_TABLE1, actual11)
282
283 try:
284 from lxml import etree
285 except:
286 return
287
288 data_file_tmp = _write_temp_file(_DATA2)
289 doc_type_temp = _DOCTYPE % data_file_tmp
290 doc_type_miss = _DOCTYPE % '/tmp/doesnotexist'
291
292 _EXPECT_IT = (('X', '9'),)
293 _EXPECT_NO = ((None, None),)
294
295 temp_file2 = _write_test_file(_DATA1, pre=doc_type_temp, pos=_INSERTED)
296 temp_file3 = _write_test_file(_DATA1, pre=doc_type_miss, pos=_INSERTED)
297
298 parser_off = etree.XMLParser(resolve_entities=False)
299 parser_onn = etree.XMLParser(resolve_entities=True)
300
301 actual12 = fromxml(temp_file1, 'tr', 'td', parser=parser_off)
302 _compare(_TABLE1, actual12)
303
304 actual21 = fromxml(temp_file2, 'tr', 'td')
305 _compare(_TABLE1 + _EXPECT_NO, actual21)
306
307 actual22 = fromxml(temp_file2, 'tr', 'td', parser=parser_off)
308 _compare(_TABLE1 + _EXPECT_NO, actual22)
309
310 actual23 = fromxml(temp_file2, 'tr', 'td', parser=parser_onn)
311 _compare(_TABLE1 + _EXPECT_IT, actual23)
312
313 actual31 = fromxml(temp_file3, 'tr', 'td')
314 _compare(_TABLE1 + _EXPECT_NO, actual31)
315
316 actual32 = fromxml(temp_file3, 'tr', 'td', parser=parser_off)
317 _compare(_TABLE1 + _EXPECT_NO, actual32)
318
319 try:
320 actual33 = fromxml(temp_file3, 'tr', 'td', parser=parser_onn)
321 for _ in actual33:
322 pass
323 except etree.XMLSyntaxError:
324 # print('XMLSyntaxError', ex, file=sys.stderr)
325 pass
326 else:
327 assert True, 'Error testing XML'
328
329
330 def _check_toxml(table, expected, check=(), dump=None, **kwargs):
331 with NamedTemporaryFile(delete=True, suffix='.xml') as f:
332 filename = f.name
333
334 toxml(table, filename, **kwargs)
335 _dump_file(filename, dump)
336 if check:
337 try:
338 actual = fromxml(filename, *check)
339 _compare(expected, actual, dump)
340 except Exception as ex:
341 _dump_file(filename, False)
342 raise ex
343
344
345 _HEAD1 = (('ABCD', 'N123'),)
346 _BODY1 = (('a', '1'),
347 ('b', '2'),
348 ('c', '3'))
349 _TABLE1 = _HEAD1 + _BODY1
350
351
352 def test_toxml00():
353 _check_toxml(
354 _TABLE1, _TABLE1,
355 check=('.//tr', ('th', 'td'))
356 )
357
358
359 def test_toxml01():
360 _check_toxml(
361 _TABLE1, _TABLE1,
362 check=('.//tr', ('th', 'td')),
363 root='table',
364 head='thead/tr/th',
365 rows='tbody/tr/td'
366 )
367
368
369 def test_toxml02():
370 _check_toxml(
371 _TABLE1, _BODY1,
372 check=('.//row', 'col'),
373 root='matrix',
374 rows='row/col'
375 )
376
377
378 def test_toxml03():
379 _check_toxml(
380 _TABLE1, _BODY1,
381 check=('line', 'cell'),
382 rows='plan/line/cell'
383 )
384
385
386 def test_toxml04():
387 _check_toxml(
388 _TABLE1, _BODY1,
389 check=('.//line', 'cell'),
390 rows='dir/file/book/plan/line/cell'
391 )
392
393
394 def test_toxml05():
395 _check_toxml(
396 _TABLE1, _TABLE1,
397 check=('.//x', 'y'),
398 root='a',
399 head='h/k/x/y',
400 rows='r/v/x/y'
401 )
402
403
404 def test_toxml06():
405 _check_toxml(
406 _TABLE1, _TABLE1,
407 check=('.//row', 'col'),
408 root='table',
409 head='head/row/col',
410 rows='row/col'
411 )
412
413
414 def test_toxml07():
415 _check_toxml(
416 _TABLE1, _TABLE1,
417 check=('.//field-list', 'field-name'),
418 root='root-tag',
419 head='head-tag/field-list/field-name',
420 rows='body-row/field-list/field-name'
421 )
422
423
424 def test_toxml08():
425 _check_toxml(
426 _TABLE1, _TABLE1,
427 check=('.//field.list', 'field.name'),
428 root='root.tag',
429 head='head.tag/field.list/field.name',
430 rows='body.row/field.list/field.name'
431 )
432
433
434 def test_toxml09():
435 _check_toxml(
436 _TABLE1, _BODY1,
437 check=('.//tr/td', '*'),
438 style='name',
439 root='table',
440 rows='tbody/tr/td'
441 )
442
443
444 def test_toxml10():
445 _check_toxml(
446 _TABLE1, _BODY1,
447 check=('.//tr/td', '*'),
448 style='name',
449 root='table',
450 head='thead/tr/th',
451 rows='tbody/tr/td'
452 )
453
454
455 _ATTRIB_COLS = {'ABCD': ('.', 'ABCD'), 'N123': ('.', 'N123')}
456
457
458 def test_toxml11():
459 _check_toxml(
460 _TABLE1, _TABLE1,
461 check=('.//tr/td', _ATTRIB_COLS),
462 style='attribute',
463 root='table',
464 rows='tbody/tr/td'
465 )
466
467
468 def test_toxml12():
469 _check_toxml(
470 _TABLE1, _TABLE1,
471 check=('.//tr/td', _ATTRIB_COLS),
472 style='attribute',
473 root='table',
474 head='thead/tr/th',
475 rows='tbody/tr/td'
476 )
477
478
479 def test_toxml13():
480 _check_toxml(
481 _TABLE1, _BODY1,
482 check=('.//tr', ('td', 'th')),
483 style=' <tr><td>{ABCD}</td><td>{N123}</td></tr>\n',
484 root='table',
485 rows='tbody'
486 )
487
488
489 def test_toxml131():
490 _check_toxml(
491 _TABLE1, _TABLE1,
492 check=('.//tr', ('th', 'td')),
493 style=' <tr><td>{ABCD}</td><td>{N123}</td></tr>\n',
494 root='table',
495 head='thead/tr/td',
496 rows='tbody'
497 )
498
499
500 def test_toxml14():
501 table1 = [['foo', 'bar'],
502 ['a', 1],
503 ['b', 2]]
504
505 _check_toxml(
506 table1, table1,
507 style='attribute',
508 rows='row/col'
509 )
510 _check_toxml(
511 table1, table1,
512 style='name',
513 rows='row/col'
514 )
515
516
517 _ROW_A0 = (('A', '0'),)
518 _ROW_Z9 = (('Z', '9'),)
519 _TAB_ABZ = _ROW_A0 + _BODY1 + _ROW_Z9
520 _TAB_HAZ = _HEAD1 + _ROW_A0 + _BODY1 + _ROW_Z9
521 _TAG_A0 = ' <row><col>A</col><col>0</col></row>'
522 _TAG_Z9 = ' <row><col>Z</col><col>9</col></row>'
523 _TAG_TOP = '<table>\n'
524 _TAG_END = '\n</table>'
525
526
527 def test_toxml15():
528 _check_toxml(
529 _TABLE1, _TAB_ABZ,
530 check=('row', 'col'),
531 root='table',
532 rows='row/col',
533 prologue=_TAG_A0,
534 epilogue=_TAG_Z9
535 )
536
537
538 def test_toxml16():
539 _check_toxml(
540 _TABLE1, _TAB_HAZ,
541 check=('.//row', 'col'),
542 root='table',
543 head='thead/row/col',
544 rows='tbody/row/col',
545 prologue=_TAG_A0,
546 epilogue=_TAG_Z9
547 )
548
549
550 def test_toxml17():
551 _check_toxml(
552 _TABLE1, _TAB_ABZ,
553 check=('row', 'col'),
554 rows='row/col',
555 prologue=_TAG_TOP + _TAG_A0,
556 epilogue=_TAG_Z9 + _TAG_END
557 )
558
559
560 def test_toxml18():
561 _TAB_AHZ = _ROW_A0 + _HEAD1 + _BODY1 + _ROW_Z9
562 _check_toxml(
563 _TABLE1, _TAB_AHZ,
564 check=('.//row', 'col'),
565 head='thead/row/col',
566 rows='row/col',
567 prologue=_TAG_TOP + _TAG_A0,
568 epilogue=_TAG_Z9 + _TAG_END
569 )
570
571
572 def test_toxml19():
573 _check_toxml(
574 _TABLE1, _BODY1,
575 check=('.//line', 'cell'),
576 rows='tbody/line/cell',
577 prologue=_TAG_TOP + _TAG_A0,
578 epilogue=_TAG_Z9 + _TAG_END
579 )
580
581
582 def test_toxml20():
583 _check_toxml(
584 _TABLE1, _TABLE1,
585 check=('.//line', 'cell'),
586 root='book',
587 head='thead/line/cell',
588 rows='tbody/line/cell',
589 prologue=_TAG_TOP + _TAG_A0,
590 epilogue=_TAG_Z9 + _TAG_END
591 )
592
593
594 def test_toxml21():
595 _check_toxml(
596 _TABLE1, _TAB_HAZ,
597 check=('.//row', 'col'),
598 root='book',
599 head='thead/row/col',
600 rows='tbody/row/col',
601 prologue=_TAG_TOP + _TAG_A0,
602 epilogue=_TAG_Z9 + _TAG_END
603 )
604
605
606 def test_toxml22():
607 _check_toxml(
608 _TABLE1, _TAB_HAZ,
609 check=('.//tr/td', _ATTRIB_COLS),
610 style='attribute',
611 root='table',
612 rows='tbody/tr/td',
613 # dump=True,
614 prologue='<td ABCD="A" N123="0" />',
615 epilogue='<td ABCD="Z" N123="9" />'
616 )