1
2
3 """
4 Tests for the ElementTree API
5
6 Only test cases that apply equally well to etree and ElementTree
7 belong here. Note that there is a second test module called test_io.py
8 for IO related test cases.
9 """
10
11 import unittest, doctest
12 import os, re, shutil, tempfile, copy
13
14 from common_imports import StringIO, etree, ElementTree
15 from common_imports import HelperTestCase, fileInTestDir, canonicalize
16
18 etree = None
19
23
27
29 return os.path.join(self._temp_dir, name)
30
34
36 Element = self.etree.Element
37 ElementTree = self.etree.ElementTree
38
39 element = Element('top')
40 tree = ElementTree(element)
41 self.buildNodes(element, 10, 3)
42 f = open(self.getTestFilePath('testdump.xml'), 'w')
43 tree.write(f, 'UTF-8')
44 f.close()
45 f = open(self.getTestFilePath('testdump.xml'), 'r')
46 tree = ElementTree(file=f)
47 f.close()
48 f = open(self.getTestFilePath('testdump2.xml'), 'w')
49 tree.write(f, 'UTF-8')
50 f.close()
51 f = open(self.getTestFilePath('testdump.xml'), 'r')
52 data1 = f.read()
53 f.close()
54 f = open(self.getTestFilePath('testdump2.xml'), 'r')
55 data2 = f.read()
56 f.close()
57 self.assertEquals(data1, data2)
58
60 Element = self.etree.Element
61
62 if depth == 0:
63 return
64 for i in range(children):
65 new_element = Element('element_%s_%s' % (depth, i))
66 self.buildNodes(new_element, children, depth - 1)
67 element.append(new_element)
68
70 Element = self.etree.Element
71
72 root = Element('root')
73 root.append(Element('one'))
74 root.append(Element('two'))
75 root.append(Element('three'))
76 self.assertEquals(3, len(root))
77 self.assertEquals('one', root[0].tag)
78 self.assertEquals('two', root[1].tag)
79 self.assertEquals('three', root[2].tag)
80 self.assertRaises(IndexError, root.__getitem__, 3)
81
94
112
114 ElementTree = self.etree.ElementTree
115
116 f = StringIO('<doc>Test<one>One</one></doc>')
117 doc = ElementTree(file=f)
118 root = doc.getroot()
119 self.assertEquals(1, len(root))
120 self.assertEquals('one', root[0].tag)
121 self.assertRaises(IndexError, root.__getitem__, 1)
122
124 ElementTree = self.etree.ElementTree
125
126 f = StringIO('<doc><one>One</one><two>Two</two>hm<three>Three</three></doc>')
127 doc = ElementTree(file=f)
128 root = doc.getroot()
129 self.assertEquals(3, len(root))
130 self.assertEquals('one', root[0].tag)
131 self.assertEquals('two', root[1].tag)
132 self.assertEquals('three', root[2].tag)
133
135 ElementTree = self.etree.ElementTree
136
137 f = StringIO('<doc>Test</doc>')
138 doc = ElementTree(file=f)
139 root = doc.getroot()
140 self.assertEquals(0, len(root))
141
143 Element = self.etree.Element
144 SubElement = self.etree.SubElement
145 a = Element('a')
146 b = SubElement(a, 'b')
147 c = SubElement(a, 'c')
148 d = SubElement(a, 'd')
149 self.assertEquals(d, a[-1])
150 self.assertEquals(c, a[-2])
151 self.assertEquals(b, a[-3])
152 self.assertRaises(IndexError, a.__getitem__, -4)
153 a[-1] = e = Element('e')
154 self.assertEquals(e, a[-1])
155 del a[-1]
156 self.assertEquals(2, len(a))
157
159 ElementTree = self.etree.ElementTree
160
161 f = StringIO('<doc><one>One</one><two>Two</two></doc>')
162 doc = ElementTree(file=f)
163 root = doc.getroot()
164 self.assertEquals(2, len(root))
165 self.assertEquals('one', root[0].tag)
166 self.assertEquals('two', root[1].tag)
167
168 - def test_text(self):
169 ElementTree = self.etree.ElementTree
170
171 f = StringIO('<doc>This is a text</doc>')
172 doc = ElementTree(file=f)
173 root = doc.getroot()
174 self.assertEquals('This is a text', root.text)
175
176 - def test_text_empty(self):
177 ElementTree = self.etree.ElementTree
178
179 f = StringIO('<doc></doc>')
180 doc = ElementTree(file=f)
181 root = doc.getroot()
182 self.assertEquals(None, root.text)
183
184 - def test_text_other(self):
185 ElementTree = self.etree.ElementTree
186
187 f = StringIO('<doc><one>One</one></doc>')
188 doc = ElementTree(file=f)
189 root = doc.getroot()
190 self.assertEquals(None, root.text)
191 self.assertEquals('One', root[0].text)
192
194 ElementTree = self.etree.ElementTree
195
196 f = StringIO('<doc>This is > than a text</doc>')
197 doc = ElementTree(file=f)
198 root = doc.getroot()
199 self.assertEquals('This is > than a text', root.text)
200
202 Element = self.etree.Element
203
204 a = Element("a")
205 a.text = "<>&"
206 self.assertXML('<a><>&</a>',
207 a)
208
210 tostring = self.etree.tostring
211 Element = self.etree.Element
212
213 a = Element("a")
214 a.text = "<>&"
215 self.assertEquals('<a><>&</a>',
216 tostring(a))
217
219 Element = self.etree.Element
220
221 class strTest(str):
222 pass
223
224 a = Element("a")
225 a.text = strTest("text")
226 self.assertXML('<a>text</a>',
227 a)
228
230 ElementTree = self.etree.ElementTree
231
232 f = StringIO('<doc>This is <i>mixed</i> content.</doc>')
233 doc = ElementTree(file=f)
234 root = doc.getroot()
235 self.assertEquals(1, len(root))
236 self.assertEquals('This is ', root.text)
237 self.assertEquals(None, root.tail)
238 self.assertEquals('mixed', root[0].text)
239 self.assertEquals(' content.', root[0].tail)
240
247
248 a = Element("a")
249 SubElement(a, "t").tail = strTest("tail")
250 self.assertXML('<a><t></t>tail</a>',
251 a)
252
262
264 ElementTree = self.etree.ElementTree
265
266 f = StringIO('<doc one="One" two="Two"/>')
267 doc = ElementTree(file=f)
268 root = doc.getroot()
269 self.assertEquals('One', root.attrib['one'])
270 self.assertEquals('Two', root.attrib['two'])
271 self.assertRaises(KeyError, root.attrib.__getitem__, 'three')
272
274 ElementTree = self.etree.ElementTree
275
276 f = StringIO('<doc one="One" two="Two"/>')
277 doc = ElementTree(file=f)
278 root = doc.getroot()
279 self.assertEquals('One', root.attrib.get('one'))
280 self.assertEquals('Two', root.attrib.get('two'))
281 self.assertEquals(None, root.attrib.get('three'))
282 self.assertEquals('foo', root.attrib.get('three', 'foo'))
283
285 ElementTree = self.etree.ElementTree
286
287 f = StringIO('<doc one="One" two="Two"/>')
288 doc = ElementTree(file=f)
289 root = doc.getroot()
290 self.assertEquals('One', root.get('one'))
291 self.assertEquals('Two', root.get('two'))
292 self.assertEquals(None, root.get('three'))
293 self.assertEquals('foo', root.get('three', 'foo'))
294
296 XML = self.etree.XML
297
298 root = XML('<doc one="One" two="Two"/>')
299 self.assertEquals('One', root.get('one'))
300 self.assertEquals('Two', root.get('two'))
301 root.attrib.clear()
302 self.assertEquals(None, root.get('one'))
303 self.assertEquals(None, root.get('two'))
304
306 Element = self.etree.Element
307
308 root = Element("root", one="One")
309 root.set("two", "Two")
310 self.assertEquals('One', root.get('one'))
311 self.assertEquals('Two', root.get('two'))
312 root.attrib.clear()
313 self.assertEquals(None, root.get('one'))
314 self.assertEquals(None, root.get('two'))
315
317 XML = self.etree.XML
318
319 root = XML('<doc alpha="Alpha" beta="Beta"/>')
320 items = root.attrib.items()
321 items.sort()
322 self.assertEquals(
323 [('alpha', 'Alpha'), ('beta', 'Beta')],
324 items)
325
326 root.attrib.update({'alpha' : 'test', 'gamma' : 'Gamma'})
327
328 items = root.attrib.items()
329 items.sort()
330 self.assertEquals(
331 [('alpha', 'test'), ('beta', 'Beta'), ('gamma', 'Gamma')],
332 items)
333
335 XML = self.etree.XML
336
337 root = XML('<doc alpha="Alpha" beta="Beta"/>')
338 items = root.attrib.items()
339 items.sort()
340 self.assertEquals(
341 [('alpha', 'Alpha'), ('beta', 'Beta')],
342 items)
343
344 root.attrib.update({'alpha' : 'test', 'gamma' : 'Gamma'}.items())
345
346 items = root.attrib.items()
347 items.sort()
348 self.assertEquals(
349 [('alpha', 'test'), ('beta', 'Beta'), ('gamma', 'Gamma')],
350 items)
351
353 XML = self.etree.XML
354
355 root = XML('<doc alpha="Alpha" beta="Beta"/>')
356 items = root.attrib.items()
357 items.sort()
358 self.assertEquals(
359 [('alpha', 'Alpha'), ('beta', 'Beta')],
360 items)
361
362 root.attrib.update({'alpha' : 'test', 'gamma' : 'Gamma'}.iteritems())
363
364 items = root.attrib.items()
365 items.sort()
366 self.assertEquals(
367 [('alpha', 'test'), ('beta', 'Beta'), ('gamma', 'Gamma')],
368 items)
369
371 XML = self.etree.XML
372
373 root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')
374 keys = root.attrib.keys()
375 keys.sort()
376 self.assertEquals(['alpha', 'beta', 'gamma'], keys)
377
379 XML = self.etree.XML
380
381 root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')
382 keys = root.keys()
383 keys.sort()
384 self.assertEquals(['alpha', 'beta', 'gamma'], keys)
385
387 XML = self.etree.XML
388
389 root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')
390 items = root.items()
391 items.sort()
392 self.assertEquals(
393 [('alpha','Alpha'), ('beta','Beta'), ('gamma','Gamma')],
394 items)
395
397 XML = self.etree.XML
398
399 root = XML('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')
400 keys = root.keys()
401 keys.sort()
402 self.assertEquals(['bar', '{http://ns.codespeak.net/test}baz'],
403 keys)
404
406 XML = self.etree.XML
407
408 root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')
409 values = root.attrib.values()
410 values.sort()
411 self.assertEquals(['Alpha', 'Beta', 'Gamma'], values)
412
414 XML = self.etree.XML
415
416 root = XML('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')
417 values = root.attrib.values()
418 values.sort()
419 self.assertEquals(
420 ['Bar', 'Baz'], values)
421
423 XML = self.etree.XML
424
425 root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')
426 items = root.attrib.items()
427 items.sort()
428 self.assertEquals([
429 ('alpha', 'Alpha'),
430 ('beta', 'Beta'),
431 ('gamma', 'Gamma'),
432 ],
433 items)
434
436 XML = self.etree.XML
437
438 root = XML('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')
439 items = root.attrib.items()
440 items.sort()
441 self.assertEquals(
442 [('bar', 'Bar'), ('{http://ns.codespeak.net/test}baz', 'Baz')],
443 items)
444
446 XML = self.etree.XML
447
448 root = XML('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')
449
450 self.assertEquals(
451 "{'{http://ns.codespeak.net/test}baz': 'Baz', 'bar': 'Bar'}",
452 str(root.attrib))
453
455 XML = self.etree.XML
456
457 root = XML('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')
458 self.assertEquals(
459 True, root.attrib.has_key('bar'))
460 self.assertEquals(
461 False, root.attrib.has_key('baz'))
462 self.assertEquals(
463 False, root.attrib.has_key('hah'))
464 self.assertEquals(
465 True,
466 root.attrib.has_key('{http://ns.codespeak.net/test}baz'))
467
469 XML = self.etree.XML
470
471 root = XML('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')
472 self.assertEquals(
473 True, 'bar' in root.attrib)
474 self.assertEquals(
475 False, 'baz' in root.attrib)
476 self.assertEquals(
477 False, 'hah' in root.attrib)
478 self.assertEquals(
479 True,
480 '{http://ns.codespeak.net/test}baz' in root.attrib)
481
483 Element = self.etree.Element
484
485 root = Element("root")
486 root.set("attr", "TEST")
487 self.assertEquals("TEST", root.get("attr"))
488
490 XML = self.etree.XML
491
492 root = XML('<doc>This is a text.</doc>')
493 self.assertEquals(0, len(root))
494 self.assertEquals('This is a text.', root.text)
495
497 XMLID = self.etree.XMLID
498 XML = self.etree.XML
499 xml_text = '''
500 <document>
501 <h1 id="chapter1">...</h1>
502 <p id="note1" class="note">...</p>
503 <p>Regular paragraph.</p>
504 <p xml:id="xmlid">XML:ID paragraph.</p>
505 <p id="warn1" class="warning">...</p>
506 </document>
507 '''
508
509 root, dic = XMLID(xml_text)
510 root2 = XML(xml_text)
511 self.assertEquals(self._writeElement(root),
512 self._writeElement(root2))
513 expected = {
514 "chapter1" : root[0],
515 "note1" : root[1],
516 "warn1" : root[4]
517 }
518 self.assertEquals(dic, expected)
519
526
550
552 XML = self.etree.XML
553
554 root = XML('<doc><one/><two>Two</two>Hm<three/></doc>')
555 result = []
556 for el in root:
557 result.append(el.tag)
558 self.assertEquals(['one', 'two', 'three'], result)
559
561 XML = self.etree.XML
562
563 root = XML('<doc></doc>')
564 result = []
565 for el in root:
566 result.append(el.tag)
567 self.assertEquals([], result)
568
570 XML = self.etree.XML
571
572 root = XML('<doc>Text</doc>')
573 result = []
574 for el in root:
575 result.append(el.tag)
576 self.assertEquals([], result)
577
584
586 XML = self.etree.XML
587
588 try:
589 reversed(())
590 except NameError:
591
592 return
593
594 root = XML('<doc><one/><two>Two</two>Hm<three/></doc>')
595 result = []
596 for el in reversed(root):
597 result.append(el.tag)
598 self.assertEquals(['three', 'two', 'one'], result)
599
601 XML = self.etree.XML
602
603 root = XML('<doc><one/><two>Two</two>Hm<three/></doc>')
604 result = []
605 add = True
606 for el in root:
607 result.append(el.tag)
608 if add:
609 self.etree.SubElement(root, 'four')
610 add = False
611 self.assertEquals(['one', 'two', 'three', 'four'], result)
612
614 XML = self.etree.XML
615
616 root = XML('<doc><one/><two>Two</two>Hm<three/></doc>')
617 result = []
618 for el in root:
619 result.append(el.tag)
620 del root[-1]
621 self.assertEquals(['one', 'two'], result)
622
624 XML = self.etree.XML
625
626 root = XML('<doc><one/><two/></doc>')
627 result = []
628 for el0 in root:
629 result.append(el0.tag)
630 for el1 in root:
631 result.append(el1.tag)
632 self.assertEquals(['one','one', 'two', 'two', 'one', 'two'], result)
633
635 XML = self.etree.XML
636
637 root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma" />')
638 result = []
639 for key in root.attrib:
640 result.append(key)
641 result.sort()
642 self.assertEquals(['alpha', 'beta', 'gamma'], result)
643
645 XML = self.etree.XML
646 root = XML('<a><b><c/></b><b/><c><b/></c></a>')
647 self.assertEquals(len(root.findall("c")), 1)
648 self.assertEquals(len(root.findall(".//c")), 2)
649 self.assertEquals(len(root.findall(".//b")), 3)
650 self.assertEquals(len(root.findall(".//b")[0]), 1)
651 self.assertEquals(len(root.findall(".//b")[1]), 0)
652 self.assertEquals(len(root.findall(".//b")[2]), 0)
653
655 XML = self.etree.XML
656 root = XML('<a xmlns:x="X" xmlns:y="Y"><x:b><c/></x:b><b/><c><x:b/><b/></c><b/></a>')
657 self.assertEquals(len(root.findall(".//{X}b")), 2)
658 self.assertEquals(len(root.findall(".//b")), 3)
659 self.assertEquals(len(root.findall("b")), 2)
660
667
674
676 Element = self.etree.Element
677
678 el = Element('tag', {'{ns1}foo':'Foo', '{ns2}bar':'Bar'})
679 self.assertEquals('Foo', el.attrib['{ns1}foo'])
680 self.assertEquals('Bar', el.attrib['{ns2}bar'])
681
690
699
701 ElementTree = self.etree.ElementTree
702 XML = self.etree.XML
703
704 for i in range(10):
705 f = StringIO()
706 root = XML('<doc%s>This is a test.</doc%s>' % (i, i))
707 tree = ElementTree(element=root)
708 tree.write(f)
709 data = f.getvalue()
710 self.assertEquals(
711 '<doc%s>This is a test.</doc%s>' % (i, i),
712 canonicalize(data))
713
721
722
723
725 Element = self.etree.Element
726
727 element = Element('tag')
728 for i in range(10):
729 element.attrib['key'] = 'value'
730 value = element.attrib['key']
731 self.assertEquals(value, 'value')
732
733
745
768
769 - def test_set_text(self):
770 Element = self.etree.Element
771 SubElement = self.etree.SubElement
772
773 a = Element('a')
774 b = SubElement(a, 'b')
775 a.text = 'hoi'
776 self.assertEquals(
777 'hoi',
778 a.text)
779 self.assertEquals(
780 'b',
781 a[0].tag)
782
783 - def test_set_text2(self):
784 Element = self.etree.Element
785 SubElement = self.etree.SubElement
786
787 a = Element('a')
788 a.text = 'hoi'
789 b = SubElement(a ,'b')
790 self.assertEquals(
791 'hoi',
792 a.text)
793 self.assertEquals(
794 'b',
795 a[0].tag)
796
798 Element = self.etree.Element
799
800 a = Element('a')
801
802 a.text = 'foo'
803 a.text = None
804
805 self.assertEquals(
806 None,
807 a.text)
808 self.assertXML('<a></a>', a)
809
811 Element = self.etree.Element
812
813 a = Element('a')
814 self.assertEquals(None, a.text)
815
816 a.text = ''
817 self.assertEquals('', a.text)
818 self.assertXML('<a></a>', a)
819
834
844
856
866
876
888
897
909
921
923 ProcessingInstruction = self.etree.ProcessingInstruction
924 pi = ProcessingInstruction('foo')
925 self.assertEquals({}, pi.attrib)
926 self.assertEquals([], pi.keys())
927 self.assertEquals([], pi.items())
928 self.assertEquals(None, pi.get('hoi'))
929 self.assertEquals(0, len(pi))
930
931 for i in pi:
932 pass
933
949
967
977
986
1001
1018
1036
1055
1061
1062 a = Element("a")
1063 a.tag = strTest("TAG")
1064 self.assertXML('<TAG></TAG>',
1065 a)
1066
1096
1098 Element = self.etree.Element
1099 SubElement = self.etree.SubElement
1100
1101 a = Element('a')
1102 b = SubElement(a, 'b')
1103 bs = SubElement(b, 'bs')
1104 c = SubElement(a, 'c')
1105 cs = SubElement(c, 'cs')
1106
1107 el = a[0]
1108 self.assertXML(
1109 '<a><b><bs></bs></b><c><cs></cs></c></a>',
1110 a)
1111 self.assertXML('<b><bs></bs></b>', b)
1112 self.assertXML('<c><cs></cs></c>', c)
1113
1114 del a[0]
1115 self.assertXML(
1116 '<a><c><cs></cs></c></a>',
1117 a)
1118 self.assertXML('<b><bs></bs></b>', b)
1119 self.assertXML('<c><cs></cs></c>', c)
1120
1121 a.insert(0, el)
1122 self.assertXML(
1123 '<a><b><bs></bs></b><c><cs></cs></c></a>',
1124 a)
1125 self.assertXML('<b><bs></bs></b>', b)
1126 self.assertXML('<c><cs></cs></c>', c)
1127
1146
1165
1167 XML = self.etree.XML
1168 a = XML('<a><b></b>B2<c></c>C2</a>')
1169 b, c = a
1170
1171 del a[:]
1172
1173 self.assertEquals("B2", b.tail)
1174 self.assertEquals("C2", c.tail)
1175
1177 XML = self.etree.XML
1178 a = XML('<a><b></b>B2<c></c>C2</a>')
1179 b, c = a
1180
1181 a[:] = []
1182
1183 self.assertEquals("B2", b.tail)
1184 self.assertEquals("C2", c.tail)
1185
1195
1197 Element = self.etree.Element
1198
1199 a = Element('a')
1200 a.text = 'foo'
1201 a.tail = 'bar'
1202 a.set('hoi', 'dag')
1203 a.clear()
1204 self.assertEquals(None, a.text)
1205 self.assertEquals(None, a.tail)
1206 self.assertEquals(None, a.get('hoi'))
1207 self.assertEquals('a', a.tag)
1208
1210 Element = self.etree.Element
1211 SubElement = self.etree.SubElement
1212
1213 a = Element('a')
1214 a.text = 'foo'
1215 a.tail = 'bar'
1216 a.set('hoi', 'dag')
1217 b = SubElement(a, 'b')
1218 c = SubElement(b, 'c')
1219 a.clear()
1220 self.assertEquals(None, a.text)
1221 self.assertEquals(None, a.tail)
1222 self.assertEquals(None, a.get('hoi'))
1223 self.assertEquals('a', a.tag)
1224 self.assertEquals(0, len(a))
1225 self.assertXML('<a></a>',
1226 a)
1227 self.assertXML('<b><c></c></b>',
1228 b)
1229
1239
1266
1282
1299
1314
1330
1346
1357
1370
1392
1401
1403 Element = self.etree.Element
1404 SubElement = self.etree.SubElement
1405
1406 a = Element('a')
1407 b = SubElement(a, 'b')
1408 c = SubElement(a, 'c')
1409 d = SubElement(b, 'd')
1410 e = SubElement(c, 'e')
1411
1412 self.assertEquals(
1413 [a, b, d, c, e],
1414 list(a.getiterator()))
1415 self.assertEquals(
1416 [d],
1417 list(d.getiterator()))
1418
1438
1459
1473
1498
1500 Element = self.etree.Element
1501 PI = self.etree.ProcessingInstruction
1502 SubElement = self.etree.SubElement
1503
1504 a = Element('a')
1505 b = SubElement(a, 'b')
1506 pi_b = PI("TEST-b")
1507 b.append(pi_b)
1508
1509 self.assertEquals(
1510 [pi_b],
1511 list(a.getiterator(PI)))
1512
1513 pi_a = PI("TEST-a")
1514 a.append(pi_a)
1515
1516 self.assertEquals(
1517 [pi_b, pi_a],
1518 list(a.getiterator(PI)))
1519
1520 self.assertEquals(
1521 [pi_b],
1522 list(b.getiterator(PI)))
1523
1525 Element = self.etree.Element
1526 SubElement = self.etree.SubElement
1527
1528 a = Element('a')
1529 a.text = 'a'
1530 b = SubElement(a, 'b')
1531 b.text = 'b'
1532 b.tail = 'b1'
1533 c = SubElement(a, 'c')
1534 c.text = 'c'
1535 c.tail = 'c1'
1536 d = SubElement(b, 'd')
1537 c.text = 'd'
1538 c.tail = 'd1'
1539 e = SubElement(c, 'e')
1540 e.text = 'e'
1541 e.tail = 'e1'
1542
1543 self.assertEquals(
1544 [a, b, d, c, e],
1545 list(a.getiterator()))
1546
1547
1548
1549
1551 Element = self.etree.Element
1552 SubElement = self.etree.SubElement
1553
1554 a = Element('a')
1555 a.text = 'a'
1556 b = SubElement(a, 'b')
1557 b.text = 'b'
1558 b.tail = 'b1'
1559 c = SubElement(a, 'c')
1560 c.text = 'c'
1561 c.tail = 'c1'
1562 d = SubElement(b, 'd')
1563 c.text = 'd'
1564 c.tail = 'd1'
1565 e = SubElement(c, 'e')
1566 e.text = 'e'
1567 e.tail = 'e1'
1568
1569 self.assertEquals(
1570 [a],
1571 list(a.getiterator('a')))
1572 a2 = SubElement(e, 'a')
1573 self.assertEquals(
1574 [a, a2],
1575 list(a.getiterator('a')))
1576 self.assertEquals(
1577 [a2],
1578 list(e.getiterator('a')))
1579
1589
1591 Element = self.etree.Element
1592 SubElement = self.etree.SubElement
1593
1594 a = Element('a')
1595 b = SubElement(a, 'b')
1596 c = SubElement(a, 'c')
1597 d = SubElement(a, 'd')
1598
1599 self.assertEquals(
1600 [b, c],
1601 a[0:2])
1602 self.assertEquals(
1603 [b, c, d],
1604 a[:])
1605 self.assertEquals(
1606 [b, c, d],
1607 a[:10])
1608 self.assertEquals(
1609 [b],
1610 a[0:1])
1611 self.assertEquals(
1612 [],
1613 a[10:12])
1614
1616 Element = self.etree.Element
1617 SubElement = self.etree.SubElement
1618
1619 a = Element('a')
1620 b = SubElement(a, 'b')
1621 c = SubElement(a, 'c')
1622 d = SubElement(a, 'd')
1623
1624 self.assertEquals(
1625 [d],
1626 a[-1:])
1627 self.assertEquals(
1628 [c, d],
1629 a[-2:])
1630 self.assertEquals(
1631 [c],
1632 a[-2:-1])
1633 self.assertEquals(
1634 [b, c],
1635 a[-3:-1])
1636 self.assertEquals(
1637 [b, c],
1638 a[-3:2])
1639
1641 ElementTree = self.etree.ElementTree
1642
1643 f = StringIO('<a><b>B</b>B1<c>C</c>C1</a>')
1644 doc = ElementTree(file=f)
1645 a = doc.getroot()
1646 b = a[0]
1647 c = a[1]
1648 self.assertEquals(
1649 [b, c],
1650 a[:])
1651 self.assertEquals(
1652 [b],
1653 a[0:1])
1654 self.assertEquals(
1655 [c],
1656 a[1:])
1657
1681
1696
1711
1726
1728 ElementTree = self.etree.ElementTree
1729 f = StringIO('<a><b></b>B2<c></c>C2<d></d>D2<e></e>E2</a>')
1730 doc = ElementTree(file=f)
1731 a = doc.getroot()
1732 del a[1:3]
1733 self.assertXML(
1734 '<a><b></b>B2<e></e>E2</a>',
1735 a)
1736
1747
1749 Element = self.etree.Element
1750 SubElement = self.etree.SubElement
1751
1752 a = Element('a')
1753 b = SubElement(a, 'b')
1754 c = SubElement(a, 'c')
1755 d = SubElement(a, 'd')
1756
1757 e = Element('e')
1758 f = Element('f')
1759 g = Element('g')
1760
1761 s = [e, f, g]
1762 a[1:2] = s
1763 self.assertEquals(
1764 [b, e, f, g, d],
1765 list(a))
1766
1783
1800
1802 Element = self.etree.Element
1803 SubElement = self.etree.SubElement
1804
1805 a = Element('a')
1806 b = SubElement(a, 'b')
1807 c = SubElement(a, 'c')
1808 d = SubElement(a, 'd')
1809
1810 e = Element('e')
1811 f = Element('f')
1812 g = Element('g')
1813
1814 s = [e, f, g]
1815 a[3:] = s
1816 self.assertEquals(
1817 [b, c, d, e, f, g],
1818 list(a))
1819
1832
1842
1858
1877
1879 ElementTree = self.etree.ElementTree
1880 ns = 'http://xml.infrae.com/1'
1881 f = StringIO('<x:a xmlns:x="%s"><x:b></x:b></x:a>' % ns)
1882 t = ElementTree(file=f)
1883 a = t.getroot()
1884 self.assertEquals('{%s}a' % ns,
1885 a.tag)
1886 self.assertEquals('{%s}b' % ns,
1887 a[0].tag)
1888
1890 ElementTree = self.etree.ElementTree
1891 ns = 'http://xml.infrae.com/1'
1892 ns2 = 'http://xml.infrae.com/2'
1893 f = StringIO('<x:a xmlns:x="%s" xmlns:y="%s"><x:b></x:b><y:b></y:b></x:a>' % (ns, ns2))
1894 t = ElementTree(file=f)
1895 a = t.getroot()
1896 self.assertEquals('{%s}a' % ns,
1897 a.tag)
1898 self.assertEquals('{%s}b' % ns,
1899 a[0].tag)
1900 self.assertEquals('{%s}b' % ns2,
1901 a[1].tag)
1902
1904 Element = self.etree.Element
1905 SubElement = self.etree.SubElement
1906 ns = 'http://xml.infrae.com/1'
1907 ns2 = 'http://xml.infrae.com/2'
1908 a = Element('{%s}a' % ns)
1909 b = SubElement(a, '{%s}b' % ns2)
1910 c = SubElement(a, '{%s}c' % ns)
1911 self.assertEquals('{%s}a' % ns,
1912 a.tag)
1913 self.assertEquals('{%s}b' % ns2,
1914 b.tag)
1915 self.assertEquals('{%s}c' % ns,
1916 c.tag)
1917 self.assertEquals('{%s}a' % ns,
1918 a.tag)
1919 self.assertEquals('{%s}b' % ns2,
1920 b.tag)
1921 self.assertEquals('{%s}c' % ns,
1922 c.tag)
1923
1925 Element = self.etree.Element
1926 SubElement = self.etree.SubElement
1927 ElementTree = self.etree.ElementTree
1928
1929 ns = 'http://xml.infrae.com/1'
1930 ns2 = 'http://xml.infrae.com/2'
1931 f = StringIO('<a xmlns="%s" xmlns:x="%s"><x:b></x:b><b></b></a>' % (ns, ns2))
1932 t = ElementTree(file=f)
1933
1934 a = t.getroot()
1935 self.assertEquals('{%s}a' % ns,
1936 a.tag)
1937 self.assertEquals('{%s}b' % ns2,
1938 a[0].tag)
1939 self.assertEquals('{%s}b' % ns,
1940 a[1].tag)
1941
1943 Element = self.etree.Element
1944 ns = 'http://xml.infrae.com/1'
1945 ns2 = 'http://xml.infrae.com/2'
1946 a = Element('a')
1947 a.set('{%s}foo' % ns, 'Foo')
1948 a.set('{%s}bar' % ns2, 'Bar')
1949 self.assertEquals(
1950 'Foo',
1951 a.get('{%s}foo' % ns))
1952 self.assertEquals(
1953 'Bar',
1954 a.get('{%s}bar' % ns2))
1955 self.assertXML(
1956 '<a xmlns:ns0="%s" xmlns:ns1="%s" ns0:foo="Foo" ns1:bar="Bar"></a>' % (ns, ns2),
1957 a)
1958
1973
1975 tostring = self.etree.tostring
1976 root = self.etree.XML(
1977 '<foo><bar xmlns:ns="http://a.b.c"><ns:baz/></bar></foo>')
1978 baz = root[0][0]
1979
1980 nsdecl = re.findall("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']",
1981 tostring(baz))
1982 self.assertEquals(["http://a.b.c"], nsdecl)
1983
1985 tostring = self.etree.tostring
1986 root = self.etree.XML(
1987 '<foo><bar xmlns="http://a.b.c"><baz/></bar></foo>')
1988 baz = root[0][0]
1989
1990 nsdecl = re.findall("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']",
1991 tostring(baz))
1992 self.assertEquals(["http://a.b.c"], nsdecl)
1993
1995 tostring = self.etree.tostring
1996 root = self.etree.XML(
1997 '<foo xmlns:ns="http://a.b.c"><bar><ns:baz/></bar></foo>')
1998 baz = root[0][0]
1999
2000 nsdecl = re.findall("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']",
2001 tostring(baz))
2002
2003 self.assertEquals(["http://a.b.c"], nsdecl)
2004
2006 Element = self.etree.Element
2007
2008 root = Element('element')
2009
2010 subelement = Element('subelement',
2011 {"{http://www.w3.org/XML/1998/namespace}id": "foo"})
2012 self.assertEquals(1, len(subelement.attrib))
2013 self.assertEquals(
2014 "foo",
2015 subelement.get("{http://www.w3.org/XML/1998/namespace}id"))
2016
2017 root.append(subelement)
2018 self.assertEquals(1, len(subelement.attrib))
2019 self.assertEquals(
2020 {"{http://www.w3.org/XML/1998/namespace}id" : "foo"}.items(),
2021 subelement.attrib.items())
2022 self.assertEquals(
2023 "foo",
2024 subelement.get("{http://www.w3.org/XML/1998/namespace}id"))
2025
2037
2051
2065
2067 iterparse = self.etree.iterparse
2068 f = StringIO('<a><b></b><c/></a>')
2069
2070 iterator = iterparse(f)
2071 self.assertEquals(None,
2072 iterator.root)
2073 events = list(iterator)
2074 root = iterator.root
2075 self.assertEquals(
2076 [('end', root[0]), ('end', root[1]), ('end', root)],
2077 events)
2078
2080 iterparse = self.etree.iterparse
2081 iterator = iterparse(fileInTestDir("test.xml"))
2082 self.assertEquals(None,
2083 iterator.root)
2084 events = list(iterator)
2085 root = iterator.root
2086 self.assertEquals(
2087 [('end', root[0]), ('end', root)],
2088 events)
2089
2091 iterparse = self.etree.iterparse
2092 f = StringIO('<a><b></b><c/></a>')
2093
2094 iterator = iterparse(f, events=('start',))
2095 events = list(iterator)
2096 root = iterator.root
2097 self.assertEquals(
2098 [('start', root), ('start', root[0]), ('start', root[1])],
2099 events)
2100
2102 iterparse = self.etree.iterparse
2103 f = StringIO('<a><b></b><c/></a>')
2104
2105 iterator = iterparse(f, events=('start','end'))
2106 events = list(iterator)
2107 root = iterator.root
2108 self.assertEquals(
2109 [('start', root), ('start', root[0]), ('end', root[0]),
2110 ('start', root[1]), ('end', root[1]), ('end', root)],
2111 events)
2112
2114 iterparse = self.etree.iterparse
2115 f = StringIO('<a><b></b><c/></a>')
2116
2117 iterator = iterparse(f)
2118 for event, elem in iterator:
2119 elem.clear()
2120
2121 root = iterator.root
2122 self.assertEquals(0,
2123 len(root))
2124
2126 iterparse = self.etree.iterparse
2127 CHILD_COUNT = 12345
2128 f = StringIO('<a>' + ('<b>test</b>'*CHILD_COUNT) + '</a>')
2129
2130 i = 0
2131 for key in iterparse(f):
2132 event, element = key
2133 i += 1
2134 self.assertEquals(i, CHILD_COUNT + 1)
2135
2137 iterparse = self.etree.iterparse
2138 f = StringIO('<a xmlns="ns1"><b><c xmlns="ns2"/></b></a>')
2139
2140 attr_name = '{testns}bla'
2141 events = []
2142 iterator = iterparse(f, events=('start','end','start-ns','end-ns'))
2143 for event, elem in iterator:
2144 events.append(event)
2145 if event == 'start':
2146 if elem.tag != '{ns1}a':
2147 elem.set(attr_name, 'value')
2148
2149 self.assertEquals(
2150 ['start-ns', 'start', 'start', 'start-ns', 'start',
2151 'end', 'end-ns', 'end', 'end', 'end-ns'],
2152 events)
2153
2154 root = iterator.root
2155 self.assertEquals(
2156 None,
2157 root.get(attr_name))
2158 self.assertEquals(
2159 'value',
2160 root[0].get(attr_name))
2161
2163 iterparse = self.etree.iterparse
2164 f = StringIO('<a><b><d/></b><c/></a>')
2165
2166 counts = []
2167 for event, elem in iterparse(f):
2168 counts.append(len(list(elem.getiterator())))
2169 self.assertEquals(
2170 [1,2,1,4],
2171 counts)
2172
2180
2184
2194
2196 parse = self.etree.parse
2197
2198 f = StringIO('<a><b></b></a>')
2199 tree = parse(f)
2200 f.close()
2201 self.assertXML(
2202 '<a><b></b></a>',
2203 tree.getroot()
2204 )
2205
2207
2208 parse = self.etree.parse
2209 tree = parse(StringIO('<?xml version="1.0" encoding="ascii"?><html/>'))
2210 self.assertXML('<html></html>',
2211 tree.getroot())
2212
2221
2234
2242
2244 parse = self.etree.parse
2245
2246 f = open(fileInTestDir('test-string.xml'), 'r')
2247 tree = parse(f)
2248 f.close()
2249 self.assertXML(
2250 u'<a>Søk på nettet</a>'.encode('UTF-8'),
2251 tree.getroot(), 'UTF-8')
2252
2254 ElementTree = self.etree.ElementTree
2255 Element = self.etree.Element
2256
2257 a = Element('a')
2258 a.text = u'Søk på nettet'
2259
2260 f = StringIO()
2261 tree = ElementTree(element=a)
2262 tree.write(f, 'iso-8859-1')
2263 result = f.getvalue()
2264 declaration = "<?xml version=\'1.0\' encoding=\'iso-8859-1\'?>"
2265 self.assertEncodingDeclaration(result,'iso-8859-1')
2266 result = result.split('?>', 1)[-1]
2267 if result[0] == '\n':
2268 result = result[1:]
2269 self.assertEquals(u'<a>Søk på nettet</a>'.encode('iso-8859-1'),
2270 result)
2271
2272
2274 XML = self.etree.XML
2275 test_utf = u'<?xml version=\'1.0\' encoding=\'iso-8859-1\'?><a>Søk på nettet</a>'
2276 self.assertRaises(SyntaxError, XML, test_utf)
2277
2292
2301
2309
2320
2332
2345
2359
2361 utext = u'Søk på nettet'
2362 uxml = u'<p>%s</p>' % utext
2363 prologue = '<?xml version="1.0" encoding="iso-8859-1" ?>'
2364 isoxml = prologue + uxml.encode('iso-8859-1')
2365 tree = self.etree.XML(isoxml)
2366 self.assertEquals(utext, tree.text)
2367
2369 utext = u'Søk på nettet'
2370 uxml = u'<p>%s</p>' % utext
2371 prologue = '<?xml version="1.0" encoding="iso-8859-1" ?>'
2372 isoxml = prologue + uxml.encode('iso-8859-1')
2373 el = self.etree.parse(StringIO(isoxml)).getroot()
2374 self.assertEquals(utext, el.text)
2375
2389
2391 Element = self.etree.Element
2392
2393 a = Element('a')
2394 a.text = 'Foo'
2395
2396 b = copy.deepcopy(a)
2397 self.assertEquals('Foo', b.text)
2398
2399 b.text = 'Bar'
2400 self.assertEquals('Bar', b.text)
2401 self.assertEquals('Foo', a.text)
2402
2403 del a
2404 self.assertEquals('Bar', b.text)
2405
2407 Element = self.etree.Element
2408
2409 a = Element('a')
2410 a.tail = 'Foo'
2411
2412 b = copy.deepcopy(a)
2413 self.assertEquals('Foo', b.tail)
2414
2415 b.tail = 'Bar'
2416 self.assertEquals('Bar', b.tail)
2417 self.assertEquals('Foo', a.tail)
2418
2419 del a
2420 self.assertEquals('Bar', b.tail)
2421
2423 Element = self.etree.Element
2424 SubElement = self.etree.SubElement
2425
2426 root = Element('root')
2427 a = SubElement(root, 'a')
2428 a.text = 'FooText'
2429 a.tail = 'FooTail'
2430
2431 b = copy.deepcopy(a)
2432 self.assertEquals('FooText', b.text)
2433 self.assertEquals('FooTail', b.tail)
2434
2435 b.text = 'BarText'
2436 b.tail = 'BarTail'
2437 self.assertEquals('BarTail', b.tail)
2438 self.assertEquals('FooTail', a.tail)
2439 self.assertEquals('BarText', b.text)
2440 self.assertEquals('FooText', a.text)
2441
2442 del a
2443 self.assertEquals('BarTail', b.tail)
2444 self.assertEquals('BarText', b.text)
2445
2447 root = self.etree.XML('''<doc xmlns="dns" xmlns:t="tns">
2448 <parent><node t:foo="bar" /></parent>
2449 </doc>''')
2450 self.assertEquals(
2451 root[0][0].get('{tns}foo'),
2452 copy.deepcopy(root[0])[0].get('{tns}foo') )
2453 self.assertEquals(
2454 root[0][0].get('{tns}foo'),
2455 copy.deepcopy(root[0][0]).get('{tns}foo') )
2456
2471
2473 Element = self.etree.Element
2474
2475 a = Element('a')
2476 a.text = 'Foo'
2477
2478 b = copy.copy(a)
2479 self.assertEquals('Foo', b.text)
2480
2481 b.text = 'Bar'
2482 self.assertEquals('Bar', b.text)
2483 self.assertEquals('Foo', a.text)
2484
2485
2498
2500 etree = self.etree
2501 e = etree.Element('foo')
2502 self.assertEquals(False, bool(e))
2503 etree.SubElement(e, 'bar')
2504 self.assertEquals(True, bool(e))
2505 e = etree.Element('foo')
2506 e.text = 'hey'
2507 self.assertEquals(False, bool(e))
2508 e = etree.Element('foo')
2509 e.tail = 'bar'
2510 self.assertEquals(False, bool(e))
2511 e = etree.Element('foo')
2512 e.set('bar', 'Bar')
2513 self.assertEquals(False, bool(e))
2514
2532
2540
2542 etree = self.etree
2543 qname1 = etree.QName('myns', 'a')
2544 qname2 = etree.QName('myns', 'a')
2545 self.assertEquals(qname1, "{myns}a")
2546 self.assertEquals("{myns}a", qname2)
2547 self.assertEquals(qname1, qname1)
2548 self.assertEquals(qname1, qname2)
2549
2551 """Write out element for comparison.
2552 """
2553 ElementTree = self.etree.ElementTree
2554 f = StringIO()
2555 tree = ElementTree(element=element)
2556 tree.write(f, encoding)
2557 data = unicode(f.getvalue(), encoding)
2558 return canonicalize(data)
2559
2561 """Write out element for comparison, using real file.
2562 """
2563 ElementTree = self.etree.ElementTree
2564 handle, filename = tempfile.mkstemp()
2565 try:
2566 f = open(filename, 'wb')
2567 tree = ElementTree(element=element)
2568 tree.write(f, encoding)
2569 f.close()
2570 f = open(filename, 'rb')
2571 data = unicode(f.read(), encoding)
2572 f.close()
2573 finally:
2574 os.close(handle)
2575 os.remove(filename)
2576 return canonicalize(data)
2577
2578 - def assertXML(self, expected, element, encoding='us-ascii'):
2579 """Writes element out and checks whether it is expected.
2580
2581 Does this two ways; once using StringIO, once using a real file.
2582 """
2583 self.assertEquals(expected, self._writeElement(element, encoding))
2584 self.assertEquals(expected, self._writeElementFile(element, encoding))
2585
2587 "Checks if the result XML byte string specifies the encoding."
2588 has_encoding = re.compile(r"<\?xml[^>]+ encoding=[\"']([^\"']+)[\"']").match
2589 self.assert_(has_encoding(result))
2590 result_encoding = has_encoding(result).group(1)
2591 self.assertEquals(result_encoding.upper(), encoding.upper())
2592
2594 return self.etree.tostring(tree.getroot()).replace(' ', '').replace('\n', '')
2595
2598
2600 self.assert_(hasattr(element, 'tag'))
2601 self.assert_(hasattr(element, 'attrib'))
2602 self.assert_(hasattr(element, 'text'))
2603 self.assert_(hasattr(element, 'tail'))
2604 self._check_string(element.tag)
2605 self._check_mapping(element.attrib)
2606 if element.text != None:
2607 self._check_string(element.text)
2608 if element.tail != None:
2609 self._check_string(element.tail)
2610
2612 len(string)
2613 for char in string:
2614 self.assertEquals(1, len(char))
2615 new_string = string + ""
2616 new_string = string + " "
2617 string[:0]
2618
2620 len(mapping)
2621 keys = mapping.keys()
2622 items = mapping.items()
2623 for key in keys:
2624 item = mapping[key]
2625 mapping["key"] = "value"
2626 self.assertEquals("value", mapping["key"])
2627
2628
2631
2632 if ElementTree:
2635
2642
2643 if __name__ == '__main__':
2644 unittest.main()
2645