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, tempfile, copy, operator, gc
13
14 from common_imports import StringIO, etree, ElementTree, cElementTree
15 from common_imports import fileInTestDir, canonicalize, HelperTestCase
16
17 if cElementTree is not None:
18 if tuple([int(n) for n in
19 getattr(cElementTree, "VERSION", "0.0").split(".")]) <= (1,0,7):
20 cElementTree = None
21
22 try:
23 reversed
24 except NameError:
25
27 seq = list(seq)[::-1]
28 return seq
29
31 etree = None
32
34 for i in range(10):
35 e = self.etree.Element('foo')
36 self.assertEquals(e.tag, 'foo')
37 self.assertEquals(e.text, None)
38 self.assertEquals(e.tail, None)
39
52
65
83
85 ElementTree = self.etree.ElementTree
86
87 f = StringIO('<doc>Test<one>One</one></doc>')
88 doc = ElementTree(file=f)
89 root = doc.getroot()
90 self.assertEquals(1, len(root))
91 self.assertEquals('one', root[0].tag)
92 self.assertRaises(IndexError, operator.getitem, root, 1)
93
95 ElementTree = self.etree.ElementTree
96
97 f = StringIO('<doc><one>One</one><two>Two</two>hm<three>Three</three></doc>')
98 doc = ElementTree(file=f)
99 root = doc.getroot()
100 self.assertEquals(3, len(root))
101 self.assertEquals('one', root[0].tag)
102 self.assertEquals('two', root[1].tag)
103 self.assertEquals('three', root[2].tag)
104
106 ElementTree = self.etree.ElementTree
107
108 f = StringIO('<doc>Test</doc>')
109 doc = ElementTree(file=f)
110 root = doc.getroot()
111 self.assertEquals(0, len(root))
112
114 Element = self.etree.Element
115 SubElement = self.etree.SubElement
116 a = Element('a')
117 b = SubElement(a, 'b')
118 c = SubElement(a, 'c')
119 d = SubElement(a, 'd')
120 self.assertEquals(d, a[-1])
121 self.assertEquals(c, a[-2])
122 self.assertEquals(b, a[-3])
123 self.assertRaises(IndexError, operator.getitem, a, -4)
124 a[-1] = e = Element('e')
125 self.assertEquals(e, a[-1])
126 del a[-1]
127 self.assertEquals(2, len(a))
128
138
139 - def test_text(self):
140 ElementTree = self.etree.ElementTree
141
142 f = StringIO('<doc>This is a text</doc>')
143 doc = ElementTree(file=f)
144 root = doc.getroot()
145 self.assertEquals('This is a text', root.text)
146
147 - def test_text_empty(self):
148 ElementTree = self.etree.ElementTree
149
150 f = StringIO('<doc></doc>')
151 doc = ElementTree(file=f)
152 root = doc.getroot()
153 self.assertEquals(None, root.text)
154
155 - def test_text_other(self):
156 ElementTree = self.etree.ElementTree
157
158 f = StringIO('<doc><one>One</one></doc>')
159 doc = ElementTree(file=f)
160 root = doc.getroot()
161 self.assertEquals(None, root.text)
162 self.assertEquals('One', root[0].text)
163
165 ElementTree = self.etree.ElementTree
166
167 f = StringIO('<doc>This is > than a text</doc>')
168 doc = ElementTree(file=f)
169 root = doc.getroot()
170 self.assertEquals('This is > than a text', root.text)
171
173 Element = self.etree.Element
174
175 a = Element("a")
176 a.text = "<>&"
177 self.assertXML('<a><>&</a>',
178 a)
179
181 tostring = self.etree.tostring
182 Element = self.etree.Element
183
184 a = Element("a")
185 a.text = "<>&"
186 self.assertEquals('<a><>&</a>',
187 tostring(a))
188
190 Element = self.etree.Element
191
192 class strTest(str):
193 pass
194
195 a = Element("a")
196 a.text = strTest("text")
197 self.assertXML('<a>text</a>',
198 a)
199
211
218
219 a = Element("a")
220 SubElement(a, "t").tail = strTest("tail")
221 self.assertXML('<a><t></t>tail</a>',
222 a)
223
225
226 XML = self.etree.XML
227
228 root = XML('<doc>This is <i>mixed</i> content.</doc>')
229 self.assertEquals(1, len(root))
230 self.assertEquals('This is ', root.text)
231 self.assertEquals(None, root.tail)
232 self.assertEquals('mixed', root[0].text)
233 self.assertEquals(' content.', root[0].tail)
234
235 del root[0].tail
236
237 self.assertEquals(1, len(root))
238 self.assertEquals('This is ', root.text)
239 self.assertEquals(None, root.tail)
240 self.assertEquals('mixed', root[0].text)
241 self.assertEquals(None, root[0].tail)
242
243 root[0].tail = "TAIL"
244
245 self.assertEquals(1, len(root))
246 self.assertEquals('This is ', root.text)
247 self.assertEquals(None, root.tail)
248 self.assertEquals('mixed', root[0].text)
249 self.assertEquals('TAIL', root[0].tail)
250
260
270
281
283 ElementTree = self.etree.ElementTree
284
285 f = StringIO('<doc one="One" two="Two"/>')
286 doc = ElementTree(file=f)
287 root = doc.getroot()
288 self.assertEquals('One', root.get('one'))
289 self.assertEquals('Two', root.get('two'))
290 self.assertEquals(None, root.get('three'))
291 self.assertEquals('foo', root.get('three', 'foo'))
292
294 XML = self.etree.XML
295
296 root = XML('<doc one="One" two="Two"/>')
297 self.assertEquals('One', root.get('one'))
298 self.assertEquals('Two', root.get('two'))
299 root.attrib.clear()
300 self.assertEquals(None, root.get('one'))
301 self.assertEquals(None, root.get('two'))
302
304 Element = self.etree.Element
305
306 root = Element("root", one="One")
307 root.set("two", "Two")
308 self.assertEquals('One', root.get('one'))
309 self.assertEquals('Two', root.get('two'))
310 root.attrib.clear()
311 self.assertEquals(None, root.get('one'))
312 self.assertEquals(None, root.get('two'))
313
315 Element = self.etree.Element
316 SubElement = self.etree.SubElement
317
318 attribNS = '{http://foo/bar}x'
319
320 parent = Element('parent')
321 parent.set(attribNS, 'a')
322 child = SubElement(parent, 'child')
323 child.set(attribNS, 'b')
324
325 self.assertEquals('a', parent.get(attribNS))
326 self.assertEquals('b', child.get(attribNS))
327
328 parent.clear()
329 self.assertEquals(None, parent.get(attribNS))
330 self.assertEquals('b', child.get(attribNS))
331
333 XML = self.etree.XML
334
335 root = XML('<doc alpha="Alpha" beta="Beta"/>')
336 items = root.attrib.items()
337 items.sort()
338 self.assertEquals(
339 [('alpha', 'Alpha'), ('beta', 'Beta')],
340 items)
341
342 root.attrib.update({'alpha' : 'test', 'gamma' : 'Gamma'})
343
344 items = root.attrib.items()
345 items.sort()
346 self.assertEquals(
347 [('alpha', 'test'), ('beta', 'Beta'), ('gamma', 'Gamma')],
348 items)
349
351 XML = self.etree.XML
352
353 root = XML('<doc alpha="Alpha" beta="Beta"/>')
354 items = root.attrib.items()
355 items.sort()
356 self.assertEquals(
357 [('alpha', 'Alpha'), ('beta', 'Beta')],
358 items)
359
360 root.attrib.update({'alpha' : 'test', 'gamma' : 'Gamma'}.items())
361
362 items = root.attrib.items()
363 items.sort()
364 self.assertEquals(
365 [('alpha', 'test'), ('beta', 'Beta'), ('gamma', 'Gamma')],
366 items)
367
369 XML = self.etree.XML
370
371 root = XML('<doc alpha="Alpha" beta="Beta"/>')
372 items = root.attrib.items()
373 items.sort()
374 self.assertEquals(
375 [('alpha', 'Alpha'), ('beta', 'Beta')],
376 items)
377
378 root.attrib.update({'alpha' : 'test', 'gamma' : 'Gamma'}.iteritems())
379
380 items = root.attrib.items()
381 items.sort()
382 self.assertEquals(
383 [('alpha', 'test'), ('beta', 'Beta'), ('gamma', 'Gamma')],
384 items)
385
387 XML = self.etree.XML
388
389 root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')
390 keys = root.attrib.keys()
391 keys.sort()
392 self.assertEquals(['alpha', 'beta', 'gamma'], keys)
393
395 XML = self.etree.XML
396
397 root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')
398 keys = root.keys()
399 keys.sort()
400 self.assertEquals(['alpha', 'beta', 'gamma'], keys)
401
403 XML = self.etree.XML
404
405 root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')
406 items = root.items()
407 items.sort()
408 self.assertEquals(
409 [('alpha','Alpha'), ('beta','Beta'), ('gamma','Gamma')],
410 items)
411
413 XML = self.etree.XML
414
415 root = XML('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')
416 keys = root.keys()
417 keys.sort()
418 self.assertEquals(['bar', '{http://ns.codespeak.net/test}baz'],
419 keys)
420
422 XML = self.etree.XML
423
424 root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')
425 values = root.attrib.values()
426 values.sort()
427 self.assertEquals(['Alpha', 'Beta', 'Gamma'], values)
428
430 XML = self.etree.XML
431
432 root = XML('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')
433 values = root.attrib.values()
434 values.sort()
435 self.assertEquals(
436 ['Bar', 'Baz'], values)
437
439 XML = self.etree.XML
440
441 root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')
442 items = root.attrib.items()
443 items.sort()
444 self.assertEquals([
445 ('alpha', 'Alpha'),
446 ('beta', 'Beta'),
447 ('gamma', 'Gamma'),
448 ],
449 items)
450
452 XML = self.etree.XML
453
454 root = XML('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')
455 items = root.attrib.items()
456 items.sort()
457 self.assertEquals(
458 [('bar', 'Bar'), ('{http://ns.codespeak.net/test}baz', 'Baz')],
459 items)
460
462 XML = self.etree.XML
463
464 expected = "{'{http://ns.codespeak.net/test}baz': 'Baz', 'bar': 'Bar'}"
465 alternative = "{'bar': 'Bar', '{http://ns.codespeak.net/test}baz': 'Baz'}"
466
467 root = XML('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')
468 try:
469 self.assertEquals(expected, str(root.attrib))
470 except AssertionError:
471 self.assertEquals(alternative, str(root.attrib))
472
474 XML = self.etree.XML
475
476 root = XML('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')
477 self.assertEquals(
478 True, root.attrib.has_key('bar'))
479 self.assertEquals(
480 False, root.attrib.has_key('baz'))
481 self.assertEquals(
482 False, root.attrib.has_key('hah'))
483 self.assertEquals(
484 True,
485 root.attrib.has_key('{http://ns.codespeak.net/test}baz'))
486
488 XML = self.etree.XML
489
490 root = XML('<foo bar="Bar" xmlns:ns="http://ns.codespeak.net/test" ns:baz="Baz" />')
491 self.assertEquals(
492 True, 'bar' in root.attrib)
493 self.assertEquals(
494 False, 'baz' in root.attrib)
495 self.assertEquals(
496 False, 'hah' in root.attrib)
497 self.assertEquals(
498 True,
499 '{http://ns.codespeak.net/test}baz' in root.attrib)
500
507
509 XML = self.etree.XML
510
511 root = XML('<doc>This is a text.</doc>')
512 self.assertEquals(0, len(root))
513 self.assertEquals('This is a text.', root.text)
514
516 XMLID = self.etree.XMLID
517 XML = self.etree.XML
518 xml_text = '''
519 <document>
520 <h1 id="chapter1">...</h1>
521 <p id="note1" class="note">...</p>
522 <p>Regular paragraph.</p>
523 <p xml:id="xmlid">XML:ID paragraph.</p>
524 <p id="warn1" class="warning">...</p>
525 </document>
526 '''
527
528 root, dic = XMLID(xml_text)
529 root2 = XML(xml_text)
530 self.assertEquals(self._writeElement(root),
531 self._writeElement(root2))
532 expected = {
533 "chapter1" : root[0],
534 "note1" : root[1],
535 "warn1" : root[4]
536 }
537 self.assertEquals(dic, expected)
538
545
553
560
567
591
593 XML = self.etree.XML
594
595 root = XML('<doc><one/><two>Two</two>Hm<three/></doc>')
596 result = []
597 for el in root:
598 result.append(el.tag)
599 self.assertEquals(['one', 'two', 'three'], result)
600
602 XML = self.etree.XML
603
604 root = XML('<doc></doc>')
605 result = []
606 for el in root:
607 result.append(el.tag)
608 self.assertEquals([], result)
609
611 XML = self.etree.XML
612
613 root = XML('<doc>Text</doc>')
614 result = []
615 for el in root:
616 result.append(el.tag)
617 self.assertEquals([], result)
618
625
627 XML = self.etree.XML
628 root = XML('<doc><one/><two>Two</two>Hm<three/></doc>')
629 result = []
630 for el in reversed(root):
631 result.append(el.tag)
632 self.assertEquals(['three', 'two', 'one'], result)
633
635 XML = self.etree.XML
636
637 root = XML('<doc><one/><two>Two</two>Hm<three/></doc>')
638 result = []
639 add = True
640 for el in root:
641 result.append(el.tag)
642 if add:
643 self.etree.SubElement(root, 'four')
644 add = False
645 self.assertEquals(['one', 'two', 'three', 'four'], result)
646
648 XML = self.etree.XML
649
650 root = XML('<doc><one/><two>Two</two>Hm<three/></doc>')
651 result = []
652 for el in root:
653 result.append(el.tag)
654 del root[-1]
655 self.assertEquals(['one', 'two'], result)
656
658 XML = self.etree.XML
659
660 root = XML('<doc><one/><two/></doc>')
661 result = []
662 for el0 in root:
663 result.append(el0.tag)
664 for el1 in root:
665 result.append(el1.tag)
666 self.assertEquals(['one','one', 'two', 'two', 'one', 'two'], result)
667
669 XML = self.etree.XML
670
671 root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma" />')
672 result = []
673 for key in root.attrib:
674 result.append(key)
675 result.sort()
676 self.assertEquals(['alpha', 'beta', 'gamma'], result)
677
679 XML = self.etree.XML
680 root = XML('<a><b><c/></b><b/><c><b/></c></a>')
681 self.assertEquals(len(list(root.findall("c"))), 1)
682 self.assertEquals(len(list(root.findall(".//c"))), 2)
683 self.assertEquals(len(list(root.findall(".//b"))), 3)
684 self.assertEquals(len(list(root.findall(".//b"))[0]), 1)
685 self.assertEquals(len(list(root.findall(".//b"))[1]), 0)
686 self.assertEquals(len(list(root.findall(".//b"))[2]), 0)
687
689 XML = self.etree.XML
690 root = XML('<a xmlns:x="X" xmlns:y="Y"><x:b><c/></x:b><b/><c><x:b/><b/></c><b/></a>')
691 self.assertEquals(len(list(root.findall(".//{X}b"))), 2)
692 self.assertEquals(len(list(root.findall(".//b"))), 3)
693 self.assertEquals(len(list(root.findall("b"))), 2)
694
701
708
710 Element = self.etree.Element
711
712 el = Element('tag', {'{ns1}foo':'Foo', '{ns2}bar':'Bar'})
713 self.assertEquals('Foo', el.attrib['{ns1}foo'])
714 self.assertEquals('Bar', el.attrib['{ns2}bar'])
715
724
733
747
766
768 ElementTree = self.etree.ElementTree
769 Element = self.etree.Element
770 SubElement = self.etree.SubElement
771
772 a = Element('a')
773 a.text = "A"
774 a.tail = "tail"
775 b = SubElement(a, 'b')
776 b.text = "B"
777 b.tail = "TAIL"
778 c = SubElement(a, 'c')
779 c.text = "C"
780
781 tree = ElementTree(element=a)
782 f = StringIO()
783 tree.write(f, method="text")
784 data = f.getvalue()
785
786 self.assertEquals('ABTAILCtail',
787 data)
788
796
797
798
800 Element = self.etree.Element
801
802 element = Element('tag')
803 for i in range(10):
804 element.attrib['key'] = 'value'
805 value = element.attrib['key']
806 self.assertEquals(value, 'value')
807
808
820
843
844 - def test_set_text(self):
845 Element = self.etree.Element
846 SubElement = self.etree.SubElement
847
848 a = Element('a')
849 b = SubElement(a, 'b')
850 a.text = 'hoi'
851 self.assertEquals(
852 'hoi',
853 a.text)
854 self.assertEquals(
855 'b',
856 a[0].tag)
857
858 - def test_set_text2(self):
859 Element = self.etree.Element
860 SubElement = self.etree.SubElement
861
862 a = Element('a')
863 a.text = 'hoi'
864 b = SubElement(a ,'b')
865 self.assertEquals(
866 'hoi',
867 a.text)
868 self.assertEquals(
869 'b',
870 a[0].tag)
871
873 Element = self.etree.Element
874
875 a = Element('a')
876
877 a.text = 'foo'
878 a.text = None
879
880 self.assertEquals(
881 None,
882 a.text)
883 self.assertXML('<a></a>', a)
884
886 Element = self.etree.Element
887
888 a = Element('a')
889 self.assertEquals(None, a.text)
890
891 a.text = ''
892 self.assertEquals('', a.text)
893 self.assertXML('<a></a>', a)
894
909
919
931
941
951
963
972
984
996
1008
1010 ProcessingInstruction = self.etree.ProcessingInstruction
1011 pi = ProcessingInstruction('foo')
1012 self.assertEquals({}, pi.attrib)
1013 self.assertEquals([], pi.keys())
1014 self.assertEquals([], pi.items())
1015 self.assertEquals(None, pi.get('hoi'))
1016 self.assertEquals(0, len(pi))
1017
1018 for i in pi:
1019 pass
1020
1036
1054
1064
1073
1088
1105
1123
1142
1148
1149 a = Element("a")
1150 a.tag = strTest("TAG")
1151 self.assertXML('<TAG></TAG>',
1152 a)
1153
1183
1185 Element = self.etree.Element
1186 SubElement = self.etree.SubElement
1187
1188 a = Element('a')
1189 b = SubElement(a, 'b')
1190 bs = SubElement(b, 'bs')
1191 c = SubElement(a, 'c')
1192 cs = SubElement(c, 'cs')
1193
1194 el = a[0]
1195 self.assertXML(
1196 '<a><b><bs></bs></b><c><cs></cs></c></a>',
1197 a)
1198 self.assertXML('<b><bs></bs></b>', b)
1199 self.assertXML('<c><cs></cs></c>', c)
1200
1201 del a[0]
1202 self.assertXML(
1203 '<a><c><cs></cs></c></a>',
1204 a)
1205 self.assertXML('<b><bs></bs></b>', b)
1206 self.assertXML('<c><cs></cs></c>', c)
1207
1208 a.insert(0, el)
1209 self.assertXML(
1210 '<a><b><bs></bs></b><c><cs></cs></c></a>',
1211 a)
1212 self.assertXML('<b><bs></bs></b>', b)
1213 self.assertXML('<c><cs></cs></c>', c)
1214
1233
1252
1254 XML = self.etree.XML
1255 a = XML('<a><b></b>B2<c></c>C2</a>')
1256 b, c = a
1257
1258 a[:] = []
1259
1260 self.assertEquals("B2", b.tail)
1261 self.assertEquals("C2", c.tail)
1262
1272
1274 Element = self.etree.Element
1275
1276 a = Element('a')
1277 a.text = 'foo'
1278 a.tail = 'bar'
1279 a.set('hoi', 'dag')
1280 a.clear()
1281 self.assertEquals(None, a.text)
1282 self.assertEquals(None, a.tail)
1283 self.assertEquals(None, a.get('hoi'))
1284 self.assertEquals('a', a.tag)
1285
1287 Element = self.etree.Element
1288 SubElement = self.etree.SubElement
1289
1290 a = Element('a')
1291 a.text = 'foo'
1292 a.tail = 'bar'
1293 a.set('hoi', 'dag')
1294 b = SubElement(a, 'b')
1295 c = SubElement(b, 'c')
1296 a.clear()
1297 self.assertEquals(None, a.text)
1298 self.assertEquals(None, a.tail)
1299 self.assertEquals(None, a.get('hoi'))
1300 self.assertEquals('a', a.tag)
1301 self.assertEquals(0, len(a))
1302 self.assertXML('<a></a>',
1303 a)
1304 self.assertXML('<b><c></c></b>',
1305 b)
1306
1316
1343
1359
1376
1391
1407
1423
1434
1447
1469
1478
1480 Element = self.etree.Element
1481 SubElement = self.etree.SubElement
1482
1483 a = Element('a')
1484 b = SubElement(a, 'b')
1485 c = SubElement(a, 'c')
1486 d = SubElement(b, 'd')
1487 e = SubElement(c, 'e')
1488
1489 self.assertEquals(
1490 [a, b, d, c, e],
1491 list(a.iter()))
1492 self.assertEquals(
1493 [d],
1494 list(d.iter()))
1495
1497 Element = self.etree.Element
1498 SubElement = self.etree.SubElement
1499
1500 a = Element('a')
1501 b = SubElement(a, 'b')
1502 c = SubElement(a, 'c')
1503 d = SubElement(b, 'd')
1504 e = SubElement(c, 'e')
1505
1506 self.assertEquals(
1507 [a, b, d, c, e],
1508 list(a.getiterator()))
1509 self.assertEquals(
1510 [d],
1511 list(d.getiterator()))
1512
1532
1553
1567
1592
1594 Element = self.etree.Element
1595 PI = self.etree.ProcessingInstruction
1596 SubElement = self.etree.SubElement
1597
1598 a = Element('a')
1599 b = SubElement(a, 'b')
1600 pi_b = PI("TEST-b")
1601 b.append(pi_b)
1602
1603 self.assertEquals(
1604 [pi_b],
1605 list(a.getiterator(PI)))
1606
1607 pi_a = PI("TEST-a")
1608 a.append(pi_a)
1609
1610 self.assertEquals(
1611 [pi_b, pi_a],
1612 list(a.getiterator(PI)))
1613
1614 self.assertEquals(
1615 [pi_b],
1616 list(b.getiterator(PI)))
1617
1619 Element = self.etree.Element
1620 SubElement = self.etree.SubElement
1621
1622 a = Element('a')
1623 a.text = 'a'
1624 b = SubElement(a, 'b')
1625 b.text = 'b'
1626 b.tail = 'b1'
1627 c = SubElement(a, 'c')
1628 c.text = 'c'
1629 c.tail = 'c1'
1630 d = SubElement(b, 'd')
1631 c.text = 'd'
1632 c.tail = 'd1'
1633 e = SubElement(c, 'e')
1634 e.text = 'e'
1635 e.tail = 'e1'
1636
1637 self.assertEquals(
1638 [a, b, d, c, e],
1639 list(a.getiterator()))
1640
1641
1642
1643
1645 Element = self.etree.Element
1646 SubElement = self.etree.SubElement
1647
1648 a = Element('a')
1649 a.text = 'a'
1650 b = SubElement(a, 'b')
1651 b.text = 'b'
1652 b.tail = 'b1'
1653 c = SubElement(a, 'c')
1654 c.text = 'c'
1655 c.tail = 'c1'
1656 d = SubElement(b, 'd')
1657 c.text = 'd'
1658 c.tail = 'd1'
1659 e = SubElement(c, 'e')
1660 e.text = 'e'
1661 e.tail = 'e1'
1662
1663 self.assertEquals(
1664 [a],
1665 list(a.getiterator('a')))
1666 a2 = SubElement(e, 'a')
1667 self.assertEquals(
1668 [a, a2],
1669 list(a.getiterator('a')))
1670 self.assertEquals(
1671 [a2],
1672 list(e.getiterator('a')))
1673
1683
1685 Element = self.etree.Element
1686 SubElement = self.etree.SubElement
1687
1688 a = Element('a')
1689 b = SubElement(a, 'b')
1690 c = SubElement(a, 'c')
1691 d = SubElement(a, 'd')
1692
1693 self.assertEquals(
1694 [b, c],
1695 a[0:2])
1696 self.assertEquals(
1697 [b, c, d],
1698 a[:])
1699 self.assertEquals(
1700 [b, c, d],
1701 a[:10])
1702 self.assertEquals(
1703 [b],
1704 a[0:1])
1705 self.assertEquals(
1706 [],
1707 a[10:12])
1708
1710 Element = self.etree.Element
1711 SubElement = self.etree.SubElement
1712
1713 a = Element('a')
1714 b = SubElement(a, 'b')
1715 c = SubElement(a, 'c')
1716 d = SubElement(a, 'd')
1717
1718 self.assertEquals(
1719 [d],
1720 a[-1:])
1721 self.assertEquals(
1722 [c, d],
1723 a[-2:])
1724 self.assertEquals(
1725 [c],
1726 a[-2:-1])
1727 self.assertEquals(
1728 [b, c],
1729 a[-3:-1])
1730 self.assertEquals(
1731 [b, c],
1732 a[-3:2])
1733
1735 Element = self.etree.Element
1736 SubElement = self.etree.SubElement
1737
1738 a = Element('a')
1739 b = SubElement(a, 'b')
1740 c = SubElement(a, 'c')
1741 d = SubElement(a, 'd')
1742 e = SubElement(a, 'e')
1743
1744 self.assertEquals(
1745 [e,d,c,b],
1746 a[::-1])
1747 self.assertEquals(
1748 [b,d],
1749 a[::2])
1750 self.assertEquals(
1751 [e,c],
1752 a[::-2])
1753 self.assertEquals(
1754 [d,c],
1755 a[-2:0:-1])
1756 self.assertEquals(
1757 [e],
1758 a[:1:-2])
1759
1761 ElementTree = self.etree.ElementTree
1762
1763 f = StringIO('<a><b>B</b>B1<c>C</c>C1</a>')
1764 doc = ElementTree(file=f)
1765 a = doc.getroot()
1766 b = a[0]
1767 c = a[1]
1768 self.assertEquals(
1769 [b, c],
1770 a[:])
1771 self.assertEquals(
1772 [b],
1773 a[0:1])
1774 self.assertEquals(
1775 [c],
1776 a[1:])
1777
1801
1816
1831
1846
1861
1876
1891
1893 ElementTree = self.etree.ElementTree
1894 f = StringIO('<a><b></b>B2<c></c>C2<d></d>D2<e></e>E2</a>')
1895 doc = ElementTree(file=f)
1896 a = doc.getroot()
1897 del a[1:3]
1898 self.assertXML(
1899 '<a><b></b>B2<e></e>E2</a>',
1900 a)
1901
1903 XML = self.etree.XML
1904 a = XML('<a><b></b>B2<c></c>C2</a>')
1905 b, c = a
1906
1907 del a[:]
1908
1909 self.assertEquals("B2", b.tail)
1910 self.assertEquals("C2", c.tail)
1911
1922
1924 Element = self.etree.Element
1925 SubElement = self.etree.SubElement
1926
1927 a = Element('a')
1928 b = SubElement(a, 'b')
1929 c = SubElement(a, 'c')
1930 d = SubElement(a, 'd')
1931
1932 e = Element('e')
1933 f = Element('f')
1934 g = Element('g')
1935
1936 s = [e, f, g]
1937 a[1:2] = s
1938 self.assertEquals(
1939 [b, e, f, g, d],
1940 list(a))
1941
1959
1975
1990
2005
2007 Element = self.etree.Element
2008 SubElement = self.etree.SubElement
2009
2010 a = Element('{ns}a')
2011 b = SubElement(a, '{ns}b', {'{ns1}a1': 'test'})
2012 c = SubElement(a, '{ns}c', {'{ns2}a2': 'test'})
2013 d = SubElement(a, '{ns}d', {'{ns3}a3': 'test'})
2014
2015 s = [d, c, b]
2016 a[:] = s
2017 self.assertEquals(
2018 [d, c, b],
2019 list(a))
2020 self.assertEquals(
2021 ['{ns}d', '{ns}c', '{ns}b'],
2022 [ child.tag for child in a ])
2023
2024 self.assertEquals(
2025 [['{ns3}a3'], ['{ns2}a2'], ['{ns1}a1']],
2026 [ child.attrib.keys() for child in a ])
2027
2029 Element = self.etree.Element
2030 SubElement = self.etree.SubElement
2031
2032 a = Element('{ns}a')
2033 b = SubElement(a, '{ns1}b', {'{ns}a1': 'test'})
2034 c = SubElement(a, '{ns2}c', {'{ns}a2': 'test'})
2035 d = SubElement(a, '{ns3}d', {'{ns}a3': 'test'})
2036
2037 s = [d, c, b]
2038 a[:] = s
2039 self.assertEquals(
2040 [d, c, b],
2041 list(a))
2042 self.assertEquals(
2043 ['{ns3}d', '{ns2}c', '{ns1}b'],
2044 [ child.tag for child in a ])
2045
2046 self.assertEquals(
2047 [['{ns}a3'], ['{ns}a2'], ['{ns}a1']],
2048 [ child.attrib.keys() for child in a ])
2049
2051 Element = self.etree.Element
2052 SubElement = self.etree.SubElement
2053
2054 a = Element('a')
2055 b = SubElement(a, 'b')
2056 c = SubElement(a, 'c')
2057
2058 e = Element('e')
2059 f = Element('f')
2060 g = Element('g')
2061 h = Element('h')
2062
2063 s = [e, f]
2064 a[99:] = s
2065 self.assertEquals(
2066 [a, b, e, f],
2067 list(a))
2068
2069 s = [g, h]
2070 a[:0] = s
2071 self.assertEquals(
2072 [g, h, a, b, e, f],
2073 list(a))
2074
2097
2114
2131
2148
2150 Element = self.etree.Element
2151 SubElement = self.etree.SubElement
2152
2153 a = Element('a')
2154 b = SubElement(a, 'b')
2155 c = SubElement(a, 'c')
2156 d = SubElement(a, 'd')
2157
2158 e = Element('e')
2159 f = Element('f')
2160 g = Element('g')
2161
2162 s = [e, f, g]
2163 a[3:] = s
2164 self.assertEquals(
2165 [b, c, d, e, f, g],
2166 list(a))
2167
2180
2190
2206
2225
2227 ElementTree = self.etree.ElementTree
2228 ns = 'http://xml.infrae.com/1'
2229 f = StringIO('<x:a xmlns:x="%s"><x:b></x:b></x:a>' % ns)
2230 t = ElementTree(file=f)
2231 a = t.getroot()
2232 self.assertEquals('{%s}a' % ns,
2233 a.tag)
2234 self.assertEquals('{%s}b' % ns,
2235 a[0].tag)
2236
2238 ElementTree = self.etree.ElementTree
2239 ns = 'http://xml.infrae.com/1'
2240 ns2 = 'http://xml.infrae.com/2'
2241 f = StringIO('<x:a xmlns:x="%s" xmlns:y="%s"><x:b></x:b><y:b></y:b></x:a>' % (ns, ns2))
2242 t = ElementTree(file=f)
2243 a = t.getroot()
2244 self.assertEquals('{%s}a' % ns,
2245 a.tag)
2246 self.assertEquals('{%s}b' % ns,
2247 a[0].tag)
2248 self.assertEquals('{%s}b' % ns2,
2249 a[1].tag)
2250
2252 Element = self.etree.Element
2253 SubElement = self.etree.SubElement
2254 ns = 'http://xml.infrae.com/1'
2255 ns2 = 'http://xml.infrae.com/2'
2256 a = Element('{%s}a' % ns)
2257 b = SubElement(a, '{%s}b' % ns2)
2258 c = SubElement(a, '{%s}c' % ns)
2259 self.assertEquals('{%s}a' % ns,
2260 a.tag)
2261 self.assertEquals('{%s}b' % ns2,
2262 b.tag)
2263 self.assertEquals('{%s}c' % ns,
2264 c.tag)
2265 self.assertEquals('{%s}a' % ns,
2266 a.tag)
2267 self.assertEquals('{%s}b' % ns2,
2268 b.tag)
2269 self.assertEquals('{%s}c' % ns,
2270 c.tag)
2271
2289
2291 Element = self.etree.Element
2292 ns = 'http://xml.infrae.com/1'
2293 ns2 = 'http://xml.infrae.com/2'
2294 a = Element('a')
2295 a.set('{%s}foo' % ns, 'Foo')
2296 a.set('{%s}bar' % ns2, 'Bar')
2297 self.assertEquals(
2298 'Foo',
2299 a.get('{%s}foo' % ns))
2300 self.assertEquals(
2301 'Bar',
2302 a.get('{%s}bar' % ns2))
2303 try:
2304 self.assertXML(
2305 '<a xmlns:ns0="%s" xmlns:ns1="%s" ns0:foo="Foo" ns1:bar="Bar"></a>' % (ns, ns2),
2306 a)
2307 except AssertionError:
2308 self.assertXML(
2309 '<a xmlns:ns0="%s" xmlns:ns1="%s" ns1:foo="Foo" ns0:bar="Bar"></a>' % (ns2, ns),
2310 a)
2311
2326
2328 tostring = self.etree.tostring
2329 root = self.etree.XML(
2330 '<foo><bar xmlns:ns="http://a.b.c"><ns:baz/></bar></foo>')
2331 baz = root[0][0]
2332
2333 nsdecl = re.findall("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']",
2334 tostring(baz))
2335 self.assertEquals(["http://a.b.c"], nsdecl)
2336
2338 tostring = self.etree.tostring
2339 root = self.etree.XML(
2340 '<foo><bar xmlns="http://a.b.c"><baz/></bar></foo>')
2341 baz = root[0][0]
2342
2343 nsdecl = re.findall("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']",
2344 tostring(baz))
2345 self.assertEquals(["http://a.b.c"], nsdecl)
2346
2348 tostring = self.etree.tostring
2349 root = self.etree.XML(
2350 '<foo xmlns:ns="http://a.b.c"><bar><ns:baz/></bar></foo>')
2351 baz = root[0][0]
2352
2353 nsdecl = re.findall("xmlns(?::[a-z0-9]+)?=[\"']([^\"']+)[\"']",
2354 tostring(baz))
2355
2356 self.assertEquals(["http://a.b.c"], nsdecl)
2357
2370
2372 Element = self.etree.Element
2373
2374 root = Element('element')
2375
2376 subelement = Element('subelement',
2377 {"{http://www.w3.org/XML/1998/namespace}id": "foo"})
2378 self.assertEquals(1, len(subelement.attrib))
2379 self.assertEquals(
2380 "foo",
2381 subelement.get("{http://www.w3.org/XML/1998/namespace}id"))
2382
2383 root.append(subelement)
2384 self.assertEquals(1, len(subelement.attrib))
2385 self.assertEquals(
2386 {"{http://www.w3.org/XML/1998/namespace}id" : "foo"}.items(),
2387 subelement.attrib.items())
2388 self.assertEquals(
2389 "foo",
2390 subelement.get("{http://www.w3.org/XML/1998/namespace}id"))
2391
2403
2417
2431
2445
2447 tostring = self.etree.tostring
2448 Element = self.etree.Element
2449 SubElement = self.etree.SubElement
2450
2451 a = Element('a')
2452 a.text = "A"
2453 a.tail = "tail"
2454 b = SubElement(a, 'b')
2455 b.text = "B"
2456 b.tail = "TAIL"
2457 c = SubElement(a, 'c')
2458 c.text = "C"
2459
2460 self.assertEquals('ABTAILCtail',
2461 tostring(a, method="text"))
2462
2464 iterparse = self.etree.iterparse
2465 f = StringIO('<a><b></b><c/></a>')
2466
2467 iterator = iterparse(f)
2468 self.assertEquals(None,
2469 iterator.root)
2470 events = list(iterator)
2471 root = iterator.root
2472 self.assertEquals(
2473 [('end', root[0]), ('end', root[1]), ('end', root)],
2474 events)
2475
2486
2488 iterparse = self.etree.iterparse
2489 f = StringIO('<a><b></b><c/></a>')
2490
2491 iterator = iterparse(f, events=('start',))
2492 events = list(iterator)
2493 root = iterator.root
2494 self.assertEquals(
2495 [('start', root), ('start', root[0]), ('start', root[1])],
2496 events)
2497
2499 iterparse = self.etree.iterparse
2500 f = StringIO('<a><b></b><c/></a>')
2501
2502 iterator = iterparse(f, events=('start','end'))
2503 events = list(iterator)
2504 root = iterator.root
2505 self.assertEquals(
2506 [('start', root), ('start', root[0]), ('end', root[0]),
2507 ('start', root[1]), ('end', root[1]), ('end', root)],
2508 events)
2509
2511 iterparse = self.etree.iterparse
2512 f = StringIO('<a><b></b><c/></a>')
2513
2514 iterator = iterparse(f)
2515 for event, elem in iterator:
2516 elem.clear()
2517
2518 root = iterator.root
2519 self.assertEquals(0,
2520 len(root))
2521
2523 iterparse = self.etree.iterparse
2524 CHILD_COUNT = 12345
2525 f = StringIO('<a>%s</a>' % ('<b>test</b>'*CHILD_COUNT))
2526
2527 i = 0
2528 for key in iterparse(f):
2529 event, element = key
2530 i += 1
2531 self.assertEquals(i, CHILD_COUNT + 1)
2532
2534 iterparse = self.etree.iterparse
2535 f = StringIO('<a xmlns="ns1"><b><c xmlns="ns2"/></b></a>')
2536
2537 attr_name = '{testns}bla'
2538 events = []
2539 iterator = iterparse(f, events=('start','end','start-ns','end-ns'))
2540 for event, elem in iterator:
2541 events.append(event)
2542 if event == 'start':
2543 if elem.tag != '{ns1}a':
2544 elem.set(attr_name, 'value')
2545
2546 self.assertEquals(
2547 ['start-ns', 'start', 'start', 'start-ns', 'start',
2548 'end', 'end-ns', 'end', 'end', 'end-ns'],
2549 events)
2550
2551 root = iterator.root
2552 self.assertEquals(
2553 None,
2554 root.get(attr_name))
2555 self.assertEquals(
2556 'value',
2557 root[0].get(attr_name))
2558
2560 iterparse = self.etree.iterparse
2561 f = StringIO('<a><b><d/></b><c/></a>')
2562
2563 counts = []
2564 for event, elem in iterparse(f):
2565 counts.append(len(list(elem.getiterator())))
2566 self.assertEquals(
2567 [1,2,1,4],
2568 counts)
2569
2582
2590
2594
2604
2606 parse = self.etree.parse
2607
2608 f = StringIO('<a><b></b></a>')
2609 tree = parse(f)
2610 f.close()
2611 self.assertXML(
2612 '<a><b></b></a>',
2613 tree.getroot()
2614 )
2615
2617
2618 parse = self.etree.parse
2619 tree = parse(StringIO('<?xml version="1.0" encoding="ascii"?><html/>'))
2620 self.assertXML('<html></html>',
2621 tree.getroot())
2622
2631
2644
2652
2662
2664 ElementTree = self.etree.ElementTree
2665 Element = self.etree.Element
2666
2667 a = Element('a')
2668 a.text = u'Søk på nettet'
2669
2670 f = StringIO()
2671 tree = ElementTree(element=a)
2672 tree.write(f, encoding='iso-8859-1')
2673 result = f.getvalue()
2674 declaration = "<?xml version=\'1.0\' encoding=\'iso-8859-1\'?>"
2675 self.assertEncodingDeclaration(result,'iso-8859-1')
2676 result = result.split('?>', 1)[-1].replace('\n','')
2677 self.assertEquals(u'<a>Søk på nettet</a>'.encode('iso-8859-1'),
2678 result)
2679
2694
2696 XMLParser = self.etree.XMLParser
2697
2698 text = u'Søk på nettet'
2699 wrong_declaration = "<?xml version='1.0' encoding='UTF-8'?>"
2700 xml_latin1 = (u'%s<a>%s</a>' % (wrong_declaration, text)
2701 ).encode('iso-8859-1')
2702
2703 self.assertRaises(self.etree.ParseError,
2704 self.etree.parse,
2705 StringIO(xml_latin1))
2706
2707 tree = self.etree.parse(StringIO(xml_latin1),
2708 XMLParser(encoding="iso-8859-1"))
2709 a = tree.getroot()
2710 self.assertEquals(a.text, text)
2711
2713
2714 XML = self.etree.XML
2715 test_utf = (u'<?xml version="1.0" encoding="iso-8859-1"?>' + \
2716 u'<a>Søk på nettet</a>')
2717 self.assertRaises(SyntaxError, XML, test_utf)
2718
2733
2742
2751
2762
2774
2787
2801
2803 utext = u'Søk på nettet'
2804 uxml = u'<p>%s</p>' % utext
2805 prologue = '<?xml version="1.0" encoding="iso-8859-1" ?>'
2806 isoxml = prologue + uxml.encode('iso-8859-1')
2807 tree = self.etree.XML(isoxml)
2808 self.assertEquals(utext, tree.text)
2809
2811 utext = u'Søk på nettet'
2812 uxml = u'<?xml version="1.0" encoding="UTF-8"?>' + \
2813 u'<p>%s</p>' % utext
2814 bom = '\xEF\xBB\xBF'
2815 xml = bom + uxml.encode("utf-8")
2816 tree = etree.XML(xml)
2817 self.assertEquals(utext, tree.text)
2818
2820 utext = u'Søk på nettet'
2821 uxml = u'<p>%s</p>' % utext
2822 prologue = '<?xml version="1.0" encoding="iso-8859-1" ?>'
2823 isoxml = prologue + uxml.encode('iso-8859-1')
2824 el = self.etree.parse(StringIO(isoxml)).getroot()
2825 self.assertEquals(utext, el.text)
2826
2840
2842 Element = self.etree.Element
2843
2844 a = Element('a')
2845 a.text = 'Foo'
2846
2847 b = copy.deepcopy(a)
2848 self.assertEquals('Foo', b.text)
2849
2850 b.text = 'Bar'
2851 self.assertEquals('Bar', b.text)
2852 self.assertEquals('Foo', a.text)
2853
2854 del a
2855 self.assertEquals('Bar', b.text)
2856
2858 Element = self.etree.Element
2859
2860 a = Element('a')
2861 a.tail = 'Foo'
2862
2863 b = copy.deepcopy(a)
2864 self.assertEquals('Foo', b.tail)
2865
2866 b.tail = 'Bar'
2867 self.assertEquals('Bar', b.tail)
2868 self.assertEquals('Foo', a.tail)
2869
2870 del a
2871 self.assertEquals('Bar', b.tail)
2872
2874 Element = self.etree.Element
2875 SubElement = self.etree.SubElement
2876
2877 root = Element('root')
2878 a = SubElement(root, 'a')
2879 a.text = 'FooText'
2880 a.tail = 'FooTail'
2881
2882 b = copy.deepcopy(a)
2883 self.assertEquals('FooText', b.text)
2884 self.assertEquals('FooTail', b.tail)
2885
2886 b.text = 'BarText'
2887 b.tail = 'BarTail'
2888 self.assertEquals('BarTail', b.tail)
2889 self.assertEquals('FooTail', a.tail)
2890 self.assertEquals('BarText', b.text)
2891 self.assertEquals('FooText', a.text)
2892
2893 del a
2894 self.assertEquals('BarTail', b.tail)
2895 self.assertEquals('BarText', b.text)
2896
2898 root = self.etree.XML('''<doc xmlns="dns" xmlns:t="tns">
2899 <parent><node t:foo="bar" /></parent>
2900 </doc>''')
2901 self.assertEquals(
2902 root[0][0].get('{tns}foo'),
2903 copy.deepcopy(root[0])[0].get('{tns}foo') )
2904 self.assertEquals(
2905 root[0][0].get('{tns}foo'),
2906 copy.deepcopy(root[0][0]).get('{tns}foo') )
2907
2922
2935
2936
2949
2951
2952 etree = self.etree
2953 e = etree.Element('foo')
2954 self.assertEquals(False, bool(e))
2955 etree.SubElement(e, 'bar')
2956 self.assertEquals(True, bool(e))
2957 e = etree.Element('foo')
2958 e.text = 'hey'
2959 self.assertEquals(False, bool(e))
2960 e = etree.Element('foo')
2961 e.tail = 'bar'
2962 self.assertEquals(False, bool(e))
2963 e = etree.Element('foo')
2964 e.set('bar', 'Bar')
2965 self.assertEquals(False, bool(e))
2966
2968 etree = self.etree
2969
2970 a = etree.Element('a')
2971 b = etree.SubElement(a, 'b')
2972
2973 t = etree.ElementTree(a)
2974 self.assertEquals(self._rootstring(t), '<a><b/></a>')
2975
2976 t1 = etree.ElementTree(a)
2977 self.assertEquals(self._rootstring(t1), '<a><b/></a>')
2978 self.assertEquals(self._rootstring(t), '<a><b/></a>')
2979
2980 t2 = etree.ElementTree(b)
2981 self.assertEquals(self._rootstring(t2), '<b/>')
2982 self.assertEquals(self._rootstring(t1), '<a><b/></a>')
2983 self.assertEquals(self._rootstring(t), '<a><b/></a>')
2984
2992
2994 etree = self.etree
2995 qname1 = etree.QName('myns', 'a')
2996 qname2 = etree.QName('myns', 'a')
2997 self.assertEquals(qname1, "{myns}a")
2998 self.assertEquals("{myns}a", qname2)
2999 self.assertEquals(qname1, qname1)
3000 self.assertEquals(qname1, qname2)
3001
3003 etree = self.etree
3004 qname = etree.QName('myns', 'a')
3005
3006 a = etree.Element(qname)
3007 a.set(qname, "value")
3008
3009 self.assertEquals(a.get(qname), "value")
3010 self.assertEquals(a.get("{myns}a"), "value")
3011
3013 etree = self.etree
3014 qname = etree.QName('myns', 'a')
3015
3016 a = etree.Element(qname)
3017 a.attrib[qname] = "value"
3018
3019 self.assertEquals(a.attrib[qname], "value")
3020 self.assertEquals(a.attrib.get(qname), "value")
3021
3022 self.assertEquals(a.attrib["{myns}a"], "value")
3023 self.assertEquals(a.attrib.get("{myns}a"), "value")
3024
3026 etree = self.etree
3027 qname = etree.QName('http://myns', 'a')
3028 a = etree.Element(qname)
3029 a.set(qname, qname)
3030
3031 self.assertXML(
3032 '<ns0:a xmlns:ns0="http://myns" ns0:a="ns0:a"></ns0:a>',
3033 a)
3034
3044
3054
3061
3062
3063
3079
3084
3093
3107
3118
3119
3120
3122 assertEquals = self.assertEquals
3123 assertFalse = self.assertFalse
3124
3125 events = []
3126 class Target(object):
3127 def start(self, tag, attrib):
3128 events.append("start")
3129 assertFalse(attrib)
3130 assertEquals("TAG", tag)
3131 def end(self, tag):
3132 events.append("end")
3133 assertEquals("TAG", tag)
3134 def close(self):
3135 return "DONE"
3136
3137 parser = self.etree.XMLParser(target=Target())
3138
3139 parser.feed("<TAG/>")
3140 done = parser.close()
3141
3142 self.assertEquals("DONE", done)
3143 self.assertEquals(["start", "end"], events)
3144
3156 def end(self, tag):
3157 events.append("end")
3158 assertEquals("TAG", tag)
3159 def close(self):
3160 return Element("DONE")
3161
3162 parser = self.etree.XMLParser(target=Target())
3163 tree = self.etree.ElementTree()
3164 tree.parse(StringIO("<TAG/>"), parser=parser)
3165
3166 self.assertEquals("DONE", tree.getroot().tag)
3167 self.assertEquals(["start", "end"], events)
3168
3170 assertEquals = self.assertEquals
3171
3172 events = []
3173 class Target(object):
3174 def start(self, tag, attrib):
3175 events.append("start-" + tag)
3176 for name, value in attrib.iteritems():
3177 assertEquals(tag + name, value)
3178 def end(self, tag):
3179 events.append("end-" + tag)
3180 def close(self):
3181 return "DONE"
3182
3183 parser = self.etree.XMLParser(target=Target())
3184
3185 parser.feed('<root a="roota" b="rootb"><sub c="subc"/></root>')
3186 done = parser.close()
3187
3188 self.assertEquals("DONE", done)
3189 self.assertEquals(["start-root", "start-sub", "end-sub", "end-root"],
3190 events)
3191
3193 events = []
3194 class Target(object):
3195 def start(self, tag, attrib):
3196 events.append("start-" + tag)
3197 def end(self, tag):
3198 events.append("end-" + tag)
3199 def data(self, data):
3200 events.append("data-" + data)
3201 def close(self):
3202 return "DONE"
3203
3204 parser = self.etree.XMLParser(target=Target())
3205
3206 parser.feed('<root>A<sub/>B</root>')
3207 done = parser.close()
3208
3209 self.assertEquals("DONE", done)
3210 self.assertEquals(["start-root", "data-A", "start-sub",
3211 "end-sub", "data-B", "end-root"],
3212 events)
3213
3215 events = []
3216 class Target(object):
3217 def __init__(self):
3218 self._data = []
3219 def _flush_data(self):
3220 if self._data:
3221 events.append("data-" + ''.join(self._data))
3222 del self._data[:]
3223 def start(self, tag, attrib):
3224 self._flush_data()
3225 events.append("start-" + tag)
3226 def end(self, tag):
3227 self._flush_data()
3228 events.append("end-" + tag)
3229 def data(self, data):
3230 self._data.append(data)
3231 def close(self):
3232 self._flush_data()
3233 return "DONE"
3234
3235 parser = self.etree.XMLParser(target=Target())
3236
3237 dtd = '''
3238 <!DOCTYPE root [
3239 <!ELEMENT root (sub*)>
3240 <!ELEMENT sub (#PCDATA)>
3241 <!ENTITY ent "an entity">
3242 ]>
3243 '''
3244 parser.feed(dtd+'<root><sub/><sub>this is &ent;</sub><sub/></root>')
3245 done = parser.close()
3246
3247 self.assertEquals("DONE", done)
3248 self.assertEquals(["start-root", "start-sub", "end-sub", "start-sub",
3249 "data-this is an entity",
3250 "end-sub", "start-sub", "end-sub", "end-root"],
3251 events)
3252
3254 events = []
3255 class Target(object):
3256 def __init__(self):
3257 self._data = []
3258 def _flush_data(self):
3259 if self._data:
3260 events.append("data-" + ''.join(self._data))
3261 del self._data[:]
3262 def start(self, tag, attrib):
3263 self._flush_data()
3264 events.append("start-" + tag)
3265 def end(self, tag):
3266 self._flush_data()
3267 events.append("end-" + tag)
3268 def data(self, data):
3269 self._data.append(data)
3270 def close(self):
3271 self._flush_data()
3272 return "DONE"
3273
3274 parser = self.etree.XMLParser(target=Target())
3275
3276 def feed():
3277 parser.feed('<root><sub/><sub>some &ent;</sub><sub/></root>')
3278 parser.close()
3279
3280 self.assertRaises(self.etree.ParseError, feed)
3281
3283 builder = self.etree.TreeBuilder()
3284 el = builder.start("root", {'a':'A', 'b':'B'})
3285 self.assertEquals("root", el.tag)
3286 self.assertEquals({'a':'A', 'b':'B'}, el.attrib)
3287 builder.data("ROOTTEXT")
3288 el = builder.start("child", {'x':'X', 'y':'Y'})
3289 self.assertEquals("child", el.tag)
3290 self.assertEquals({'x':'X', 'y':'Y'}, el.attrib)
3291 builder.data("CHILDTEXT")
3292 el = builder.end("child")
3293 self.assertEquals("child", el.tag)
3294 self.assertEquals({'x':'X', 'y':'Y'}, el.attrib)
3295 self.assertEquals("CHILDTEXT", el.text)
3296 self.assertEquals(None, el.tail)
3297 builder.data("CHILDTAIL")
3298 root = builder.end("root")
3299
3300 self.assertEquals("root", root.tag)
3301 self.assertEquals("ROOTTEXT", root.text)
3302 self.assertEquals("CHILDTEXT", root[0].text)
3303 self.assertEquals("CHILDTAIL", root[0].tail)
3304
3314
3315
3316
3324
3344
3345 - def assertXML(self, expected, element, encoding='us-ascii'):
3346 """Writes element out and checks whether it is expected.
3347
3348 Does this two ways; once using StringIO, once using a real file.
3349 """
3350 self.assertEquals(expected, self._writeElement(element, encoding))
3351 self.assertEquals(expected, self._writeElementFile(element, encoding))
3352
3354 "Checks if the result XML byte string specifies the encoding."
3355 has_encoding = re.compile(r"<\?xml[^>]+ encoding=[\"']([^\"']+)[\"']").match
3356 self.assert_(has_encoding(result))
3357 result_encoding = has_encoding(result).group(1)
3358 self.assertEquals(result_encoding.upper(), encoding.upper())
3359
3361 return self.etree.tostring(tree.getroot()).replace(' ', '').replace('\n', '')
3362
3364 self._check_element(tree.getroot())
3365
3367 self.assert_(hasattr(element, 'tag'))
3368 self.assert_(hasattr(element, 'attrib'))
3369 self.assert_(hasattr(element, 'text'))
3370 self.assert_(hasattr(element, 'tail'))
3371 self._check_string(element.tag)
3372 self._check_mapping(element.attrib)
3373 if element.text != None:
3374 self._check_string(element.text)
3375 if element.tail != None:
3376 self._check_string(element.tail)
3377
3379 len(string)
3380 for char in string:
3381 self.assertEquals(1, len(char))
3382 new_string = string + ""
3383 new_string = string + " "
3384 string[:0]
3385
3387 len(mapping)
3388 keys = mapping.keys()
3389 items = mapping.items()
3390 for key in keys:
3391 item = mapping[key]
3392 mapping["key"] = "value"
3393 self.assertEquals("value", mapping["key"])
3394
3395
3396 if etree:
3399
3400 if ElementTree:
3403
3404 if cElementTree:
3407
3417
3418 if __name__ == '__main__':
3419 print 'to test use test.py %s' % __file__
3420