blob: 5019722ed10fab9c7075ddaad5262417d7070de5 [file] [log] [blame]
Antoine Pitroub27ddc72010-10-27 18:58:04 +00001# regression test for SAX 2.0 -*- coding: utf-8 -*-
Lars Gustäbel96753b32000-09-24 12:24:24 +00002# $Id$
3
Fred Drakefbdeaad2006-07-29 16:56:15 +00004from xml.sax import make_parser, ContentHandler, \
5 SAXException, SAXReaderNotAvailable, SAXParseException
Martin v. Löwis962c9e72000-10-06 17:41:52 +00006try:
7 make_parser()
Martin v. Löwis80670bc2000-10-06 21:13:23 +00008except SAXReaderNotAvailable:
Martin v. Löwis962c9e72000-10-06 17:41:52 +00009 # don't try to test this module if we cannot create a parser
10 raise ImportError("no XML parsers available")
Fred Drakefbdeaad2006-07-29 16:56:15 +000011from xml.sax.saxutils import XMLGenerator, escape, unescape, quoteattr, \
Serhiy Storchakae9d4dc12015-04-02 20:55:46 +030012 XMLFilterBase, prepare_input_source
Fred Drakefbdeaad2006-07-29 16:56:15 +000013from xml.sax.expatreader import create_parser
Antoine Pitrou7f081022010-10-27 18:43:21 +000014from xml.sax.handler import feature_namespaces
Fred Drakefbdeaad2006-07-29 16:56:15 +000015from xml.sax.xmlreader import InputSource, AttributesImpl, AttributesNSImpl
Lars Gustäbel96753b32000-09-24 12:24:24 +000016from cStringIO import StringIO
Serhiy Storchakaf8980382013-02-10 14:26:08 +020017import io
Serhiy Storchakaaff77f32015-04-02 23:05:23 +030018import gc
Serhiy Storchaka23298cb2013-02-02 12:16:22 +020019import os.path
Serhiy Storchaka8673ab92013-02-02 10:28:30 +020020import shutil
21import test.test_support as support
Serhiy Storchakaaff77f32015-04-02 23:05:23 +030022from test.test_support import findfile, run_unittest, TESTFN
Collin Winterd28fcbc2007-03-28 23:34:06 +000023import unittest
Lars Gustäbel96753b32000-09-24 12:24:24 +000024
Florent Xicluna1b51c3d2010-03-13 12:41:48 +000025TEST_XMLFILE = findfile("test.xml", subdir="xmltestdata")
26TEST_XMLFILE_OUT = findfile("test.xml.out", subdir="xmltestdata")
Florent Xicluna13ba1a12010-03-13 11:18:49 +000027
Serhiy Storchaka23298cb2013-02-02 12:16:22 +020028supports_unicode_filenames = True
29if not os.path.supports_unicode_filenames:
30 try:
31 support.TESTFN_UNICODE.encode(support.TESTFN_ENCODING)
32 except (AttributeError, UnicodeError, TypeError):
33 # Either the file system encoding is None, or the file name
34 # cannot be encoded in the file system encoding.
35 supports_unicode_filenames = False
36requires_unicode_filenames = unittest.skipUnless(
37 supports_unicode_filenames,
38 'Requires unicode filenames support')
39
Collin Winterd28fcbc2007-03-28 23:34:06 +000040ns_uri = "http://www.python.org/xml-ns/saxtest/"
Lars Gustäbel96753b32000-09-24 12:24:24 +000041
Collin Winterd28fcbc2007-03-28 23:34:06 +000042class XmlTestBase(unittest.TestCase):
43 def verify_empty_attrs(self, attrs):
44 self.assertRaises(KeyError, attrs.getValue, "attr")
45 self.assertRaises(KeyError, attrs.getValueByQName, "attr")
46 self.assertRaises(KeyError, attrs.getNameByQName, "attr")
47 self.assertRaises(KeyError, attrs.getQNameByName, "attr")
48 self.assertRaises(KeyError, attrs.__getitem__, "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +000049 self.assertEqual(attrs.getLength(), 0)
50 self.assertEqual(attrs.getNames(), [])
51 self.assertEqual(attrs.getQNames(), [])
52 self.assertEqual(len(attrs), 0)
Collin Winterd28fcbc2007-03-28 23:34:06 +000053 self.assertFalse(attrs.has_key("attr"))
Ezio Melotti2623a372010-11-21 13:34:58 +000054 self.assertEqual(attrs.keys(), [])
55 self.assertEqual(attrs.get("attrs"), None)
56 self.assertEqual(attrs.get("attrs", 25), 25)
57 self.assertEqual(attrs.items(), [])
58 self.assertEqual(attrs.values(), [])
Neal Norwitz0d4c06e2007-04-25 06:30:05 +000059
Collin Winterd28fcbc2007-03-28 23:34:06 +000060 def verify_empty_nsattrs(self, attrs):
61 self.assertRaises(KeyError, attrs.getValue, (ns_uri, "attr"))
62 self.assertRaises(KeyError, attrs.getValueByQName, "ns:attr")
63 self.assertRaises(KeyError, attrs.getNameByQName, "ns:attr")
64 self.assertRaises(KeyError, attrs.getQNameByName, (ns_uri, "attr"))
65 self.assertRaises(KeyError, attrs.__getitem__, (ns_uri, "attr"))
Ezio Melotti2623a372010-11-21 13:34:58 +000066 self.assertEqual(attrs.getLength(), 0)
67 self.assertEqual(attrs.getNames(), [])
68 self.assertEqual(attrs.getQNames(), [])
69 self.assertEqual(len(attrs), 0)
Collin Winterd28fcbc2007-03-28 23:34:06 +000070 self.assertFalse(attrs.has_key((ns_uri, "attr")))
Ezio Melotti2623a372010-11-21 13:34:58 +000071 self.assertEqual(attrs.keys(), [])
72 self.assertEqual(attrs.get((ns_uri, "attr")), None)
73 self.assertEqual(attrs.get((ns_uri, "attr"), 25), 25)
74 self.assertEqual(attrs.items(), [])
75 self.assertEqual(attrs.values(), [])
Lars Gustäbel96753b32000-09-24 12:24:24 +000076
Collin Winterd28fcbc2007-03-28 23:34:06 +000077 def verify_attrs_wattr(self, attrs):
Ezio Melotti2623a372010-11-21 13:34:58 +000078 self.assertEqual(attrs.getLength(), 1)
79 self.assertEqual(attrs.getNames(), ["attr"])
80 self.assertEqual(attrs.getQNames(), ["attr"])
81 self.assertEqual(len(attrs), 1)
Collin Winterd28fcbc2007-03-28 23:34:06 +000082 self.assertTrue(attrs.has_key("attr"))
Ezio Melotti2623a372010-11-21 13:34:58 +000083 self.assertEqual(attrs.keys(), ["attr"])
84 self.assertEqual(attrs.get("attr"), "val")
85 self.assertEqual(attrs.get("attr", 25), "val")
86 self.assertEqual(attrs.items(), [("attr", "val")])
87 self.assertEqual(attrs.values(), ["val"])
88 self.assertEqual(attrs.getValue("attr"), "val")
89 self.assertEqual(attrs.getValueByQName("attr"), "val")
90 self.assertEqual(attrs.getNameByQName("attr"), "attr")
91 self.assertEqual(attrs["attr"], "val")
92 self.assertEqual(attrs.getQNameByName("attr"), "attr")
Neal Norwitz0d4c06e2007-04-25 06:30:05 +000093
Serhiy Storchakaaff77f32015-04-02 23:05:23 +030094
95def xml_unicode(doc, encoding=None):
96 if encoding is None:
97 return doc
98 return u'<?xml version="1.0" encoding="%s"?>\n%s' % (encoding, doc)
99
100def xml_bytes(doc, encoding, decl_encoding=Ellipsis):
101 if decl_encoding is Ellipsis:
102 decl_encoding = encoding
103 return xml_unicode(doc, decl_encoding).encode(encoding, 'xmlcharrefreplace')
104
105def make_xml_file(doc, encoding, decl_encoding=Ellipsis):
106 if decl_encoding is Ellipsis:
107 decl_encoding = encoding
108 with io.open(TESTFN, 'w', encoding=encoding, errors='xmlcharrefreplace') as f:
109 f.write(xml_unicode(doc, decl_encoding))
110
111
112class ParseTest(unittest.TestCase):
113 data = support.u(r'<money value="$\xa3\u20ac\U0001017b">'
114 r'$\xa3\u20ac\U0001017b</money>')
115
116 def tearDown(self):
117 support.unlink(TESTFN)
118
119 def check_parse(self, f):
120 from xml.sax import parse
121 result = StringIO()
122 parse(f, XMLGenerator(result, 'utf-8'))
123 self.assertEqual(result.getvalue(), xml_bytes(self.data, 'utf-8'))
124
125 def test_parse_bytes(self):
126 # UTF-8 is default encoding, US-ASCII is compatible with UTF-8,
127 # UTF-16 is autodetected
128 encodings = ('us-ascii', 'utf-8', 'utf-16', 'utf-16le', 'utf-16be')
129 for encoding in encodings:
130 self.check_parse(io.BytesIO(xml_bytes(self.data, encoding)))
131 make_xml_file(self.data, encoding)
132 self.check_parse(TESTFN)
133 with io.open(TESTFN, 'rb') as f:
134 self.check_parse(f)
135 self.check_parse(io.BytesIO(xml_bytes(self.data, encoding, None)))
136 make_xml_file(self.data, encoding, None)
137 self.check_parse(TESTFN)
138 with io.open(TESTFN, 'rb') as f:
139 self.check_parse(f)
140 # accept UTF-8 with BOM
141 self.check_parse(io.BytesIO(xml_bytes(self.data, 'utf-8-sig', 'utf-8')))
142 make_xml_file(self.data, 'utf-8-sig', 'utf-8')
143 self.check_parse(TESTFN)
144 with io.open(TESTFN, 'rb') as f:
145 self.check_parse(f)
146 self.check_parse(io.BytesIO(xml_bytes(self.data, 'utf-8-sig', None)))
147 make_xml_file(self.data, 'utf-8-sig', None)
148 self.check_parse(TESTFN)
149 with io.open(TESTFN, 'rb') as f:
150 self.check_parse(f)
151 # accept data with declared encoding
152 self.check_parse(io.BytesIO(xml_bytes(self.data, 'iso-8859-1')))
153 make_xml_file(self.data, 'iso-8859-1')
154 self.check_parse(TESTFN)
155 with io.open(TESTFN, 'rb') as f:
156 self.check_parse(f)
157 # fail on non-UTF-8 incompatible data without declared encoding
158 with self.assertRaises(SAXException):
159 self.check_parse(io.BytesIO(xml_bytes(self.data, 'iso-8859-1', None)))
160 make_xml_file(self.data, 'iso-8859-1', None)
161 with self.assertRaises(SAXException):
162 self.check_parse(TESTFN)
163 with io.open(TESTFN, 'rb') as f:
164 with self.assertRaises(SAXException):
165 self.check_parse(f)
166
167 def test_parse_InputSource(self):
168 # accept data without declared but with explicitly specified encoding
169 make_xml_file(self.data, 'iso-8859-1', None)
170 with io.open(TESTFN, 'rb') as f:
171 input = InputSource()
172 input.setByteStream(f)
173 input.setEncoding('iso-8859-1')
174 self.check_parse(input)
175
176 def check_parseString(self, s):
177 from xml.sax import parseString
178 result = StringIO()
179 parseString(s, XMLGenerator(result, 'utf-8'))
180 self.assertEqual(result.getvalue(), xml_bytes(self.data, 'utf-8'))
181
182 def test_parseString_bytes(self):
183 # UTF-8 is default encoding, US-ASCII is compatible with UTF-8,
184 # UTF-16 is autodetected
185 encodings = ('us-ascii', 'utf-8', 'utf-16', 'utf-16le', 'utf-16be')
186 for encoding in encodings:
187 self.check_parseString(xml_bytes(self.data, encoding))
188 self.check_parseString(xml_bytes(self.data, encoding, None))
189 # accept UTF-8 with BOM
190 self.check_parseString(xml_bytes(self.data, 'utf-8-sig', 'utf-8'))
191 self.check_parseString(xml_bytes(self.data, 'utf-8-sig', None))
192 # accept data with declared encoding
193 self.check_parseString(xml_bytes(self.data, 'iso-8859-1'))
194 # fail on non-UTF-8 incompatible data without declared encoding
195 with self.assertRaises(SAXException):
196 self.check_parseString(xml_bytes(self.data, 'iso-8859-1', None))
197
198
Collin Winterd28fcbc2007-03-28 23:34:06 +0000199class MakeParserTest(unittest.TestCase):
200 def test_make_parser2(self):
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000201 # Creating parsers several times in a row should succeed.
202 # Testing this because there have been failures of this kind
203 # before.
Fred Drakefbdeaad2006-07-29 16:56:15 +0000204 from xml.sax import make_parser
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000205 p = make_parser()
Fred Drakefbdeaad2006-07-29 16:56:15 +0000206 from xml.sax import make_parser
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000207 p = make_parser()
Fred Drakefbdeaad2006-07-29 16:56:15 +0000208 from xml.sax import make_parser
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000209 p = make_parser()
Fred Drakefbdeaad2006-07-29 16:56:15 +0000210 from xml.sax import make_parser
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000211 p = make_parser()
Fred Drakefbdeaad2006-07-29 16:56:15 +0000212 from xml.sax import make_parser
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000213 p = make_parser()
Fred Drakefbdeaad2006-07-29 16:56:15 +0000214 from xml.sax import make_parser
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000215 p = make_parser()
Tim Petersd2bf3b72001-01-18 02:22:22 +0000216
217
Lars Gustäbel96753b32000-09-24 12:24:24 +0000218# ===========================================================================
219#
220# saxutils tests
221#
222# ===========================================================================
223
Collin Winterd28fcbc2007-03-28 23:34:06 +0000224class SaxutilsTest(unittest.TestCase):
225 # ===== escape
226 def test_escape_basic(self):
Ezio Melotti2623a372010-11-21 13:34:58 +0000227 self.assertEqual(escape("Donald Duck & Co"), "Donald Duck &amp; Co")
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000228
Collin Winterd28fcbc2007-03-28 23:34:06 +0000229 def test_escape_all(self):
Ezio Melotti2623a372010-11-21 13:34:58 +0000230 self.assertEqual(escape("<Donald Duck & Co>"),
231 "&lt;Donald Duck &amp; Co&gt;")
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000232
Collin Winterd28fcbc2007-03-28 23:34:06 +0000233 def test_escape_extra(self):
Ezio Melotti2623a372010-11-21 13:34:58 +0000234 self.assertEqual(escape("Hei på deg", {"å" : "&aring;"}),
235 "Hei p&aring; deg")
Lars Gustäbel96753b32000-09-24 12:24:24 +0000236
Collin Winterd28fcbc2007-03-28 23:34:06 +0000237 # ===== unescape
238 def test_unescape_basic(self):
Ezio Melotti2623a372010-11-21 13:34:58 +0000239 self.assertEqual(unescape("Donald Duck &amp; Co"), "Donald Duck & Co")
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000240
Collin Winterd28fcbc2007-03-28 23:34:06 +0000241 def test_unescape_all(self):
Ezio Melotti2623a372010-11-21 13:34:58 +0000242 self.assertEqual(unescape("&lt;Donald Duck &amp; Co&gt;"),
243 "<Donald Duck & Co>")
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000244
Collin Winterd28fcbc2007-03-28 23:34:06 +0000245 def test_unescape_extra(self):
Ezio Melotti2623a372010-11-21 13:34:58 +0000246 self.assertEqual(unescape("Hei på deg", {"å" : "&aring;"}),
247 "Hei p&aring; deg")
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000248
Collin Winterd28fcbc2007-03-28 23:34:06 +0000249 def test_unescape_amp_extra(self):
Ezio Melotti2623a372010-11-21 13:34:58 +0000250 self.assertEqual(unescape("&amp;foo;", {"&foo;": "splat"}), "&foo;")
Lars Gustäbel96753b32000-09-24 12:24:24 +0000251
Collin Winterd28fcbc2007-03-28 23:34:06 +0000252 # ===== quoteattr
253 def test_quoteattr_basic(self):
Ezio Melotti2623a372010-11-21 13:34:58 +0000254 self.assertEqual(quoteattr("Donald Duck & Co"),
255 '"Donald Duck &amp; Co"')
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000256
Collin Winterd28fcbc2007-03-28 23:34:06 +0000257 def test_single_quoteattr(self):
Ezio Melotti2623a372010-11-21 13:34:58 +0000258 self.assertEqual(quoteattr('Includes "double" quotes'),
259 '\'Includes "double" quotes\'')
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000260
Collin Winterd28fcbc2007-03-28 23:34:06 +0000261 def test_double_quoteattr(self):
Ezio Melotti2623a372010-11-21 13:34:58 +0000262 self.assertEqual(quoteattr("Includes 'single' quotes"),
263 "\"Includes 'single' quotes\"")
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000264
Collin Winterd28fcbc2007-03-28 23:34:06 +0000265 def test_single_double_quoteattr(self):
Ezio Melotti2623a372010-11-21 13:34:58 +0000266 self.assertEqual(quoteattr("Includes 'single' and \"double\" quotes"),
267 "\"Includes 'single' and &quot;double&quot; quotes\"")
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000268
Collin Winterd28fcbc2007-03-28 23:34:06 +0000269 # ===== make_parser
270 def test_make_parser(self):
Martin v. Löwis962c9e72000-10-06 17:41:52 +0000271 # Creating a parser should succeed - it should fall back
272 # to the expatreader
Fred Drakefbdeaad2006-07-29 16:56:15 +0000273 p = make_parser(['xml.parsers.no_such_parser'])
Martin v. Löwis962c9e72000-10-06 17:41:52 +0000274
275
Serhiy Storchakae9d4dc12015-04-02 20:55:46 +0300276class PrepareInputSourceTest(unittest.TestCase):
277
278 def setUp(self):
279 self.file = support.TESTFN
280 with open(self.file, "w") as tmp:
281 tmp.write("This was read from a file.")
282
283 def tearDown(self):
284 support.unlink(self.file)
285
286 def make_byte_stream(self):
287 return io.BytesIO(b"This is a byte stream.")
288
289 def checkContent(self, stream, content):
290 self.assertIsNotNone(stream)
291 self.assertEqual(stream.read(), content)
292 stream.close()
293
294
295 def test_byte_stream(self):
296 # If the source is an InputSource that does not have a character
297 # stream but does have a byte stream, use the byte stream.
298 src = InputSource(self.file)
299 src.setByteStream(self.make_byte_stream())
300 prep = prepare_input_source(src)
301 self.assertIsNone(prep.getCharacterStream())
302 self.checkContent(prep.getByteStream(),
303 b"This is a byte stream.")
304
305 def test_system_id(self):
306 # If the source is an InputSource that has neither a character
307 # stream nor a byte stream, open the system ID.
308 src = InputSource(self.file)
309 prep = prepare_input_source(src)
310 self.assertIsNone(prep.getCharacterStream())
311 self.checkContent(prep.getByteStream(),
312 b"This was read from a file.")
313
314 def test_string(self):
315 # If the source is a string, use it as a system ID and open it.
316 prep = prepare_input_source(self.file)
317 self.assertIsNone(prep.getCharacterStream())
318 self.checkContent(prep.getByteStream(),
319 b"This was read from a file.")
320
321 def test_binary_file(self):
322 # If the source is a binary file-like object, use it as a byte
323 # stream.
324 prep = prepare_input_source(self.make_byte_stream())
325 self.assertIsNone(prep.getCharacterStream())
326 self.checkContent(prep.getByteStream(),
327 b"This is a byte stream.")
328
329
Lars Gustäbel96753b32000-09-24 12:24:24 +0000330# ===== XMLGenerator
331
332start = '<?xml version="1.0" encoding="iso-8859-1"?>\n'
333
Serhiy Storchakaf8980382013-02-10 14:26:08 +0200334class XmlgenTest:
Collin Winterd28fcbc2007-03-28 23:34:06 +0000335 def test_xmlgen_basic(self):
Serhiy Storchakaf8980382013-02-10 14:26:08 +0200336 result = self.ioclass()
Collin Winterd28fcbc2007-03-28 23:34:06 +0000337 gen = XMLGenerator(result)
338 gen.startDocument()
339 gen.startElement("doc", {})
340 gen.endElement("doc")
341 gen.endDocument()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000342
Ezio Melotti2623a372010-11-21 13:34:58 +0000343 self.assertEqual(result.getvalue(), start + "<doc></doc>")
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000344
Collin Winterd28fcbc2007-03-28 23:34:06 +0000345 def test_xmlgen_content(self):
Serhiy Storchakaf8980382013-02-10 14:26:08 +0200346 result = self.ioclass()
Collin Winterd28fcbc2007-03-28 23:34:06 +0000347 gen = XMLGenerator(result)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000348
Collin Winterd28fcbc2007-03-28 23:34:06 +0000349 gen.startDocument()
350 gen.startElement("doc", {})
351 gen.characters("huhei")
352 gen.endElement("doc")
353 gen.endDocument()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000354
Ezio Melotti2623a372010-11-21 13:34:58 +0000355 self.assertEqual(result.getvalue(), start + "<doc>huhei</doc>")
Lars Gustäbel96753b32000-09-24 12:24:24 +0000356
Collin Winterd28fcbc2007-03-28 23:34:06 +0000357 def test_xmlgen_pi(self):
Serhiy Storchakaf8980382013-02-10 14:26:08 +0200358 result = self.ioclass()
Collin Winterd28fcbc2007-03-28 23:34:06 +0000359 gen = XMLGenerator(result)
Lars Gustäbel96753b32000-09-24 12:24:24 +0000360
Collin Winterd28fcbc2007-03-28 23:34:06 +0000361 gen.startDocument()
362 gen.processingInstruction("test", "data")
363 gen.startElement("doc", {})
364 gen.endElement("doc")
365 gen.endDocument()
Fred Drake004d5e62000-10-23 17:22:08 +0000366
Ezio Melotti2623a372010-11-21 13:34:58 +0000367 self.assertEqual(result.getvalue(), start + "<?test data?><doc></doc>")
Lars Gustäbel96753b32000-09-24 12:24:24 +0000368
Collin Winterd28fcbc2007-03-28 23:34:06 +0000369 def test_xmlgen_content_escape(self):
Serhiy Storchakaf8980382013-02-10 14:26:08 +0200370 result = self.ioclass()
Collin Winterd28fcbc2007-03-28 23:34:06 +0000371 gen = XMLGenerator(result)
Lars Gustäbel96753b32000-09-24 12:24:24 +0000372
Collin Winterd28fcbc2007-03-28 23:34:06 +0000373 gen.startDocument()
374 gen.startElement("doc", {})
375 gen.characters("<huhei&")
376 gen.endElement("doc")
377 gen.endDocument()
Fred Drake004d5e62000-10-23 17:22:08 +0000378
Ezio Melotti2623a372010-11-21 13:34:58 +0000379 self.assertEqual(result.getvalue(),
Collin Winterd28fcbc2007-03-28 23:34:06 +0000380 start + "<doc>&lt;huhei&amp;</doc>")
Lars Gustäbel96753b32000-09-24 12:24:24 +0000381
Collin Winterd28fcbc2007-03-28 23:34:06 +0000382 def test_xmlgen_attr_escape(self):
Serhiy Storchakaf8980382013-02-10 14:26:08 +0200383 result = self.ioclass()
Collin Winterd28fcbc2007-03-28 23:34:06 +0000384 gen = XMLGenerator(result)
Lars Gustäbel96753b32000-09-24 12:24:24 +0000385
Collin Winterd28fcbc2007-03-28 23:34:06 +0000386 gen.startDocument()
387 gen.startElement("doc", {"a": '"'})
388 gen.startElement("e", {"a": "'"})
389 gen.endElement("e")
390 gen.startElement("e", {"a": "'\""})
391 gen.endElement("e")
392 gen.startElement("e", {"a": "\n\r\t"})
393 gen.endElement("e")
394 gen.endElement("doc")
395 gen.endDocument()
Fred Drake004d5e62000-10-23 17:22:08 +0000396
Ezio Melotti2623a372010-11-21 13:34:58 +0000397 self.assertEqual(result.getvalue(), start +
Collin Winterd28fcbc2007-03-28 23:34:06 +0000398 ("<doc a='\"'><e a=\"'\"></e>"
399 "<e a=\"'&quot;\"></e>"
400 "<e a=\"&#10;&#13;&#9;\"></e></doc>"))
Lars Gustäbel96753b32000-09-24 12:24:24 +0000401
Serhiy Storchakaf8980382013-02-10 14:26:08 +0200402 def test_xmlgen_encoding(self):
403 encodings = ('iso-8859-15', 'utf-8',
404 'utf-16be', 'utf-16le',
405 'utf-32be', 'utf-32le')
406 for encoding in encodings:
407 result = self.ioclass()
408 gen = XMLGenerator(result, encoding=encoding)
409
410 gen.startDocument()
411 gen.startElement("doc", {"a": u'\u20ac'})
412 gen.characters(u"\u20ac")
413 gen.endElement("doc")
414 gen.endDocument()
415
416 self.assertEqual(result.getvalue(), (
417 u'<?xml version="1.0" encoding="%s"?>\n'
418 u'<doc a="\u20ac">\u20ac</doc>' % encoding
419 ).encode(encoding, 'xmlcharrefreplace'))
420
421 def test_xmlgen_unencodable(self):
422 result = self.ioclass()
423 gen = XMLGenerator(result, encoding='ascii')
424
425 gen.startDocument()
426 gen.startElement("doc", {"a": u'\u20ac'})
427 gen.characters(u"\u20ac")
428 gen.endElement("doc")
429 gen.endDocument()
430
431 self.assertEqual(result.getvalue(),
432 '<?xml version="1.0" encoding="ascii"?>\n'
433 '<doc a="&#8364;">&#8364;</doc>')
434
Collin Winterd28fcbc2007-03-28 23:34:06 +0000435 def test_xmlgen_ignorable(self):
Serhiy Storchakaf8980382013-02-10 14:26:08 +0200436 result = self.ioclass()
Collin Winterd28fcbc2007-03-28 23:34:06 +0000437 gen = XMLGenerator(result)
Lars Gustäbel96753b32000-09-24 12:24:24 +0000438
Collin Winterd28fcbc2007-03-28 23:34:06 +0000439 gen.startDocument()
440 gen.startElement("doc", {})
441 gen.ignorableWhitespace(" ")
442 gen.endElement("doc")
443 gen.endDocument()
Fred Drakec9fadf92001-08-07 19:17:06 +0000444
Ezio Melotti2623a372010-11-21 13:34:58 +0000445 self.assertEqual(result.getvalue(), start + "<doc> </doc>")
Fred Drakec9fadf92001-08-07 19:17:06 +0000446
Serhiy Storchaka74239032013-05-12 17:29:34 +0300447 def test_xmlgen_encoding_bytes(self):
448 encodings = ('iso-8859-15', 'utf-8',
449 'utf-16be', 'utf-16le',
450 'utf-32be', 'utf-32le')
451 for encoding in encodings:
452 result = self.ioclass()
453 gen = XMLGenerator(result, encoding=encoding)
454
455 gen.startDocument()
456 gen.startElement("doc", {"a": u'\u20ac'})
457 gen.characters(u"\u20ac".encode(encoding))
458 gen.ignorableWhitespace(" ".encode(encoding))
459 gen.endElement("doc")
460 gen.endDocument()
461
462 self.assertEqual(result.getvalue(), (
463 u'<?xml version="1.0" encoding="%s"?>\n'
464 u'<doc a="\u20ac">\u20ac </doc>' % encoding
465 ).encode(encoding, 'xmlcharrefreplace'))
466
Collin Winterd28fcbc2007-03-28 23:34:06 +0000467 def test_xmlgen_ns(self):
Serhiy Storchakaf8980382013-02-10 14:26:08 +0200468 result = self.ioclass()
Collin Winterd28fcbc2007-03-28 23:34:06 +0000469 gen = XMLGenerator(result)
Fred Drakec9fadf92001-08-07 19:17:06 +0000470
Collin Winterd28fcbc2007-03-28 23:34:06 +0000471 gen.startDocument()
472 gen.startPrefixMapping("ns1", ns_uri)
473 gen.startElementNS((ns_uri, "doc"), "ns1:doc", {})
474 # add an unqualified name
475 gen.startElementNS((None, "udoc"), None, {})
476 gen.endElementNS((None, "udoc"), None)
477 gen.endElementNS((ns_uri, "doc"), "ns1:doc")
478 gen.endPrefixMapping("ns1")
479 gen.endDocument()
Fred Drake004d5e62000-10-23 17:22:08 +0000480
Ezio Melotti2623a372010-11-21 13:34:58 +0000481 self.assertEqual(result.getvalue(), start + \
Martin v. Löwiscf0a1cc2000-10-03 22:35:29 +0000482 ('<ns1:doc xmlns:ns1="%s"><udoc></udoc></ns1:doc>' %
Collin Winterd28fcbc2007-03-28 23:34:06 +0000483 ns_uri))
Lars Gustäbel96753b32000-09-24 12:24:24 +0000484
Collin Winterd28fcbc2007-03-28 23:34:06 +0000485 def test_1463026_1(self):
Serhiy Storchakaf8980382013-02-10 14:26:08 +0200486 result = self.ioclass()
Collin Winterd28fcbc2007-03-28 23:34:06 +0000487 gen = XMLGenerator(result)
Martin v. Löwis2bad58f2007-02-12 12:21:10 +0000488
Collin Winterd28fcbc2007-03-28 23:34:06 +0000489 gen.startDocument()
490 gen.startElementNS((None, 'a'), 'a', {(None, 'b'):'c'})
491 gen.endElementNS((None, 'a'), 'a')
492 gen.endDocument()
Martin v. Löwis2bad58f2007-02-12 12:21:10 +0000493
Ezio Melotti2623a372010-11-21 13:34:58 +0000494 self.assertEqual(result.getvalue(), start+'<a b="c"></a>')
Martin v. Löwis2bad58f2007-02-12 12:21:10 +0000495
Collin Winterd28fcbc2007-03-28 23:34:06 +0000496 def test_1463026_2(self):
Serhiy Storchakaf8980382013-02-10 14:26:08 +0200497 result = self.ioclass()
Collin Winterd28fcbc2007-03-28 23:34:06 +0000498 gen = XMLGenerator(result)
Martin v. Löwis2bad58f2007-02-12 12:21:10 +0000499
Collin Winterd28fcbc2007-03-28 23:34:06 +0000500 gen.startDocument()
501 gen.startPrefixMapping(None, 'qux')
502 gen.startElementNS(('qux', 'a'), 'a', {})
503 gen.endElementNS(('qux', 'a'), 'a')
504 gen.endPrefixMapping(None)
505 gen.endDocument()
Martin v. Löwis2bad58f2007-02-12 12:21:10 +0000506
Ezio Melotti2623a372010-11-21 13:34:58 +0000507 self.assertEqual(result.getvalue(), start+'<a xmlns="qux"></a>')
Martin v. Löwis2bad58f2007-02-12 12:21:10 +0000508
Collin Winterd28fcbc2007-03-28 23:34:06 +0000509 def test_1463026_3(self):
Serhiy Storchakaf8980382013-02-10 14:26:08 +0200510 result = self.ioclass()
Collin Winterd28fcbc2007-03-28 23:34:06 +0000511 gen = XMLGenerator(result)
Martin v. Löwis2bad58f2007-02-12 12:21:10 +0000512
Collin Winterd28fcbc2007-03-28 23:34:06 +0000513 gen.startDocument()
514 gen.startPrefixMapping('my', 'qux')
515 gen.startElementNS(('qux', 'a'), 'a', {(None, 'b'):'c'})
516 gen.endElementNS(('qux', 'a'), 'a')
517 gen.endPrefixMapping('my')
518 gen.endDocument()
Martin v. Löwis2bad58f2007-02-12 12:21:10 +0000519
Ezio Melotti2623a372010-11-21 13:34:58 +0000520 self.assertEqual(result.getvalue(),
Collin Winterd28fcbc2007-03-28 23:34:06 +0000521 start+'<my:a xmlns:my="qux" b="c"></my:a>')
Tim Petersea5962f2007-03-12 18:07:52 +0000522
Antoine Pitrou7f081022010-10-27 18:43:21 +0000523 def test_5027_1(self):
524 # The xml prefix (as in xml:lang below) is reserved and bound by
525 # definition to http://www.w3.org/XML/1998/namespace. XMLGenerator had
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200526 # a bug whereby a KeyError is raised because this namespace is missing
Antoine Pitrou7f081022010-10-27 18:43:21 +0000527 # from a dictionary.
528 #
529 # This test demonstrates the bug by parsing a document.
530 test_xml = StringIO(
531 '<?xml version="1.0"?>'
532 '<a:g1 xmlns:a="http://example.com/ns">'
533 '<a:g2 xml:lang="en">Hello</a:g2>'
534 '</a:g1>')
535
536 parser = make_parser()
537 parser.setFeature(feature_namespaces, True)
Serhiy Storchakaf8980382013-02-10 14:26:08 +0200538 result = self.ioclass()
Antoine Pitrou7f081022010-10-27 18:43:21 +0000539 gen = XMLGenerator(result)
540 parser.setContentHandler(gen)
541 parser.parse(test_xml)
542
Ezio Melotti2623a372010-11-21 13:34:58 +0000543 self.assertEqual(result.getvalue(),
544 start + (
545 '<a:g1 xmlns:a="http://example.com/ns">'
546 '<a:g2 xml:lang="en">Hello</a:g2>'
547 '</a:g1>'))
Antoine Pitrou7f081022010-10-27 18:43:21 +0000548
549 def test_5027_2(self):
550 # The xml prefix (as in xml:lang below) is reserved and bound by
551 # definition to http://www.w3.org/XML/1998/namespace. XMLGenerator had
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200552 # a bug whereby a KeyError is raised because this namespace is missing
Antoine Pitrou7f081022010-10-27 18:43:21 +0000553 # from a dictionary.
554 #
555 # This test demonstrates the bug by direct manipulation of the
556 # XMLGenerator.
Serhiy Storchakaf8980382013-02-10 14:26:08 +0200557 result = self.ioclass()
Antoine Pitrou7f081022010-10-27 18:43:21 +0000558 gen = XMLGenerator(result)
559
560 gen.startDocument()
561 gen.startPrefixMapping('a', 'http://example.com/ns')
562 gen.startElementNS(('http://example.com/ns', 'g1'), 'g1', {})
563 lang_attr = {('http://www.w3.org/XML/1998/namespace', 'lang'): 'en'}
564 gen.startElementNS(('http://example.com/ns', 'g2'), 'g2', lang_attr)
565 gen.characters('Hello')
566 gen.endElementNS(('http://example.com/ns', 'g2'), 'g2')
567 gen.endElementNS(('http://example.com/ns', 'g1'), 'g1')
568 gen.endPrefixMapping('a')
569 gen.endDocument()
570
Ezio Melotti2623a372010-11-21 13:34:58 +0000571 self.assertEqual(result.getvalue(),
572 start + (
573 '<a:g1 xmlns:a="http://example.com/ns">'
574 '<a:g2 xml:lang="en">Hello</a:g2>'
575 '</a:g1>'))
Antoine Pitrou7f081022010-10-27 18:43:21 +0000576
Serhiy Storchakaf8980382013-02-10 14:26:08 +0200577 def test_no_close_file(self):
578 result = self.ioclass()
579 def func(out):
580 gen = XMLGenerator(out)
581 gen.startDocument()
582 gen.startElement("doc", {})
583 func(result)
584 self.assertFalse(result.closed)
585
Serhiy Storchaka93bfe7d2013-02-25 13:31:29 +0200586 def test_xmlgen_fragment(self):
587 result = self.ioclass()
588 gen = XMLGenerator(result)
589
590 # Don't call gen.startDocument()
591 gen.startElement("foo", {"a": "1.0"})
592 gen.characters("Hello")
593 gen.endElement("foo")
594 gen.startElement("bar", {"b": "2.0"})
595 gen.endElement("bar")
596 # Don't call gen.endDocument()
597
598 self.assertEqual(result.getvalue(),
599 '<foo a="1.0">Hello</foo><bar b="2.0"></bar>')
600
Serhiy Storchakaf8980382013-02-10 14:26:08 +0200601class StringXmlgenTest(XmlgenTest, unittest.TestCase):
602 ioclass = StringIO
603
604class BytesIOXmlgenTest(XmlgenTest, unittest.TestCase):
605 ioclass = io.BytesIO
606
607class WriterXmlgenTest(XmlgenTest, unittest.TestCase):
608 class ioclass(list):
609 write = list.append
610 closed = False
611
612 def getvalue(self):
613 return b''.join(self)
614
Lars Gustäbel96753b32000-09-24 12:24:24 +0000615
Collin Winterd28fcbc2007-03-28 23:34:06 +0000616class XMLFilterBaseTest(unittest.TestCase):
617 def test_filter_basic(self):
618 result = StringIO()
619 gen = XMLGenerator(result)
620 filter = XMLFilterBase()
621 filter.setContentHandler(gen)
Fred Drake004d5e62000-10-23 17:22:08 +0000622
Collin Winterd28fcbc2007-03-28 23:34:06 +0000623 filter.startDocument()
624 filter.startElement("doc", {})
625 filter.characters("content")
626 filter.ignorableWhitespace(" ")
627 filter.endElement("doc")
628 filter.endDocument()
Lars Gustäbel96753b32000-09-24 12:24:24 +0000629
Ezio Melotti2623a372010-11-21 13:34:58 +0000630 self.assertEqual(result.getvalue(), start + "<doc>content </doc>")
Lars Gustäbel96753b32000-09-24 12:24:24 +0000631
632# ===========================================================================
633#
634# expatreader tests
635#
636# ===========================================================================
637
Florent Xicluna13ba1a12010-03-13 11:18:49 +0000638xml_test_out = open(TEST_XMLFILE_OUT).read()
Lars Gustäbelb7536d52000-09-24 18:53:56 +0000639
Collin Winterd28fcbc2007-03-28 23:34:06 +0000640class ExpatReaderTest(XmlTestBase):
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000641
Collin Winterd28fcbc2007-03-28 23:34:06 +0000642 # ===== XMLReader support
Lars Gustäbelb7536d52000-09-24 18:53:56 +0000643
Serhiy Storchakae9d4dc12015-04-02 20:55:46 +0300644 def test_expat_binary_file(self):
Collin Winterd28fcbc2007-03-28 23:34:06 +0000645 parser = create_parser()
646 result = StringIO()
647 xmlgen = XMLGenerator(result)
Lars Gustäbelb7536d52000-09-24 18:53:56 +0000648
Collin Winterd28fcbc2007-03-28 23:34:06 +0000649 parser.setContentHandler(xmlgen)
Florent Xicluna13ba1a12010-03-13 11:18:49 +0000650 parser.parse(open(TEST_XMLFILE))
Lars Gustäbelb7536d52000-09-24 18:53:56 +0000651
Ezio Melotti2623a372010-11-21 13:34:58 +0000652 self.assertEqual(result.getvalue(), xml_test_out)
Lars Gustäbelb7536d52000-09-24 18:53:56 +0000653
Serhiy Storchaka23298cb2013-02-02 12:16:22 +0200654 @requires_unicode_filenames
Serhiy Storchaka8673ab92013-02-02 10:28:30 +0200655 def test_expat_file_unicode(self):
656 fname = support.TESTFN_UNICODE
657 shutil.copyfile(TEST_XMLFILE, fname)
658 self.addCleanup(support.unlink, fname)
659
660 parser = create_parser()
661 result = StringIO()
662 xmlgen = XMLGenerator(result)
663
664 parser.setContentHandler(xmlgen)
665 parser.parse(open(fname))
666
667 self.assertEqual(result.getvalue(), xml_test_out)
668
Collin Winterd28fcbc2007-03-28 23:34:06 +0000669 # ===== DTDHandler support
Lars Gustäbelb7536d52000-09-24 18:53:56 +0000670
Collin Winterd28fcbc2007-03-28 23:34:06 +0000671 class TestDTDHandler:
Lars Gustäbelb7536d52000-09-24 18:53:56 +0000672
Collin Winterd28fcbc2007-03-28 23:34:06 +0000673 def __init__(self):
674 self._notations = []
675 self._entities = []
Lars Gustäbelb7536d52000-09-24 18:53:56 +0000676
Collin Winterd28fcbc2007-03-28 23:34:06 +0000677 def notationDecl(self, name, publicId, systemId):
678 self._notations.append((name, publicId, systemId))
Lars Gustäbelb7536d52000-09-24 18:53:56 +0000679
Collin Winterd28fcbc2007-03-28 23:34:06 +0000680 def unparsedEntityDecl(self, name, publicId, systemId, ndata):
681 self._entities.append((name, publicId, systemId, ndata))
Lars Gustäbelb7536d52000-09-24 18:53:56 +0000682
Collin Winterd28fcbc2007-03-28 23:34:06 +0000683 def test_expat_dtdhandler(self):
684 parser = create_parser()
685 handler = self.TestDTDHandler()
686 parser.setDTDHandler(handler)
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000687
Collin Winterd28fcbc2007-03-28 23:34:06 +0000688 parser.feed('<!DOCTYPE doc [\n')
689 parser.feed(' <!ENTITY img SYSTEM "expat.gif" NDATA GIF>\n')
690 parser.feed(' <!NOTATION GIF PUBLIC "-//CompuServe//NOTATION Graphics Interchange Format 89a//EN">\n')
691 parser.feed(']>\n')
692 parser.feed('<doc></doc>')
693 parser.close()
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000694
Ezio Melotti2623a372010-11-21 13:34:58 +0000695 self.assertEqual(handler._notations,
Collin Winterd28fcbc2007-03-28 23:34:06 +0000696 [("GIF", "-//CompuServe//NOTATION Graphics Interchange Format 89a//EN", None)])
Ezio Melotti2623a372010-11-21 13:34:58 +0000697 self.assertEqual(handler._entities, [("img", None, "expat.gif", "GIF")])
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000698
Collin Winterd28fcbc2007-03-28 23:34:06 +0000699 # ===== EntityResolver support
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000700
Collin Winterd28fcbc2007-03-28 23:34:06 +0000701 class TestEntityResolver:
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000702
Collin Winterd28fcbc2007-03-28 23:34:06 +0000703 def resolveEntity(self, publicId, systemId):
704 inpsrc = InputSource()
705 inpsrc.setByteStream(StringIO("<entity/>"))
706 return inpsrc
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000707
Collin Winterd28fcbc2007-03-28 23:34:06 +0000708 def test_expat_entityresolver(self):
709 parser = create_parser()
710 parser.setEntityResolver(self.TestEntityResolver())
711 result = StringIO()
712 parser.setContentHandler(XMLGenerator(result))
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000713
Collin Winterd28fcbc2007-03-28 23:34:06 +0000714 parser.feed('<!DOCTYPE doc [\n')
715 parser.feed(' <!ENTITY test SYSTEM "whatever">\n')
716 parser.feed(']>\n')
717 parser.feed('<doc>&test;</doc>')
718 parser.close()
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000719
Ezio Melotti2623a372010-11-21 13:34:58 +0000720 self.assertEqual(result.getvalue(), start +
721 "<doc><entity></entity></doc>")
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000722
Collin Winterd28fcbc2007-03-28 23:34:06 +0000723 # ===== Attributes support
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000724
Collin Winterd28fcbc2007-03-28 23:34:06 +0000725 class AttrGatherer(ContentHandler):
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000726
Collin Winterd28fcbc2007-03-28 23:34:06 +0000727 def startElement(self, name, attrs):
728 self._attrs = attrs
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000729
Collin Winterd28fcbc2007-03-28 23:34:06 +0000730 def startElementNS(self, name, qname, attrs):
731 self._attrs = attrs
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000732
Collin Winterd28fcbc2007-03-28 23:34:06 +0000733 def test_expat_attrs_empty(self):
734 parser = create_parser()
735 gather = self.AttrGatherer()
736 parser.setContentHandler(gather)
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000737
Collin Winterd28fcbc2007-03-28 23:34:06 +0000738 parser.feed("<doc/>")
739 parser.close()
Lars Gustäbel2fc52942000-10-24 15:35:07 +0000740
Collin Winterd28fcbc2007-03-28 23:34:06 +0000741 self.verify_empty_attrs(gather._attrs)
Martin v. Löwis80670bc2000-10-06 21:13:23 +0000742
Collin Winterd28fcbc2007-03-28 23:34:06 +0000743 def test_expat_attrs_wattr(self):
744 parser = create_parser()
745 gather = self.AttrGatherer()
746 parser.setContentHandler(gather)
747
748 parser.feed("<doc attr='val'/>")
749 parser.close()
750
751 self.verify_attrs_wattr(gather._attrs)
752
753 def test_expat_nsattrs_empty(self):
754 parser = create_parser(1)
755 gather = self.AttrGatherer()
756 parser.setContentHandler(gather)
757
758 parser.feed("<doc/>")
759 parser.close()
760
761 self.verify_empty_nsattrs(gather._attrs)
762
763 def test_expat_nsattrs_wattr(self):
764 parser = create_parser(1)
765 gather = self.AttrGatherer()
766 parser.setContentHandler(gather)
767
768 parser.feed("<doc xmlns:ns='%s' ns:attr='val'/>" % ns_uri)
769 parser.close()
770
771 attrs = gather._attrs
772
Ezio Melotti2623a372010-11-21 13:34:58 +0000773 self.assertEqual(attrs.getLength(), 1)
774 self.assertEqual(attrs.getNames(), [(ns_uri, "attr")])
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000775 self.assertTrue((attrs.getQNames() == [] or
Collin Winterd28fcbc2007-03-28 23:34:06 +0000776 attrs.getQNames() == ["ns:attr"]))
Ezio Melotti2623a372010-11-21 13:34:58 +0000777 self.assertEqual(len(attrs), 1)
Collin Winterd28fcbc2007-03-28 23:34:06 +0000778 self.assertTrue(attrs.has_key((ns_uri, "attr")))
Ezio Melotti2623a372010-11-21 13:34:58 +0000779 self.assertEqual(attrs.get((ns_uri, "attr")), "val")
780 self.assertEqual(attrs.get((ns_uri, "attr"), 25), "val")
781 self.assertEqual(attrs.items(), [((ns_uri, "attr"), "val")])
782 self.assertEqual(attrs.values(), ["val"])
783 self.assertEqual(attrs.getValue((ns_uri, "attr")), "val")
784 self.assertEqual(attrs[(ns_uri, "attr")], "val")
Collin Winterd28fcbc2007-03-28 23:34:06 +0000785
786 # ===== InputSource support
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000787
Collin Winterd28fcbc2007-03-28 23:34:06 +0000788 def test_expat_inpsource_filename(self):
789 parser = create_parser()
790 result = StringIO()
791 xmlgen = XMLGenerator(result)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000792
Collin Winterd28fcbc2007-03-28 23:34:06 +0000793 parser.setContentHandler(xmlgen)
Florent Xicluna13ba1a12010-03-13 11:18:49 +0000794 parser.parse(TEST_XMLFILE)
Collin Winterd28fcbc2007-03-28 23:34:06 +0000795
Ezio Melotti2623a372010-11-21 13:34:58 +0000796 self.assertEqual(result.getvalue(), xml_test_out)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000797
Collin Winterd28fcbc2007-03-28 23:34:06 +0000798 def test_expat_inpsource_sysid(self):
799 parser = create_parser()
800 result = StringIO()
801 xmlgen = XMLGenerator(result)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000802
Collin Winterd28fcbc2007-03-28 23:34:06 +0000803 parser.setContentHandler(xmlgen)
Florent Xicluna13ba1a12010-03-13 11:18:49 +0000804 parser.parse(InputSource(TEST_XMLFILE))
Collin Winterd28fcbc2007-03-28 23:34:06 +0000805
Ezio Melotti2623a372010-11-21 13:34:58 +0000806 self.assertEqual(result.getvalue(), xml_test_out)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000807
Serhiy Storchaka23298cb2013-02-02 12:16:22 +0200808 @requires_unicode_filenames
Serhiy Storchaka8673ab92013-02-02 10:28:30 +0200809 def test_expat_inpsource_sysid_unicode(self):
810 fname = support.TESTFN_UNICODE
811 shutil.copyfile(TEST_XMLFILE, fname)
812 self.addCleanup(support.unlink, fname)
813
814 parser = create_parser()
815 result = StringIO()
816 xmlgen = XMLGenerator(result)
817
818 parser.setContentHandler(xmlgen)
819 parser.parse(InputSource(fname))
820
821 self.assertEqual(result.getvalue(), xml_test_out)
822
Serhiy Storchakae9d4dc12015-04-02 20:55:46 +0300823 def test_expat_inpsource_byte_stream(self):
Collin Winterd28fcbc2007-03-28 23:34:06 +0000824 parser = create_parser()
825 result = StringIO()
826 xmlgen = XMLGenerator(result)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000827
Collin Winterd28fcbc2007-03-28 23:34:06 +0000828 parser.setContentHandler(xmlgen)
829 inpsrc = InputSource()
Florent Xicluna13ba1a12010-03-13 11:18:49 +0000830 inpsrc.setByteStream(open(TEST_XMLFILE))
Collin Winterd28fcbc2007-03-28 23:34:06 +0000831 parser.parse(inpsrc)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000832
Ezio Melotti2623a372010-11-21 13:34:58 +0000833 self.assertEqual(result.getvalue(), xml_test_out)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000834
Collin Winterd28fcbc2007-03-28 23:34:06 +0000835 # ===== IncrementalParser support
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000836
Collin Winterd28fcbc2007-03-28 23:34:06 +0000837 def test_expat_incremental(self):
838 result = StringIO()
839 xmlgen = XMLGenerator(result)
840 parser = create_parser()
841 parser.setContentHandler(xmlgen)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000842
Collin Winterd28fcbc2007-03-28 23:34:06 +0000843 parser.feed("<doc>")
844 parser.feed("</doc>")
845 parser.close()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000846
Ezio Melotti2623a372010-11-21 13:34:58 +0000847 self.assertEqual(result.getvalue(), start + "<doc></doc>")
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000848
Collin Winterd28fcbc2007-03-28 23:34:06 +0000849 def test_expat_incremental_reset(self):
850 result = StringIO()
851 xmlgen = XMLGenerator(result)
852 parser = create_parser()
853 parser.setContentHandler(xmlgen)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000854
Collin Winterd28fcbc2007-03-28 23:34:06 +0000855 parser.feed("<doc>")
856 parser.feed("text")
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000857
Collin Winterd28fcbc2007-03-28 23:34:06 +0000858 result = StringIO()
859 xmlgen = XMLGenerator(result)
860 parser.setContentHandler(xmlgen)
861 parser.reset()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000862
Collin Winterd28fcbc2007-03-28 23:34:06 +0000863 parser.feed("<doc>")
864 parser.feed("text")
865 parser.feed("</doc>")
866 parser.close()
867
Ezio Melotti2623a372010-11-21 13:34:58 +0000868 self.assertEqual(result.getvalue(), start + "<doc>text</doc>")
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000869
Collin Winterd28fcbc2007-03-28 23:34:06 +0000870 # ===== Locator support
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000871
Collin Winterd28fcbc2007-03-28 23:34:06 +0000872 def test_expat_locator_noinfo(self):
873 result = StringIO()
874 xmlgen = XMLGenerator(result)
875 parser = create_parser()
876 parser.setContentHandler(xmlgen)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000877
Collin Winterd28fcbc2007-03-28 23:34:06 +0000878 parser.feed("<doc>")
879 parser.feed("</doc>")
880 parser.close()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000881
Ezio Melotti2623a372010-11-21 13:34:58 +0000882 self.assertEqual(parser.getSystemId(), None)
883 self.assertEqual(parser.getPublicId(), None)
884 self.assertEqual(parser.getLineNumber(), 1)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000885
Collin Winterd28fcbc2007-03-28 23:34:06 +0000886 def test_expat_locator_withinfo(self):
887 result = StringIO()
888 xmlgen = XMLGenerator(result)
889 parser = create_parser()
890 parser.setContentHandler(xmlgen)
Florent Xicluna13ba1a12010-03-13 11:18:49 +0000891 parser.parse(TEST_XMLFILE)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000892
Ezio Melotti2623a372010-11-21 13:34:58 +0000893 self.assertEqual(parser.getSystemId(), TEST_XMLFILE)
894 self.assertEqual(parser.getPublicId(), None)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000895
Serhiy Storchaka23298cb2013-02-02 12:16:22 +0200896 @requires_unicode_filenames
Serhiy Storchaka8673ab92013-02-02 10:28:30 +0200897 def test_expat_locator_withinfo_unicode(self):
898 fname = support.TESTFN_UNICODE
899 shutil.copyfile(TEST_XMLFILE, fname)
900 self.addCleanup(support.unlink, fname)
901
902 result = StringIO()
903 xmlgen = XMLGenerator(result)
904 parser = create_parser()
905 parser.setContentHandler(xmlgen)
906 parser.parse(fname)
907
908 self.assertEqual(parser.getSystemId(), fname)
909 self.assertEqual(parser.getPublicId(), None)
910
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000911
Martin v. Löwis80670bc2000-10-06 21:13:23 +0000912# ===========================================================================
913#
914# error reporting
915#
916# ===========================================================================
917
Collin Winterd28fcbc2007-03-28 23:34:06 +0000918class ErrorReportingTest(unittest.TestCase):
919 def test_expat_inpsource_location(self):
920 parser = create_parser()
921 parser.setContentHandler(ContentHandler()) # do nothing
922 source = InputSource()
923 source.setByteStream(StringIO("<foo bar foobar>")) #ill-formed
924 name = "a file name"
925 source.setSystemId(name)
926 try:
927 parser.parse(source)
928 self.fail()
929 except SAXException, e:
Ezio Melotti2623a372010-11-21 13:34:58 +0000930 self.assertEqual(e.getSystemId(), name)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000931
Collin Winterd28fcbc2007-03-28 23:34:06 +0000932 def test_expat_incomplete(self):
933 parser = create_parser()
934 parser.setContentHandler(ContentHandler()) # do nothing
935 self.assertRaises(SAXParseException, parser.parse, StringIO("<foo>"))
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000936
Collin Winterd28fcbc2007-03-28 23:34:06 +0000937 def test_sax_parse_exception_str(self):
938 # pass various values from a locator to the SAXParseException to
939 # make sure that the __str__() doesn't fall apart when None is
940 # passed instead of an integer line and column number
941 #
942 # use "normal" values for the locator:
943 str(SAXParseException("message", None,
944 self.DummyLocator(1, 1)))
945 # use None for the line number:
946 str(SAXParseException("message", None,
947 self.DummyLocator(None, 1)))
948 # use None for the column number:
949 str(SAXParseException("message", None,
950 self.DummyLocator(1, None)))
951 # use None for both:
952 str(SAXParseException("message", None,
953 self.DummyLocator(None, None)))
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000954
Collin Winterd28fcbc2007-03-28 23:34:06 +0000955 class DummyLocator:
956 def __init__(self, lineno, colno):
957 self._lineno = lineno
958 self._colno = colno
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000959
Collin Winterd28fcbc2007-03-28 23:34:06 +0000960 def getPublicId(self):
961 return "pubid"
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000962
Collin Winterd28fcbc2007-03-28 23:34:06 +0000963 def getSystemId(self):
964 return "sysid"
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000965
Collin Winterd28fcbc2007-03-28 23:34:06 +0000966 def getLineNumber(self):
967 return self._lineno
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000968
Collin Winterd28fcbc2007-03-28 23:34:06 +0000969 def getColumnNumber(self):
970 return self._colno
Martin v. Löwis80670bc2000-10-06 21:13:23 +0000971
Lars Gustäbelab647872000-09-24 18:40:52 +0000972# ===========================================================================
973#
974# xmlreader tests
975#
976# ===========================================================================
977
Collin Winterd28fcbc2007-03-28 23:34:06 +0000978class XmlReaderTest(XmlTestBase):
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000979
Collin Winterd28fcbc2007-03-28 23:34:06 +0000980 # ===== AttributesImpl
981 def test_attrs_empty(self):
982 self.verify_empty_attrs(AttributesImpl({}))
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000983
Collin Winterd28fcbc2007-03-28 23:34:06 +0000984 def test_attrs_wattr(self):
985 self.verify_attrs_wattr(AttributesImpl({"attr" : "val"}))
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000986
Collin Winterd28fcbc2007-03-28 23:34:06 +0000987 def test_nsattrs_empty(self):
988 self.verify_empty_nsattrs(AttributesNSImpl({}, {}))
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000989
Collin Winterd28fcbc2007-03-28 23:34:06 +0000990 def test_nsattrs_wattr(self):
991 attrs = AttributesNSImpl({(ns_uri, "attr") : "val"},
992 {(ns_uri, "attr") : "ns:attr"})
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000993
Ezio Melotti2623a372010-11-21 13:34:58 +0000994 self.assertEqual(attrs.getLength(), 1)
995 self.assertEqual(attrs.getNames(), [(ns_uri, "attr")])
996 self.assertEqual(attrs.getQNames(), ["ns:attr"])
997 self.assertEqual(len(attrs), 1)
Collin Winterd28fcbc2007-03-28 23:34:06 +0000998 self.assertTrue(attrs.has_key((ns_uri, "attr")))
Ezio Melotti2623a372010-11-21 13:34:58 +0000999 self.assertEqual(attrs.keys(), [(ns_uri, "attr")])
1000 self.assertEqual(attrs.get((ns_uri, "attr")), "val")
1001 self.assertEqual(attrs.get((ns_uri, "attr"), 25), "val")
1002 self.assertEqual(attrs.items(), [((ns_uri, "attr"), "val")])
1003 self.assertEqual(attrs.values(), ["val"])
1004 self.assertEqual(attrs.getValue((ns_uri, "attr")), "val")
1005 self.assertEqual(attrs.getValueByQName("ns:attr"), "val")
1006 self.assertEqual(attrs.getNameByQName("ns:attr"), (ns_uri, "attr"))
1007 self.assertEqual(attrs[(ns_uri, "attr")], "val")
1008 self.assertEqual(attrs.getQNameByName((ns_uri, "attr")), "ns:attr")
Fred Drake004d5e62000-10-23 17:22:08 +00001009
Lars Gustäbelab647872000-09-24 18:40:52 +00001010
Collin Winterd28fcbc2007-03-28 23:34:06 +00001011 # During the development of Python 2.5, an attempt to move the "xml"
1012 # package implementation to a new package ("xmlcore") proved painful.
1013 # The goal of this change was to allow applications to be able to
1014 # obtain and rely on behavior in the standard library implementation
1015 # of the XML support without needing to be concerned about the
1016 # availability of the PyXML implementation.
1017 #
1018 # While the existing import hackery in Lib/xml/__init__.py can cause
1019 # PyXML's _xmlpus package to supplant the "xml" package, that only
1020 # works because either implementation uses the "xml" package name for
1021 # imports.
1022 #
1023 # The move resulted in a number of problems related to the fact that
1024 # the import machinery's "package context" is based on the name that's
1025 # being imported rather than the __name__ of the actual package
1026 # containment; it wasn't possible for the "xml" package to be replaced
1027 # by a simple module that indirected imports to the "xmlcore" package.
1028 #
1029 # The following two tests exercised bugs that were introduced in that
1030 # attempt. Keeping these tests around will help detect problems with
1031 # other attempts to provide reliable access to the standard library's
1032 # implementation of the XML support.
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001033
Collin Winterd28fcbc2007-03-28 23:34:06 +00001034 def test_sf_1511497(self):
1035 # Bug report: http://www.python.org/sf/1511497
1036 import sys
1037 old_modules = sys.modules.copy()
1038 for modname in sys.modules.keys():
1039 if modname.startswith("xml."):
1040 del sys.modules[modname]
1041 try:
1042 import xml.sax.expatreader
1043 module = xml.sax.expatreader
Ezio Melotti2623a372010-11-21 13:34:58 +00001044 self.assertEqual(module.__name__, "xml.sax.expatreader")
Collin Winterd28fcbc2007-03-28 23:34:06 +00001045 finally:
1046 sys.modules.update(old_modules)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001047
Collin Winterd28fcbc2007-03-28 23:34:06 +00001048 def test_sf_1513611(self):
1049 # Bug report: http://www.python.org/sf/1513611
1050 sio = StringIO("invalid")
1051 parser = make_parser()
1052 from xml.sax import SAXParseException
1053 self.assertRaises(SAXParseException, parser.parse, sio)
Fred Drakefbdeaad2006-07-29 16:56:15 +00001054
Fred Drakefbdeaad2006-07-29 16:56:15 +00001055
Neal Norwitzab364c42008-03-28 07:36:31 +00001056def test_main():
Collin Winterd28fcbc2007-03-28 23:34:06 +00001057 run_unittest(MakeParserTest,
Serhiy Storchakaaff77f32015-04-02 23:05:23 +03001058 ParseTest,
Collin Winterd28fcbc2007-03-28 23:34:06 +00001059 SaxutilsTest,
Serhiy Storchakae9d4dc12015-04-02 20:55:46 +03001060 PrepareInputSourceTest,
Serhiy Storchakaf8980382013-02-10 14:26:08 +02001061 StringXmlgenTest,
1062 BytesIOXmlgenTest,
1063 WriterXmlgenTest,
Collin Winterd28fcbc2007-03-28 23:34:06 +00001064 ExpatReaderTest,
1065 ErrorReportingTest,
1066 XmlReaderTest)
Fred Drakefbdeaad2006-07-29 16:56:15 +00001067
Collin Winterd28fcbc2007-03-28 23:34:06 +00001068if __name__ == "__main__":
Neal Norwitzab364c42008-03-28 07:36:31 +00001069 test_main()