1
2
3 """
4 Tests specific to the extended etree API
5
6 Tests that apply to the general ElementTree API should go into
7 test_elementtree
8 """
9
10
11 import unittest, copy, sys, warnings
12
13 from common_imports import etree, StringIO, HelperTestCase, fileInTestDir
14 from common_imports import SillyFileLike, canonicalize, doctest
15
16 print
17 print "TESTED VERSION:"
18 print " Python: ", sys.version_info
19 print " lxml.etree: ", etree.LXML_VERSION
20 print " libxml used: ", etree.LIBXML_VERSION
21 print " libxml compiled: ", etree.LIBXML_COMPILED_VERSION
22 print " libxslt used: ", etree.LIBXSLT_VERSION
23 print " libxslt compiled: ", etree.LIBXSLT_COMPILED_VERSION
24 print
25
26 try:
27 sorted(())
28 except NameError:
29
31 seq = list(seq)
32 seq.sort()
33 return seq
34
35 warnings.simplefilter("error", etree.TagNameWarning)
36
38 """Tests only for etree, not ElementTree"""
39 etree = etree
40
51
53 self.assert_(hasattr(self.etree, '_import_c_api'))
54
61
63 Element = self.etree.Element
64 el = Element('name')
65 self.assertRaises(ValueError, Element, '{}')
66 self.assertRaises(ValueError, setattr, el, 'tag', '{}')
67
68 self.assertRaises(ValueError, Element, '{test}')
69 self.assertRaises(ValueError, setattr, el, 'tag', '{test}')
70
72 Element = self.etree.Element
73 self.assertRaises(self.etree.TagNameWarning,
74 Element, 'p:name')
75 self.assertRaises(self.etree.TagNameWarning,
76 Element, '{test}p:name')
77
78 el = Element('name')
79 self.assertRaises(self.etree.TagNameWarning,
80 setattr, el, 'tag', 'p:name')
81
83
84
85 Element = self.etree.Element
86
87 root = Element("root")
88 root.set("attr", "TEST")
89 self.assertEquals("TEST", root.get("attr"))
90 self.assertRaises(TypeError, root.set, "newattr", 5)
91
93 ElementTree = self.etree.ElementTree
94
95 f = StringIO('<doc one="One" two="Two"/>')
96 doc = ElementTree(file=f)
97 root = doc.getroot()
98 self.assertEquals('One', root.attrib['one'])
99 self.assertEquals('Two', root.attrib['two'])
100
101 self.assertEquals('One', root.attrib.pop('one'))
102
103 self.assertEquals(None, root.attrib.get('one'))
104 self.assertEquals('Two', root.attrib['two'])
105
107 root = self.etree.XML('<doc one="One" two="Two"/>')
108 self.assertRaises(KeyError, root.attrib.pop, 'NONE')
109
110 self.assertEquals('One', root.attrib['one'])
111 self.assertEquals('Two', root.attrib['two'])
112
114 root = self.etree.XML('<doc one="One" two="Two"/>')
115 self.assertEquals('Three', root.attrib.pop('three', 'Three'))
116
118 root = self.etree.XML('<doc/>')
119 self.assertEquals('Three', root.attrib.pop('three', 'Three'))
120
122 root = self.etree.XML('<doc one="One" two="Two"/>')
123 self.assertRaises(TypeError, root.attrib.pop, 'One', None, None)
124
126
127 Element = self.etree.Element
128 SubElement = self.etree.SubElement
129 ProcessingInstruction = self.etree.ProcessingInstruction
130
131 a = Element('a')
132 a.append(ProcessingInstruction('foo', 'some more text'))
133 self.assertEquals(a[0].target, 'foo')
134 self.assertEquals(a[0].text, 'some more text')
135
137 XML = self.etree.XML
138 root = XML("<test><?mypi my test ?></test>")
139 self.assertEquals(root[0].target, "mypi")
140 self.assertEquals(root[0].text, "my test ")
141
143
144 ProcessingInstruction = self.etree.ProcessingInstruction
145
146 a = ProcessingInstruction("PI", "ONE")
147 b = copy.deepcopy(a)
148 b.text = "ANOTHER"
149
150 self.assertEquals('ONE', a.text)
151 self.assertEquals('ANOTHER', b.text)
152
164
166
167
168 Element = self.etree.Element
169
170 root = Element("root")
171 root.set("attr", "TEST")
172 self.assertEquals("TEST", root.get("attr"))
173 self.assertRaises(TypeError, root.set, "newattr", 5)
174
176
177 parse = self.etree.parse
178
179 f = StringIO('<a><b></c></b></a>')
180 self.assertRaises(SyntaxError, parse, f)
181 f.close()
182
194
196 parse = self.etree.parse
197 tostring = self.etree.tostring
198 XMLParser = self.etree.XMLParser
199
200 xml = '<?test?><a><?A?><b><?B?><c/></b><?C?></a><?tail?>'
201
202 f = StringIO(xml)
203 tree = parse(f)
204 self.assertEquals(
205 xml,
206 tostring(tree))
207
208 f = StringIO(xml)
209 parser = XMLParser(remove_pis=True)
210 tree = parse(f, parser)
211 self.assertEquals(
212 '<a><b><c/></b></a>',
213 tostring(tree))
214
219
221 parse = self.etree.parse
222
223 f = StringIO('<a><b></c></b></a>')
224 self.etree.clearErrorLog()
225 try:
226 parse(f)
227 logs = None
228 except SyntaxError, e:
229 logs = e.error_log
230 f.close()
231 self.assert_([ log for log in logs
232 if 'mismatch' in log.message ])
233 self.assert_([ log for log in logs
234 if 'PARSER' in log.domain_name])
235 self.assert_([ log for log in logs
236 if 'TAG_NAME_MISMATCH' in log.type_name ])
237
244
257
268
274
276 iterparse = self.etree.iterparse
277 f = StringIO("""
278 <a> \n \n <b> b test </b> \n
279
280 \n\t <c> \n </c> </a> \n """)
281 iterator = iterparse(f, remove_blank_text=True)
282 text = [ (element.text, element.tail)
283 for event, element in iterator ]
284 self.assertEquals(
285 [(" b test ", None), (" \n ", None), (None, None)],
286 text)
287
289 iterparse = self.etree.iterparse
290 f = StringIO('<a><b><d/></b><c/></a>')
291
292 iterator = iterparse(f, tag="b", events=('start', 'end'))
293 events = list(iterator)
294 root = iterator.root
295 self.assertEquals(
296 [('start', root[0]), ('end', root[0])],
297 events)
298
300 iterparse = self.etree.iterparse
301 f = StringIO('<a><b><d/></b><c/></a>')
302
303 iterator = iterparse(f, tag="*", events=('start', 'end'))
304 events = list(iterator)
305 self.assertEquals(
306 8,
307 len(events))
308
310 iterwalk = self.etree.iterwalk
311 root = self.etree.XML('<a><b><d/></b><c/></a>')
312
313 iterator = iterwalk(root, tag="b", events=('start', 'end'))
314 events = list(iterator)
315 self.assertEquals(
316 [('start', root[0]), ('end', root[0])],
317 events)
318
320 iterwalk = self.etree.iterwalk
321 root = self.etree.XML('<a><b><d/></b><c/></a>')
322
323 iterator = iterwalk(root, tag="*", events=('start', 'end'))
324 events = list(iterator)
325 self.assertEquals(
326 8,
327 len(events))
328
330 iterwalk = self.etree.iterwalk
331 root = self.etree.XML('<a><b></b><c/></a>')
332
333 events = list(iterwalk(root))
334 self.assertEquals(
335 [('end', root[0]), ('end', root[1]), ('end', root)],
336 events)
337
339 iterwalk = self.etree.iterwalk
340 root = self.etree.XML('<a><b></b><c/></a>')
341
342 iterator = iterwalk(root, events=('start',))
343 events = list(iterator)
344 self.assertEquals(
345 [('start', root), ('start', root[0]), ('start', root[1])],
346 events)
347
349 iterwalk = self.etree.iterwalk
350 root = self.etree.XML('<a><b></b><c/></a>')
351
352 iterator = iterwalk(root, events=('start','end'))
353 events = list(iterator)
354 self.assertEquals(
355 [('start', root), ('start', root[0]), ('end', root[0]),
356 ('start', root[1]), ('end', root[1]), ('end', root)],
357 events)
358
360 iterwalk = self.etree.iterwalk
361 root = self.etree.XML('<a><b></b><c/></a>')
362
363 iterator = iterwalk(root)
364 for event, elem in iterator:
365 elem.clear()
366
367 self.assertEquals(0,
368 len(root))
369
371 iterwalk = self.etree.iterwalk
372 root = self.etree.XML('<a xmlns="ns1"><b><c xmlns="ns2"/></b></a>')
373
374 attr_name = '{testns}bla'
375 events = []
376 iterator = iterwalk(root, events=('start','end','start-ns','end-ns'))
377 for event, elem in iterator:
378 events.append(event)
379 if event == 'start':
380 if elem.tag != '{ns1}a':
381 elem.set(attr_name, 'value')
382
383 self.assertEquals(
384 ['start-ns', 'start', 'start', 'start-ns', 'start',
385 'end', 'end-ns', 'end', 'end', 'end-ns'],
386 events)
387
388 self.assertEquals(
389 None,
390 root.get(attr_name))
391 self.assertEquals(
392 'value',
393 root[0].get(attr_name))
394
396 iterwalk = self.etree.iterwalk
397 root = self.etree.XML('<a><b><d/></b><c/></a>')
398
399 counts = []
400 for event, elem in iterwalk(root):
401 counts.append(len(list(elem.getiterator())))
402 self.assertEquals(
403 [1,2,1,4],
404 counts)
405
407 parse = self.etree.parse
408 parser = self.etree.XMLParser(dtd_validation=True)
409 assertEqual = self.assertEqual
410 test_url = u"__nosuch.dtd"
411
412 class MyResolver(self.etree.Resolver):
413 def resolve(self, url, id, context):
414 assertEqual(url, test_url)
415 return self.resolve_string(
416 u'<!ENTITY myentity "%s">' % url, context)
417
418 parser.resolvers.add(MyResolver())
419
420 xml = u'<!DOCTYPE doc SYSTEM "%s"><doc>&myentity;</doc>' % test_url
421 tree = parse(StringIO(xml), parser)
422 root = tree.getroot()
423 self.assertEquals(root.text, test_url)
424
426 parse = self.etree.parse
427 parser = self.etree.XMLParser(dtd_validation=True)
428 assertEqual = self.assertEqual
429 test_url = u"__nosuch.dtd"
430
431 class check(object):
432 resolved = False
433
434 class MyResolver(self.etree.Resolver):
435 def resolve(self, url, id, context):
436 assertEqual(url, test_url)
437 check.resolved = True
438 return self.resolve_empty(context)
439
440 parser.resolvers.add(MyResolver())
441
442 xml = u'<!DOCTYPE doc SYSTEM "%s"><doc>&myentity;</doc>' % test_url
443 tree = parse(StringIO(xml), parser)
444 self.assert_(check.resolved)
445
446 root = tree.getroot()
447 self.assertEquals(root.text, None)
448
450 parse = self.etree.parse
451 parser = self.etree.XMLParser(dtd_validation=True)
452 test_url = u"__nosuch.dtd"
453
454 class _LocalException(Exception):
455 pass
456
457 class MyResolver(self.etree.Resolver):
458 def resolve(self, url, id, context):
459 raise _LocalException
460
461 parser.resolvers.add(MyResolver())
462
463 xml = u'<!DOCTYPE doc SYSTEM "test"><doc>&myentity;</doc>'
464 self.assertRaises(_LocalException, parse, StringIO(xml), parser)
465
466
476
481
494
507
513
519
534
547
562
575
590
603
618
631
632
634 XML = self.etree.XML
635
636 root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>')
637 values = root.values()
638 values.sort()
639 self.assertEquals(['Alpha', 'Beta', 'Gamma'], values)
640
641
651
652
667
668
678
679
695
696
707
708
719
720
725
726
728 self.assertRaises(TypeError, etree.dump, None)
729
731 ElementTree = self.etree.ElementTree
732
733 f = StringIO('<a xmlns:foo="http://www.infrae.com/ns/1"><foo:b/></a>')
734 doc = ElementTree(file=f)
735 a = doc.getroot()
736 self.assertEquals(
737 None,
738 a.prefix)
739 self.assertEquals(
740 'foo',
741 a[0].prefix)
742
744 ElementTree = self.etree.ElementTree
745
746 f = StringIO('<a xmlns="http://www.infrae.com/ns/1"><b/></a>')
747 doc = ElementTree(file=f)
748 a = doc.getroot()
749 self.assertEquals(
750 None,
751 a.prefix)
752 self.assertEquals(
753 None,
754 a[0].prefix)
755
776
778 XML = self.etree.XML
779
780 root = XML('<doc><one/><two>Two</two>Hm<three/></doc>')
781 result = []
782 for el in root.iterchildren():
783 result.append(el.tag)
784 self.assertEquals(['one', 'two', 'three'], result)
785
787 XML = self.etree.XML
788
789 root = XML('<doc><one/><two>Two</two>Hm<three/></doc>')
790 result = []
791 for el in root.iterchildren(reversed=True):
792 result.append(el.tag)
793 self.assertEquals(['three', 'two', 'one'], result)
794
796 XML = self.etree.XML
797
798 root = XML('<doc><one/><two>Two</two>Hm<two>Bla</two></doc>')
799 result = []
800 for el in root.iterchildren(tag='two'):
801 result.append(el.text)
802 self.assertEquals(['Two', 'Bla'], result)
803
805 XML = self.etree.XML
806
807 root = XML('<doc><one/><two>Two</two>Hm<two>Bla</two></doc>')
808 result = []
809 for el in root.iterchildren(reversed=True, tag='two'):
810 result.append(el.text)
811 self.assertEquals(['Bla', 'Two'], result)
812
814 Element = self.etree.Element
815 SubElement = self.etree.SubElement
816
817 a = Element('a')
818 b = SubElement(a, 'b')
819 c = SubElement(a, 'c')
820 d = SubElement(b, 'd')
821 self.assertEquals(
822 [],
823 list(a.iterancestors()))
824 self.assertEquals(
825 [a],
826 list(b.iterancestors()))
827 self.assertEquals(
828 a,
829 c.iterancestors().next())
830 self.assertEquals(
831 [b, a],
832 list(d.iterancestors()))
833
845
862
883
901
918
936
938 Element = self.etree.Element
939 SubElement = self.etree.SubElement
940
941 a = Element('a')
942 b = SubElement(a, 'b')
943 c = SubElement(a, 'c')
944 d = SubElement(b, 'd')
945 self.assertEquals(
946 [],
947 list(a.itersiblings()))
948 self.assertEquals(
949 [c],
950 list(b.itersiblings()))
951 self.assertEquals(
952 c,
953 b.itersiblings().next())
954 self.assertEquals(
955 [],
956 list(c.itersiblings()))
957 self.assertEquals(
958 [b],
959 list(c.itersiblings(preceding=True)))
960 self.assertEquals(
961 [],
962 list(b.itersiblings(preceding=True)))
963
965 Element = self.etree.Element
966 SubElement = self.etree.SubElement
967
968 a = Element('a')
969 b = SubElement(a, 'b')
970 c = SubElement(a, 'c')
971 d = SubElement(b, 'd')
972 self.assertEquals(
973 [],
974 list(a.itersiblings(tag='XXX')))
975 self.assertEquals(
976 [c],
977 list(b.itersiblings(tag='c')))
978 self.assertEquals(
979 [b],
980 list(c.itersiblings(preceding=True, tag='b')))
981 self.assertEquals(
982 [],
983 list(c.itersiblings(preceding=True, tag='c')))
984
986 parseid = self.etree.parseid
987 XML = self.etree.XML
988 xml_text = '''
989 <!DOCTYPE document [
990 <!ELEMENT document (h1,p)*>
991 <!ELEMENT h1 (#PCDATA)>
992 <!ATTLIST h1 myid ID #REQUIRED>
993 <!ELEMENT p (#PCDATA)>
994 <!ATTLIST p someid ID #REQUIRED>
995 ]>
996 <document>
997 <h1 myid="chapter1">...</h1>
998 <p id="note1" class="note">...</p>
999 <p>Regular paragraph.</p>
1000 <p xml:id="xmlid">XML:ID paragraph.</p>
1001 <p someid="warn1" class="warning">...</p>
1002 </document>
1003 '''
1004
1005 tree, dic = parseid(StringIO(xml_text))
1006 root = tree.getroot()
1007 root2 = XML(xml_text)
1008 self.assertEquals(self._writeElement(root),
1009 self._writeElement(root2))
1010 expected = {
1011 "chapter1" : root[0],
1012 "xmlid" : root[3],
1013 "warn1" : root[4]
1014 }
1015 self.assert_("chapter1" in dic)
1016 self.assert_("warn1" in dic)
1017 self.assert_("xmlid" in dic)
1018 self._checkIDDict(dic, expected)
1019
1021 XMLDTDID = self.etree.XMLDTDID
1022 XML = self.etree.XML
1023 xml_text = '''
1024 <!DOCTYPE document [
1025 <!ELEMENT document (h1,p)*>
1026 <!ELEMENT h1 (#PCDATA)>
1027 <!ATTLIST h1 myid ID #REQUIRED>
1028 <!ELEMENT p (#PCDATA)>
1029 <!ATTLIST p someid ID #REQUIRED>
1030 ]>
1031 <document>
1032 <h1 myid="chapter1">...</h1>
1033 <p id="note1" class="note">...</p>
1034 <p>Regular paragraph.</p>
1035 <p xml:id="xmlid">XML:ID paragraph.</p>
1036 <p someid="warn1" class="warning">...</p>
1037 </document>
1038 '''
1039
1040 root, dic = XMLDTDID(xml_text)
1041 root2 = XML(xml_text)
1042 self.assertEquals(self._writeElement(root),
1043 self._writeElement(root2))
1044 expected = {
1045 "chapter1" : root[0],
1046 "xmlid" : root[3],
1047 "warn1" : root[4]
1048 }
1049 self.assert_("chapter1" in dic)
1050 self.assert_("warn1" in dic)
1051 self.assert_("xmlid" in dic)
1052 self._checkIDDict(dic, expected)
1053
1055 XMLDTDID = self.etree.XMLDTDID
1056 XML = self.etree.XML
1057 xml_text = '''
1058 <document>
1059 <h1 myid="chapter1">...</h1>
1060 <p id="note1" class="note">...</p>
1061 <p>Regular paragraph.</p>
1062 <p someid="warn1" class="warning">...</p>
1063 </document>
1064 '''
1065
1066 root, dic = XMLDTDID(xml_text)
1067 root2 = XML(xml_text)
1068 self.assertEquals(self._writeElement(root),
1069 self._writeElement(root2))
1070 expected = {}
1071 self._checkIDDict(dic, expected)
1072
1074 self.assertEquals(dic, expected)
1075 self.assertEquals(len(dic),
1076 len(expected))
1077 self.assertEquals(sorted(dic.items()),
1078 sorted(expected.items()))
1079 self.assertEquals(sorted(dic.iteritems()),
1080 sorted(expected.iteritems()))
1081 self.assertEquals(sorted(dic.keys()),
1082 sorted(expected.keys()))
1083 self.assertEquals(sorted(dic.iterkeys()),
1084 sorted(expected.iterkeys()))
1085 self.assertEquals(sorted(dic.values()),
1086 sorted(expected.values()))
1087 self.assertEquals(sorted(dic.itervalues()),
1088 sorted(expected.itervalues()))
1089
1091 etree = self.etree
1092
1093 r = {'foo': 'http://ns.infrae.com/foo'}
1094 e = etree.Element('{http://ns.infrae.com/foo}bar', nsmap=r)
1095 self.assertEquals(
1096 'foo',
1097 e.prefix)
1098 self.assertEquals(
1099 '<foo:bar xmlns:foo="http://ns.infrae.com/foo"></foo:bar>',
1100 self._writeElement(e))
1101
1103 etree = self.etree
1104
1105 r = {None: 'http://ns.infrae.com/foo'}
1106 e = etree.Element('{http://ns.infrae.com/foo}bar', nsmap=r)
1107 self.assertEquals(
1108 None,
1109 e.prefix)
1110 self.assertEquals(
1111 '{http://ns.infrae.com/foo}bar',
1112 e.tag)
1113 self.assertEquals(
1114 '<bar xmlns="http://ns.infrae.com/foo"></bar>',
1115 self._writeElement(e))
1116
1118 etree = self.etree
1119
1120 r = {None: 'http://ns.infrae.com/foo',
1121 'hoi': 'http://ns.infrae.com/hoi'}
1122 e = etree.Element('{http://ns.infrae.com/foo}bar', nsmap=r)
1123 e.set('{http://ns.infrae.com/hoi}test', 'value')
1124 self.assertEquals(
1125 '<bar xmlns="http://ns.infrae.com/foo" xmlns:hoi="http://ns.infrae.com/hoi" hoi:test="value"></bar>',
1126 self._writeElement(e))
1127
1129 etree = self.etree
1130 r = {None: 'http://ns.infrae.com/foo',
1131 'hoi': 'http://ns.infrae.com/hoi'}
1132 e = etree.Element('{http://ns.infrae.com/foo}z', nsmap=r)
1133 tree = etree.ElementTree(element=e)
1134 etree.SubElement(e, '{http://ns.infrae.com/hoi}x')
1135 self.assertEquals(
1136 '<z xmlns="http://ns.infrae.com/foo" xmlns:hoi="http://ns.infrae.com/hoi"><hoi:x></hoi:x></z>',
1137 self._writeElement(e))
1138
1140 etree = self.etree
1141
1142 r = {None: 'http://ns.infrae.com/foo'}
1143 e1 = etree.Element('{http://ns.infrae.com/foo}bar', nsmap=r)
1144 e2 = etree.Element('{http://ns.infrae.com/foo}bar', nsmap=r)
1145
1146 e1.append(e2)
1147
1148 self.assertEquals(
1149 None,
1150 e1.prefix)
1151 self.assertEquals(
1152 None,
1153 e1[0].prefix)
1154 self.assertEquals(
1155 '{http://ns.infrae.com/foo}bar',
1156 e1.tag)
1157 self.assertEquals(
1158 '{http://ns.infrae.com/foo}bar',
1159 e1[0].tag)
1160
1162 etree = self.etree
1163
1164 r = {None: 'http://ns.infrae.com/BAR'}
1165 e1 = etree.Element('{http://ns.infrae.com/BAR}bar', nsmap=r)
1166 e2 = etree.Element('{http://ns.infrae.com/foo}bar', nsmap=r)
1167
1168 e1.append(e2)
1169
1170 self.assertEquals(
1171 None,
1172 e1.prefix)
1173 self.assertNotEquals(
1174 None,
1175 e2.prefix)
1176 self.assertEquals(
1177 '{http://ns.infrae.com/BAR}bar',
1178 e1.tag)
1179 self.assertEquals(
1180 '{http://ns.infrae.com/foo}bar',
1181 e2.tag)
1182
1184 ns_href = "http://a.b.c"
1185 one = self.etree.parse(
1186 StringIO('<foo><bar xmlns:ns="%s"><ns:baz/></bar></foo>' % ns_href))
1187 baz = one.getroot()[0][0]
1188
1189 two = self.etree.parse(
1190 StringIO('<root xmlns:ns="%s"/>' % ns_href))
1191 two.getroot().append(baz)
1192 del one
1193
1194 self.assertEquals('{%s}baz' % ns_href, baz.tag)
1195 self.assertEquals(
1196 '<root xmlns:ns="%s"><ns:baz/></root>' % ns_href,
1197 self.etree.tostring(two))
1198
1200
1201 parse = self.etree.parse
1202 tostring = self.etree.tostring
1203
1204 ns_href = "http://a.b.c"
1205 one = parse(
1206 StringIO('<foo><bar xmlns:ns="%s"><ns:baz/></bar></foo>' % ns_href))
1207 baz = one.getroot()[0][0]
1208
1209 print tostring(baz)
1210 parsed = parse(StringIO( tostring(baz) )).getroot()
1211
1212 self.assertEquals('{%s}baz' % ns_href, parsed.tag)
1213
1215 etree = self.etree
1216
1217 r = {None: 'http://ns.infrae.com/foo',
1218 'hoi': 'http://ns.infrae.com/hoi'}
1219 e = etree.Element('{http://ns.infrae.com/foo}bar', nsmap=r)
1220 self.assertEquals(
1221 r,
1222 e.nsmap)
1223
1225 etree = self.etree
1226
1227 re = {None: 'http://ns.infrae.com/foo',
1228 'hoi': 'http://ns.infrae.com/hoi'}
1229 e = etree.Element('{http://ns.infrae.com/foo}bar', nsmap=re)
1230
1231 rs = {None: 'http://ns.infrae.com/honk',
1232 'top': 'http://ns.infrae.com/top'}
1233 s = etree.SubElement(e, '{http://ns.infrae.com/honk}bar', nsmap=rs)
1234
1235 r = re.copy()
1236 r.update(rs)
1237 self.assertEquals(
1238 re,
1239 e.nsmap)
1240 self.assertEquals(
1241 r,
1242 s.nsmap)
1243
1245 Element = self.etree.Element
1246 SubElement = self.etree.SubElement
1247
1248 a = Element('{a}a')
1249 b = SubElement(a, '{a}b')
1250 c = SubElement(a, '{a}c')
1251 d = SubElement(b, '{b}d')
1252 e = SubElement(c, '{a}e')
1253 f = SubElement(c, '{b}f')
1254
1255 self.assertEquals(
1256 [a],
1257 list(a.getiterator('{a}a')))
1258 self.assertEquals(
1259 [],
1260 list(a.getiterator('{b}a')))
1261 self.assertEquals(
1262 [],
1263 list(a.getiterator('a')))
1264 self.assertEquals(
1265 [f],
1266 list(c.getiterator('{b}*')))
1267 self.assertEquals(
1268 [d, f],
1269 list(a.getiterator('{b}*')))
1270
1286
1303
1305 XML = self.etree.XML
1306 root = XML('<a xmlns:x="X" xmlns:y="Y"><x:b><c/></x:b><b/><c><x:b/><b/></c><b/></a>')
1307 self.assertEquals(len(root.findall(".//{X}b")), 2)
1308 self.assertEquals(len(root.findall(".//{X}*")), 2)
1309 self.assertEquals(len(root.findall(".//b")), 3)
1310
1312 etree = self.etree
1313 e = etree.Element('foo')
1314 for i in range(10):
1315 etree.SubElement(e, 'a%s' % i)
1316 for i in range(10):
1317 self.assertEquals(
1318 i,
1319 e.index(e[i]))
1320 self.assertEquals(
1321 3, e.index(e[3], 3))
1322 self.assertRaises(
1323 ValueError, e.index, e[3], 4)
1324 self.assertRaises(
1325 ValueError, e.index, e[3], 0, 2)
1326 self.assertRaises(
1327 ValueError, e.index, e[8], 0, -3)
1328 self.assertRaises(
1329 ValueError, e.index, e[8], -5, -3)
1330 self.assertEquals(
1331 8, e.index(e[8], 0, -1))
1332 self.assertEquals(
1333 8, e.index(e[8], -12, -1))
1334 self.assertEquals(
1335 0, e.index(e[0], -12, -1))
1336
1338 etree = self.etree
1339 e = etree.Element('foo')
1340 for i in range(10):
1341 el = etree.SubElement(e, 'a%s' % i)
1342 el.text = "text%d" % i
1343 el.tail = "tail%d" % i
1344
1345 child0 = e[0]
1346 child1 = e[1]
1347 child2 = e[2]
1348
1349 e.replace(e[0], e[1])
1350 self.assertEquals(
1351 9, len(e))
1352 self.assertEquals(
1353 child1, e[0])
1354 self.assertEquals(
1355 child1.text, "text1")
1356 self.assertEquals(
1357 child1.tail, "tail1")
1358 self.assertEquals(
1359 child0.tail, "tail0")
1360 self.assertEquals(
1361 child2, e[1])
1362
1363 e.replace(e[-1], e[0])
1364 self.assertEquals(
1365 child1, e[-1])
1366 self.assertEquals(
1367 child1.text, "text1")
1368 self.assertEquals(
1369 child1.tail, "tail1")
1370 self.assertEquals(
1371 child2, e[0])
1372
1374 etree = self.etree
1375 e = etree.Element('foo')
1376 for i in range(10):
1377 etree.SubElement(e, 'a%s' % i)
1378
1379 new_element = etree.Element("test")
1380 new_element.text = "TESTTEXT"
1381 new_element.tail = "TESTTAIL"
1382 child1 = e[1]
1383 e.replace(e[0], new_element)
1384 self.assertEquals(
1385 new_element, e[0])
1386 self.assertEquals(
1387 "TESTTEXT",
1388 e[0].text)
1389 self.assertEquals(
1390 "TESTTAIL",
1391 e[0].tail)
1392 self.assertEquals(
1393 child1, e[1])
1394
1396 etree = self.etree
1397 root = etree.Element('foo')
1398 for i in range(3):
1399 element = etree.SubElement(root, 'a%s' % i)
1400 element.text = "text%d" % i
1401 element.tail = "tail%d" % i
1402
1403 elements = []
1404 for i in range(3):
1405 new_element = etree.Element("test%s" % i)
1406 new_element.text = "TEXT%s" % i
1407 new_element.tail = "TAIL%s" % i
1408 elements.append(new_element)
1409
1410 root.extend(elements)
1411
1412 self.assertEquals(
1413 ["a0", "a1", "a2", "test0", "test1", "test2"],
1414 [ el.tag for el in root ])
1415 self.assertEquals(
1416 ["text0", "text1", "text2", "TEXT0", "TEXT1", "TEXT2"],
1417 [ el.text for el in root ])
1418 self.assertEquals(
1419 ["tail0", "tail1", "tail2", "TAIL0", "TAIL1", "TAIL2"],
1420 [ el.tail for el in root ])
1421
1423 XML = self.etree.XML
1424 root = XML('''<?xml version="1.0"?>
1425 <root><test>
1426
1427 <bla/></test>
1428 </root>
1429 ''')
1430
1431 self.assertEquals(
1432 [2, 2, 4],
1433 [ el.sourceline for el in root.getiterator() ])
1434
1436 parse = self.etree.parse
1437 tree = parse(fileInTestDir('include/test_xinclude.xml'))
1438
1439 self.assertEquals(
1440 [1, 2, 3],
1441 [ el.sourceline for el in tree.getiterator() ])
1442
1452
1454 etree = self.etree
1455 root = etree.XML("<root/>", base_url="http://no/such/url")
1456 docinfo = root.getroottree().docinfo
1457 self.assertEquals(docinfo.URL, "http://no/such/url")
1458
1460 etree = self.etree
1461 root = etree.HTML("<html/>", base_url="http://no/such/url")
1462 docinfo = root.getroottree().docinfo
1463 self.assertEquals(docinfo.URL, "http://no/such/url")
1464
1466 etree = self.etree
1467 xml_header = '<?xml version="1.0" encoding="ascii"?>'
1468 pub_id = "-//W3C//DTD XHTML 1.0 Transitional//EN"
1469 sys_id = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
1470 doctype_string = '<!DOCTYPE html PUBLIC "%s" "%s">' % (pub_id, sys_id)
1471
1472 xml = xml_header + doctype_string + '<html><body></body></html>'
1473
1474 tree = etree.parse(StringIO(xml))
1475 docinfo = tree.docinfo
1476 self.assertEquals(docinfo.encoding, "ascii")
1477 self.assertEquals(docinfo.xml_version, "1.0")
1478 self.assertEquals(docinfo.public_id, pub_id)
1479 self.assertEquals(docinfo.system_url, sys_id)
1480 self.assertEquals(docinfo.root_name, 'html')
1481 self.assertEquals(docinfo.doctype, doctype_string)
1482
1484 etree = self.etree
1485 xml_header = '<?xml version="1.0" encoding="UTF-8"?>'
1486 sys_id = "some.dtd"
1487 doctype_string = '<!DOCTYPE html SYSTEM "%s">' % sys_id
1488 xml = xml_header + doctype_string + '<html><body></body></html>'
1489
1490 tree = etree.parse(StringIO(xml))
1491 docinfo = tree.docinfo
1492 self.assertEquals(docinfo.encoding, "UTF-8")
1493 self.assertEquals(docinfo.xml_version, "1.0")
1494 self.assertEquals(docinfo.public_id, None)
1495 self.assertEquals(docinfo.system_url, sys_id)
1496 self.assertEquals(docinfo.root_name, 'html')
1497 self.assertEquals(docinfo.doctype, doctype_string)
1498
1500 etree = self.etree
1501 xml = '<html><body></body></html>'
1502 tree = etree.parse(StringIO(xml))
1503 docinfo = tree.docinfo
1504 self.assertEquals(docinfo.encoding, None)
1505 self.assertEquals(docinfo.xml_version, "1.0")
1506 self.assertEquals(docinfo.public_id, None)
1507 self.assertEquals(docinfo.system_url, None)
1508 self.assertEquals(docinfo.root_name, 'html')
1509 self.assertEquals(docinfo.doctype, '')
1510
1512
1513 xml = '''\
1514 <!DOCTYPE test SYSTEM "test.dtd" [
1515 <!ENTITY entity "tasty">
1516 <!ELEMENT test (a)>
1517 <!ELEMENT a (#PCDATA)>
1518 ]>
1519 <test><a>test-test</a></test>\
1520 '''
1521 root = self.etree.parse(StringIO(xml))
1522 self.assertEqual(self.etree.tostring(root).replace(" ", ""),
1523 xml.replace(" ", ""))
1524
1526 Element = self.etree.Element
1527
1528 a = Element('a')
1529 self.assertRaises(AssertionError, setattr, a, "text", 'ha\0ho')
1530 self.assertRaises(AssertionError, setattr, a, "tail", 'ha\0ho')
1531
1532 self.assertRaises(AssertionError, Element, 'ha\0ho')
1533
1535 Element = self.etree.Element
1536
1537 a = Element('a')
1538 self.assertRaises(AssertionError, setattr, a, "text", u'ha\0ho')
1539 self.assertRaises(AssertionError, setattr, a, "tail", u'ha\0ho')
1540
1541 self.assertRaises(AssertionError, Element, u'ha\0ho')
1542
1544 Element = self.etree.Element
1545
1546 a = Element('a')
1547 self.assertRaises(AssertionError, setattr, a, "text", 'ha\x07ho')
1548 self.assertRaises(AssertionError, setattr, a, "text", 'ha\x02ho')
1549
1550 self.assertRaises(AssertionError, setattr, a, "tail", 'ha\x07ho')
1551 self.assertRaises(AssertionError, setattr, a, "tail", 'ha\x02ho')
1552
1553 self.assertRaises(AssertionError, Element, 'ha\x07ho')
1554 self.assertRaises(AssertionError, Element, 'ha\x02ho')
1555
1557 Element = self.etree.Element
1558
1559 a = Element('a')
1560 self.assertRaises(AssertionError, setattr, a, "text", u'ha\x07ho')
1561 self.assertRaises(AssertionError, setattr, a, "text", u'ha\x02ho')
1562
1563 self.assertRaises(AssertionError, setattr, a, "tail", u'ha\x07ho')
1564 self.assertRaises(AssertionError, setattr, a, "tail", u'ha\x02ho')
1565
1566 self.assertRaises(AssertionError, Element, u'ha\x07ho')
1567 self.assertRaises(AssertionError, Element, u'ha\x02ho')
1568
1582
1587
1605
1618
1634
1638
1653
1671
1681
1682
1685 filename = fileInTestDir('test_broken.xml')
1686 root = etree.XML('''\
1687 <doc xmlns:xi="http://www.w3.org/2001/XInclude">
1688 <xi:include href="%s" parse="text"/>
1689 </doc>
1690 ''' % filename)
1691 old_text = root.text
1692 content = open(filename).read()
1693 old_tail = root[0].tail
1694
1695 self.include( etree.ElementTree(root) )
1696 self.assertEquals(old_text + content + old_tail,
1697 root.text)
1698
1700 tree = etree.parse(fileInTestDir('include/test_xinclude.xml'))
1701
1702 self.include( tree )
1703
1704 self.assertEquals(
1705 'a',
1706 tree.getroot()[1].tag)
1707
1711
1712
1717
1718
1721 tree = self.parse('<a><b/></a>')
1722 f = StringIO()
1723 tree.write_c14n(f)
1724 s = f.getvalue()
1725 self.assertEquals('<a><b></b></a>',
1726 s)
1727
1729 suite = unittest.TestSuite()
1730 suite.addTests([unittest.makeSuite(ETreeOnlyTestCase)])
1731 suite.addTests([unittest.makeSuite(ETreeXIncludeTestCase)])
1732 suite.addTests([unittest.makeSuite(ElementIncludeTestCase)])
1733 suite.addTests([unittest.makeSuite(ETreeC14NTestCase)])
1734 suite.addTests(
1735 [doctest.DocFileSuite('../../../doc/tutorial.txt')])
1736 suite.addTests(
1737 [doctest.DocFileSuite('../../../doc/api.txt')])
1738 suite.addTests(
1739 [doctest.DocFileSuite('../../../doc/parsing.txt')])
1740 suite.addTests(
1741 [doctest.DocFileSuite('../../../doc/resolvers.txt')])
1742 return suite
1743
1744 if __name__ == '__main__':
1745 unittest.main()
1746