Debian Codegraph @

lib-python/3/test/test_pyexpat.py

raw symbols SCIP
1 # XXX TypeErrors on calling handlers, or on bad return values from a
2 # handler, are obscure and unhelpful.
3
4 import abc
5 import functools
6 import os
7 import platform
8 import re
9 import sys
10 import sysconfig
11 import textwrap
12 import unittest
13 import traceback
14 from io import BytesIO
15 from test import support
16 from test.support import import_helper, os_helper
17
18 from xml.parsers import expat
19 from xml.parsers.expat import errors
20
21 from test.support import sortdict, is_emscripten, is_wasi
22
23
24 class SetAttributeTest(unittest.TestCase):
25 def setUp(self):
26 self.parser = expat.ParserCreate(namespace_separator='!')
27
28 def test_buffer_text(self):
29 self.assertIs(self.parser.buffer_text, False)
30 for x in 0, 1, 2, 0:
31 self.parser.buffer_text = x
32 self.assertIs(self.parser.buffer_text, bool(x))
33
34 def test_namespace_prefixes(self):
35 self.assertIs(self.parser.namespace_prefixes, False)
36 for x in 0, 1, 2, 0:
37 self.parser.namespace_prefixes = x
38 self.assertIs(self.parser.namespace_prefixes, bool(x))
39
40 def test_ordered_attributes(self):
41 self.assertIs(self.parser.ordered_attributes, False)
42 for x in 0, 1, 2, 0:
43 self.parser.ordered_attributes = x
44 self.assertIs(self.parser.ordered_attributes, bool(x))
45
46 def test_specified_attributes(self):
47 self.assertIs(self.parser.specified_attributes, False)
48 for x in 0, 1, 2, 0:
49 self.parser.specified_attributes = x
50 self.assertIs(self.parser.specified_attributes, bool(x))
51
52 def test_invalid_attributes(self):
53 with self.assertRaises(AttributeError):
54 self.parser.returns_unicode = 1
55 with self.assertRaises(AttributeError):
56 self.parser.returns_unicode
57
58 # Issue #25019
59 self.assertRaises(TypeError, setattr, self.parser, range(0xF), 0)
60 self.assertRaises(TypeError, self.parser.__setattr__, range(0xF), 0)
61 self.assertRaises(TypeError, getattr, self.parser, range(0xF))
62
63
64 data = b'''\
65 <?xml version="1.0" encoding="iso-8859-1" standalone="no"?>
66 <?xml-stylesheet href="stylesheet.css"?>
67 <!-- comment data -->
68 <!DOCTYPE quotations SYSTEM "quotations.dtd" [
69 <!ELEMENT root ANY>
70 <!ATTLIST root attr1 CDATA #REQUIRED attr2 CDATA #IMPLIED>
71 <!NOTATION notation SYSTEM "notation.jpeg">
72 <!ENTITY acirc "&#226;">
73 <!ENTITY external_entity SYSTEM "entity.file">
74 <!ENTITY unparsed_entity SYSTEM "entity.file" NDATA notation>
75 %unparsed_entity;
76 ]>
77
78 <root attr1="value1" attr2="value2&#8000;">
79 <myns:subelement xmlns:myns="http://www.python.org/namespace">
80 Contents of subelements
81 </myns:subelement>
82 <sub2><![CDATA[contents of CDATA section]]></sub2>
83 &external_entity;
84 &skipped_entity;
85 \xb5
86 </root>
87 '''
88
89
90 # Produce UTF-8 output
91 class ParseTest(unittest.TestCase):
92 class Outputter:
93 def __init__(self):
94 self.out = []
95
96 def StartElementHandler(self, name, attrs):
97 self.out.append('Start element: ' + repr(name) + ' ' +
98 sortdict(attrs))
99
100 def EndElementHandler(self, name):
101 self.out.append('End element: ' + repr(name))
102
103 def CharacterDataHandler(self, data):
104 data = data.strip()
105 if data:
106 self.out.append('Character data: ' + repr(data))
107
108 def ProcessingInstructionHandler(self, target, data):
109 self.out.append('PI: ' + repr(target) + ' ' + repr(data))
110
111 def StartNamespaceDeclHandler(self, prefix, uri):
112 self.out.append('NS decl: ' + repr(prefix) + ' ' + repr(uri))
113
114 def EndNamespaceDeclHandler(self, prefix):
115 self.out.append('End of NS decl: ' + repr(prefix))
116
117 def StartCdataSectionHandler(self):
118 self.out.append('Start of CDATA section')
119
120 def EndCdataSectionHandler(self):
121 self.out.append('End of CDATA section')
122
123 def CommentHandler(self, text):
124 self.out.append('Comment: ' + repr(text))
125
126 def NotationDeclHandler(self, *args):
127 name, base, sysid, pubid = args
128 self.out.append('Notation declared: %s' %(args,))
129
130 def UnparsedEntityDeclHandler(self, *args):
131 entityName, base, systemId, publicId, notationName = args
132 self.out.append('Unparsed entity decl: %s' %(args,))
133
134 def NotStandaloneHandler(self):
135 self.out.append('Not standalone')
136 return 1
137
138 def ExternalEntityRefHandler(self, *args):
139 context, base, sysId, pubId = args
140 self.out.append('External entity ref: %s' %(args[1:],))
141 return 1
142
143 def StartDoctypeDeclHandler(self, *args):
144 self.out.append(('Start doctype', args))
145 return 1
146
147 def EndDoctypeDeclHandler(self):
148 self.out.append("End doctype")
149 return 1
150
151 def EntityDeclHandler(self, *args):
152 self.out.append(('Entity declaration', args))
153 return 1
154
155 def XmlDeclHandler(self, *args):
156 self.out.append(('XML declaration', args))
157 return 1
158
159 def ElementDeclHandler(self, *args):
160 self.out.append(('Element declaration', args))
161 return 1
162
163 def AttlistDeclHandler(self, *args):
164 self.out.append(('Attribute list declaration', args))
165 return 1
166
167 def SkippedEntityHandler(self, *args):
168 self.out.append(("Skipped entity", args))
169 return 1
170
171 def DefaultHandler(self, userData):
172 pass
173
174 def DefaultHandlerExpand(self, userData):
175 pass
176
177 handler_names = [
178 'StartElementHandler', 'EndElementHandler', 'CharacterDataHandler',
179 'ProcessingInstructionHandler', 'UnparsedEntityDeclHandler',
180 'NotationDeclHandler', 'StartNamespaceDeclHandler',
181 'EndNamespaceDeclHandler', 'CommentHandler',
182 'StartCdataSectionHandler', 'EndCdataSectionHandler', 'DefaultHandler',
183 'DefaultHandlerExpand', 'NotStandaloneHandler',
184 'ExternalEntityRefHandler', 'StartDoctypeDeclHandler',
185 'EndDoctypeDeclHandler', 'EntityDeclHandler', 'XmlDeclHandler',
186 'ElementDeclHandler', 'AttlistDeclHandler', 'SkippedEntityHandler',
187 ]
188
189 def _hookup_callbacks(self, parser, handler):
190 """
191 Set each of the callbacks defined on handler and named in
192 self.handler_names on the given parser.
193 """
194 for name in self.handler_names:
195 setattr(parser, name, getattr(handler, name))
196
197 def _verify_parse_output(self, operations):
198 expected_operations = [
199 ('XML declaration', ('1.0', 'iso-8859-1', 0)),
200 'PI: \'xml-stylesheet\' \'href="stylesheet.css"\'',
201 "Comment: ' comment data '",
202 "Not standalone",
203 ("Start doctype", ('quotations', 'quotations.dtd', None, 1)),
204 ('Element declaration', ('root', (2, 0, None, ()))),
205 ('Attribute list declaration', ('root', 'attr1', 'CDATA', None,
206 1)),
207 ('Attribute list declaration', ('root', 'attr2', 'CDATA', None,
208 0)),
209 "Notation declared: ('notation', None, 'notation.jpeg', None)",
210 ('Entity declaration', ('acirc', 0, '\xe2', None, None, None, None)),
211 ('Entity declaration', ('external_entity', 0, None, None,
212 'entity.file', None, None)),
213 "Unparsed entity decl: ('unparsed_entity', None, 'entity.file', None, 'notation')",
214 "Not standalone",
215 "End doctype",
216 "Start element: 'root' {'attr1': 'value1', 'attr2': 'value2\u1f40'}",
217 "NS decl: 'myns' 'http://www.python.org/namespace'",
218 "Start element: 'http://www.python.org/namespace!subelement' {}",
219 "Character data: 'Contents of subelements'",
220 "End element: 'http://www.python.org/namespace!subelement'",
221 "End of NS decl: 'myns'",
222 "Start element: 'sub2' {}",
223 'Start of CDATA section',
224 "Character data: 'contents of CDATA section'",
225 'End of CDATA section',
226 "End element: 'sub2'",
227 "External entity ref: (None, 'entity.file', None)",
228 ('Skipped entity', ('skipped_entity', 0)),
229 "Character data: '\xb5'",
230 "End element: 'root'",
231 ]
232 for operation, expected_operation in zip(operations, expected_operations):
233 self.assertEqual(operation, expected_operation)
234
235 def test_parse_bytes(self):
236 out = self.Outputter()
237 parser = expat.ParserCreate(namespace_separator='!')
238 self._hookup_callbacks(parser, out)
239
240 parser.Parse(data, True)
241
242 operations = out.out
243 self._verify_parse_output(operations)
244 # Issue #6697.
245 self.assertRaises(AttributeError, getattr, parser, '\uD800')
246
247 def test_parse_str(self):
248 out = self.Outputter()
249 parser = expat.ParserCreate(namespace_separator='!')
250 self._hookup_callbacks(parser, out)
251
252 parser.Parse(data.decode('iso-8859-1'), True)
253
254 operations = out.out
255 self._verify_parse_output(operations)
256
257 def test_parse_file(self):
258 # Try parsing a file
259 out = self.Outputter()
260 parser = expat.ParserCreate(namespace_separator='!')
261 self._hookup_callbacks(parser, out)
262 file = BytesIO(data)
263
264 parser.ParseFile(file)
265
266 operations = out.out
267 self._verify_parse_output(operations)
268
269 def test_parse_again(self):
270 parser = expat.ParserCreate()
271 file = BytesIO(data)
272 parser.ParseFile(file)
273 # Issue 6676: ensure a meaningful exception is raised when attempting
274 # to parse more than one XML document per xmlparser instance,
275 # a limitation of the Expat library.
276 with self.assertRaises(expat.error) as cm:
277 parser.ParseFile(file)
278 self.assertEqual(expat.ErrorString(cm.exception.code),
279 expat.errors.XML_ERROR_FINISHED)
280
281 class NamespaceSeparatorTest(unittest.TestCase):
282 def test_legal(self):
283 # Tests that make sure we get errors when the namespace_separator value
284 # is illegal, and that we don't for good values:
285 expat.ParserCreate()
286 expat.ParserCreate(namespace_separator=None)
287 expat.ParserCreate(namespace_separator=' ')
288
289 def test_illegal(self):
290 try:
291 expat.ParserCreate(namespace_separator=42)
292 self.fail()
293 except TypeError as e:
294 self.assertEqual(str(e),
295 "ParserCreate() argument 'namespace_separator' must be str or None, not int")
296
297 try:
298 expat.ParserCreate(namespace_separator='too long')
299 self.fail()
300 except ValueError as e:
301 self.assertEqual(str(e),
302 'namespace_separator must be at most one character, omitted, or None')
303
304 def test_zero_length(self):
305 # ParserCreate() needs to accept a namespace_separator of zero length
306 # to satisfy the requirements of RDF applications that are required
307 # to simply glue together the namespace URI and the localname. Though
308 # considered a wart of the RDF specifications, it needs to be supported.
309 #
310 # See XML-SIG mailing list thread starting with
311 # http://mail.python.org/pipermail/xml-sig/2001-April/005202.html
312 #
313 expat.ParserCreate(namespace_separator='') # too short
314
315
316 class InterningTest(unittest.TestCase):
317 def test(self):
318 # Test the interning machinery.
319 p = expat.ParserCreate()
320 L = []
321 def collector(name, *args):
322 L.append(name)
323 p.StartElementHandler = collector
324 p.EndElementHandler = collector
325 p.Parse(b"<e> <e/> <e></e> </e>", True)
326 tag = L[0]
327 self.assertEqual(len(L), 6)
328 for entry in L:
329 # L should have the same string repeated over and over.
330 self.assertTrue(tag is entry)
331
332 def test_issue9402(self):
333 # create an ExternalEntityParserCreate with buffer text
334 class ExternalOutputter:
335 def __init__(self, parser):
336 self.parser = parser
337 self.parser_result = None
338
339 def ExternalEntityRefHandler(self, context, base, sysId, pubId):
340 external_parser = self.parser.ExternalEntityParserCreate("")
341 self.parser_result = external_parser.Parse(b"", True)
342 return 1
343
344 parser = expat.ParserCreate(namespace_separator='!')
345 parser.buffer_text = 1
346 out = ExternalOutputter(parser)
347 parser.ExternalEntityRefHandler = out.ExternalEntityRefHandler
348 parser.Parse(data, True)
349 self.assertEqual(out.parser_result, 1)
350
351
352 class BufferTextTest(unittest.TestCase):
353 def setUp(self):
354 self.stuff = []
355 self.parser = expat.ParserCreate()
356 self.parser.buffer_text = 1
357 self.parser.CharacterDataHandler = self.CharacterDataHandler
358
359 def check(self, expected, label):
360 self.assertEqual(self.stuff, expected,
361 "%s\nstuff = %r\nexpected = %r"
362 % (label, self.stuff, map(str, expected)))
363
364 def CharacterDataHandler(self, text):
365 self.stuff.append(text)
366
367 def StartElementHandler(self, name, attrs):
368 self.stuff.append("<%s>" % name)
369 bt = attrs.get("buffer-text")
370 if bt == "yes":
371 self.parser.buffer_text = 1
372 elif bt == "no":
373 self.parser.buffer_text = 0
374
375 def EndElementHandler(self, name):
376 self.stuff.append("</%s>" % name)
377
378 def CommentHandler(self, data):
379 self.stuff.append("<!--%s-->" % data)
380
381 def setHandlers(self, handlers=[]):
382 for name in handlers:
383 setattr(self.parser, name, getattr(self, name))
384
385 def test_default_to_disabled(self):
386 parser = expat.ParserCreate()
387 self.assertFalse(parser.buffer_text)
388
389 def test_buffering_enabled(self):
390 # Make sure buffering is turned on
391 self.assertTrue(self.parser.buffer_text)
392 self.parser.Parse(b"<a>1<b/>2<c/>3</a>", True)
393 self.assertEqual(self.stuff, ['123'],
394 "buffered text not properly collapsed")
395
396 def test1(self):
397 # XXX This test exposes more detail of Expat's text chunking than we
398 # XXX like, but it tests what we need to concisely.
399 self.setHandlers(["StartElementHandler"])
400 self.parser.Parse(b"<a>1<b buffer-text='no'/>2\n3<c buffer-text='yes'/>4\n5</a>", True)
401 self.assertEqual(self.stuff,
402 ["<a>", "1", "<b>", "2", "\n", "3", "<c>", "4\n5"],
403 "buffering control not reacting as expected")
404
405 def test2(self):
406 self.parser.Parse(b"<a>1<b/>&lt;2&gt;<c/>&#32;\n&#x20;3</a>", True)
407 self.assertEqual(self.stuff, ["1<2> \n 3"],
408 "buffered text not properly collapsed")
409
410 def test3(self):
411 self.setHandlers(["StartElementHandler"])
412 self.parser.Parse(b"<a>1<b/>2<c/>3</a>", True)
413 self.assertEqual(self.stuff, ["<a>", "1", "<b>", "2", "<c>", "3"],
414 "buffered text not properly split")
415
416 def test4(self):
417 self.setHandlers(["StartElementHandler", "EndElementHandler"])
418 self.parser.CharacterDataHandler = None
419 self.parser.Parse(b"<a>1<b/>2<c/>3</a>", True)
420 self.assertEqual(self.stuff,
421 ["<a>", "<b>", "</b>", "<c>", "</c>", "</a>"])
422
423 def test5(self):
424 self.setHandlers(["StartElementHandler", "EndElementHandler"])
425 self.parser.Parse(b"<a>1<b></b>2<c/>3</a>", True)
426 self.assertEqual(self.stuff,
427 ["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "3", "</a>"])
428
429 def test6(self):
430 self.setHandlers(["CommentHandler", "EndElementHandler",
431 "StartElementHandler"])
432 self.parser.Parse(b"<a>1<b/>2<c></c>345</a> ", True)
433 self.assertEqual(self.stuff,
434 ["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "345", "</a>"],
435 "buffered text not properly split")
436
437 def test7(self):
438 self.setHandlers(["CommentHandler", "EndElementHandler",
439 "StartElementHandler"])
440 self.parser.Parse(b"<a>1<b/>2<c></c>3<!--abc-->4<!--def-->5</a> ", True)
441 self.assertEqual(self.stuff,
442 ["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "3",
443 "<!--abc-->", "4", "<!--def-->", "5", "</a>"],
444 "buffered text not properly split")
445
446
447 # Test handling of exception from callback:
448 class HandlerExceptionTest(unittest.TestCase):
449 def StartElementHandler(self, name, attrs):
450 raise RuntimeError(f'StartElementHandler: <{name}>')
451
452 def check_traceback_entry(self, entry, filename, funcname):
453 self.assertEqual(os.path.basename(entry.filename), filename)
454 self.assertEqual(entry.name, funcname)
455
456 @support.cpython_only
457 def test_exception(self):
458 # gh-66652: test _PyTraceback_Add() used by pyexpat.c to inject frames
459
460 # Change the current directory to the Python source code directory
461 # if it is available.
462 src_dir = sysconfig.get_config_var('abs_builddir')
463 if src_dir:
464 have_source = os.path.isdir(src_dir)
465 else:
466 have_source = False
467 if have_source:
468 with os_helper.change_cwd(src_dir):
469 self._test_exception(have_source)
470 else:
471 self._test_exception(have_source)
472
473 def _test_exception(self, have_source):
474 # Use path relative to the current directory which should be the Python
475 # source code directory (if it is available).
476 PYEXPAT_C = os.path.join('Modules', 'pyexpat.c')
477
478 parser = expat.ParserCreate()
479 parser.StartElementHandler = self.StartElementHandler
480 try:
481 parser.Parse(b"<a><b><c/></b></a>", True)
482
483 self.fail("the parser did not raise RuntimeError")
484 except RuntimeError as exc:
485 self.assertEqual(exc.args[0], 'StartElementHandler: <a>', exc)
486 entries = traceback.extract_tb(exc.__traceback__)
487
488 self.assertEqual(len(entries), 3, entries)
489 self.check_traceback_entry(entries[0],
490 "test_pyexpat.py", "_test_exception")
491 self.check_traceback_entry(entries[1],
492 os.path.basename(PYEXPAT_C),
493 "StartElement")
494 self.check_traceback_entry(entries[2],
495 "test_pyexpat.py", "StartElementHandler")
496
497 # Check that the traceback contains the relevant line in
498 # Modules/pyexpat.c. Skip the test if Modules/pyexpat.c is not
499 # available.
500 if have_source and os.path.exists(PYEXPAT_C):
501 self.assertIn('call_with_frame("StartElement"',
502 entries[1].line)
503
504
505 # Test Current* members:
506 class PositionTest(unittest.TestCase):
507 def StartElementHandler(self, name, attrs):
508 self.check_pos('s')
509
510 def EndElementHandler(self, name):
511 self.check_pos('e')
512
513 def check_pos(self, event):
514 pos = (event,
515 self.parser.CurrentByteIndex,
516 self.parser.CurrentLineNumber,
517 self.parser.CurrentColumnNumber)
518 self.assertTrue(self.upto < len(self.expected_list),
519 'too many parser events')
520 expected = self.expected_list[self.upto]
521 self.assertEqual(pos, expected,
522 'Expected position %s, got position %s' %(pos, expected))
523 self.upto += 1
524
525 def test(self):
526 self.parser = expat.ParserCreate()
527 self.parser.StartElementHandler = self.StartElementHandler
528 self.parser.EndElementHandler = self.EndElementHandler
529 self.upto = 0
530 self.expected_list = [('s', 0, 1, 0), ('s', 5, 2, 1), ('s', 11, 3, 2),
531 ('e', 15, 3, 6), ('e', 17, 4, 1), ('e', 22, 5, 0)]
532
533 xml = b'<a>\n <b>\n <c/>\n </b>\n</a>'
534 self.parser.Parse(xml, True)
535
536
537 class sf1296433Test(unittest.TestCase):
538 def test_parse_only_xml_data(self):
539 # http://python.org/sf/1296433
540 #
541 xml = "<?xml version='1.0' encoding='iso8859'?><s>%s</s>" % ('a' * 1025)
542 # this one doesn't crash
543 #xml = "<?xml version='1.0'?><s>%s</s>" % ('a' * 10000)
544
545 class SpecificException(Exception):
546 pass
547
548 def handler(text):
549 raise SpecificException
550
551 parser = expat.ParserCreate()
552 parser.CharacterDataHandler = handler
553
554 self.assertRaises(Exception, parser.Parse, xml.encode('iso8859'))
555
556 class ChardataBufferTest(unittest.TestCase):
557 """
558 test setting of chardata buffer size
559 """
560
561 def test_1025_bytes(self):
562 self.assertEqual(self.small_buffer_test(1025), 2)
563
564 def test_1000_bytes(self):
565 self.assertEqual(self.small_buffer_test(1000), 1)
566
567 def test_wrong_size(self):
568 parser = expat.ParserCreate()
569 parser.buffer_text = 1
570 with self.assertRaises(ValueError):
571 parser.buffer_size = -1
572 with self.assertRaises(ValueError):
573 parser.buffer_size = 0
574 with self.assertRaises((ValueError, OverflowError)):
575 parser.buffer_size = sys.maxsize + 1
576 with self.assertRaises(TypeError):
577 parser.buffer_size = 512.0
578
579 def test_unchanged_size(self):
580 xml1 = b"<?xml version='1.0' encoding='iso8859'?><s>" + b'a' * 512
581 xml2 = b'a'*512 + b'</s>'
582 parser = expat.ParserCreate()
583 parser.CharacterDataHandler = self.counting_handler
584 parser.buffer_size = 512
585 parser.buffer_text = 1
586
587 # Feed 512 bytes of character data: the handler should be called
588 # once.
589 self.n = 0
590 parser.Parse(xml1)
591 self.assertEqual(self.n, 1)
592
593 # Reassign to buffer_size, but assign the same size.
594 parser.buffer_size = parser.buffer_size
595 self.assertEqual(self.n, 1)
596
597 # Try parsing rest of the document
598 parser.Parse(xml2)
599 self.assertEqual(self.n, 2)
600
601
602 def test_disabling_buffer(self):
603 xml1 = b"<?xml version='1.0' encoding='iso8859'?><a>" + b'a' * 512
604 xml2 = b'b' * 1024
605 xml3 = b'c' * 1024 + b'</a>';
606 parser = expat.ParserCreate()
607 parser.CharacterDataHandler = self.counting_handler
608 parser.buffer_text = 1
609 parser.buffer_size = 1024
610 self.assertEqual(parser.buffer_size, 1024)
611
612 # Parse one chunk of XML
613 self.n = 0
614 parser.Parse(xml1, False)
615 self.assertEqual(parser.buffer_size, 1024)
616 self.assertEqual(self.n, 1)
617
618 # Turn off buffering and parse the next chunk.
619 parser.buffer_text = 0
620 self.assertFalse(parser.buffer_text)
621 self.assertEqual(parser.buffer_size, 1024)
622 for i in range(10):
623 parser.Parse(xml2, False)
624 self.assertEqual(self.n, 11)
625
626 parser.buffer_text = 1
627 self.assertTrue(parser.buffer_text)
628 self.assertEqual(parser.buffer_size, 1024)
629 parser.Parse(xml3, True)
630 self.assertEqual(self.n, 12)
631
632 def counting_handler(self, text):
633 self.n += 1
634
635 def small_buffer_test(self, buffer_len):
636 xml = b"<?xml version='1.0' encoding='iso8859'?><s>" + b'a' * buffer_len + b'</s>'
637 parser = expat.ParserCreate()
638 parser.CharacterDataHandler = self.counting_handler
639 parser.buffer_size = 1024
640 parser.buffer_text = 1
641
642 self.n = 0
643 parser.Parse(xml)
644 return self.n
645
646 def test_change_size_1(self):
647 xml1 = b"<?xml version='1.0' encoding='iso8859'?><a><s>" + b'a' * 1024
648 xml2 = b'aaa</s><s>' + b'a' * 1025 + b'</s></a>'
649 parser = expat.ParserCreate()
650 parser.CharacterDataHandler = self.counting_handler
651 parser.buffer_text = 1
652 parser.buffer_size = 1024
653 self.assertEqual(parser.buffer_size, 1024)
654
655 self.n = 0
656 parser.Parse(xml1, False)
657 parser.buffer_size *= 2
658 self.assertEqual(parser.buffer_size, 2048)
659 parser.Parse(xml2, True)
660 self.assertEqual(self.n, 2)
661
662 def test_change_size_2(self):
663 xml1 = b"<?xml version='1.0' encoding='iso8859'?><a>a<s>" + b'a' * 1023
664 xml2 = b'aaa</s><s>' + b'a' * 1025 + b'</s></a>'
665 parser = expat.ParserCreate()
666 parser.CharacterDataHandler = self.counting_handler
667 parser.buffer_text = 1
668 parser.buffer_size = 2048
669 self.assertEqual(parser.buffer_size, 2048)
670
671 self.n=0
672 parser.Parse(xml1, False)
673 parser.buffer_size = parser.buffer_size // 2
674 self.assertEqual(parser.buffer_size, 1024)
675 parser.Parse(xml2, True)
676 self.assertEqual(self.n, 4)
677
678 class MalformedInputTest(unittest.TestCase):
679 def test1(self):
680 xml = b"\0\r\n"
681 parser = expat.ParserCreate()
682 try:
683 parser.Parse(xml, True)
684 self.fail()
685 except expat.ExpatError as e:
686 self.assertEqual(str(e), 'unclosed token: line 2, column 0')
687
688 def test2(self):
689 # \xc2\x85 is UTF-8 encoded U+0085 (NEXT LINE)
690 xml = b"<?xml version\xc2\x85='1.0'?>\r\n"
691 parser = expat.ParserCreate()
692 err_pattern = r'XML declaration not well-formed: line 1, column \d+'
693 with self.assertRaisesRegex(expat.ExpatError, err_pattern):
694 parser.Parse(xml, True)
695
696 class ErrorMessageTest(unittest.TestCase):
697 def test_codes(self):
698 # verify mapping of errors.codes and errors.messages
699 self.assertEqual(errors.XML_ERROR_SYNTAX,
700 errors.messages[errors.codes[errors.XML_ERROR_SYNTAX]])
701
702 def test_expaterror(self):
703 xml = b'<'
704 parser = expat.ParserCreate()
705 try:
706 parser.Parse(xml, True)
707 self.fail()
708 except expat.ExpatError as e:
709 self.assertEqual(e.code,
710 errors.codes[errors.XML_ERROR_UNCLOSED_TOKEN])
711
712
713 class ForeignDTDTests(unittest.TestCase):
714 """
715 Tests for the UseForeignDTD method of expat parser objects.
716 """
717 def test_use_foreign_dtd(self):
718 """
719 If UseForeignDTD is passed True and a document without an external
720 entity reference is parsed, ExternalEntityRefHandler is first called
721 with None for the public and system ids.
722 """
723 handler_call_args = []
724 def resolve_entity(context, base, system_id, public_id):
725 handler_call_args.append((public_id, system_id))
726 return 1
727
728 parser = expat.ParserCreate()
729 parser.UseForeignDTD(True)
730 parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS)
731 parser.ExternalEntityRefHandler = resolve_entity
732 parser.Parse(b"<?xml version='1.0'?><element/>")
733 self.assertEqual(handler_call_args, [(None, None)])
734
735 # test UseForeignDTD() is equal to UseForeignDTD(True)
736 handler_call_args[:] = []
737
738 parser = expat.ParserCreate()
739 parser.UseForeignDTD()
740 parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS)
741 parser.ExternalEntityRefHandler = resolve_entity
742 parser.Parse(b"<?xml version='1.0'?><element/>")
743 self.assertEqual(handler_call_args, [(None, None)])
744
745 def test_ignore_use_foreign_dtd(self):
746 """
747 If UseForeignDTD is passed True and a document with an external
748 entity reference is parsed, ExternalEntityRefHandler is called with
749 the public and system ids from the document.
750 """
751 handler_call_args = []
752 def resolve_entity(context, base, system_id, public_id):
753 handler_call_args.append((public_id, system_id))
754 return 1
755
756 parser = expat.ParserCreate()
757 parser.UseForeignDTD(True)
758 parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS)
759 parser.ExternalEntityRefHandler = resolve_entity
760 parser.Parse(
761 b"<?xml version='1.0'?><!DOCTYPE foo PUBLIC 'bar' 'baz'><element/>")
762 self.assertEqual(handler_call_args, [("bar", "baz")])
763
764
765 class ParentParserLifetimeTest(unittest.TestCase):
766 """
767 Subparsers make use of their parent XML_Parser inside of Expat.
768 As a result, parent parsers need to outlive subparsers.
769
770 See https://github.com/python/cpython/issues/139400.
771 """
772
773 def test_parent_parser_outlives_its_subparsers__single(self):
774 parser = expat.ParserCreate()
775 subparser = parser.ExternalEntityParserCreate(None)
776
777 # Now try to cause garbage collection of the parent parser
778 # while it's still being referenced by a related subparser.
779 del parser
780
781 def test_parent_parser_outlives_its_subparsers__multiple(self):
782 parser = expat.ParserCreate()
783 subparser_one = parser.ExternalEntityParserCreate(None)
784 subparser_two = parser.ExternalEntityParserCreate(None)
785
786 # Now try to cause garbage collection of the parent parser
787 # while it's still being referenced by a related subparser.
788 del parser
789
790 def test_parent_parser_outlives_its_subparsers__chain(self):
791 parser = expat.ParserCreate()
792 subparser = parser.ExternalEntityParserCreate(None)
793 subsubparser = subparser.ExternalEntityParserCreate(None)
794
795 # Now try to cause garbage collection of the parent parsers
796 # while they are still being referenced by a related subparser.
797 del parser
798 del subparser
799
800
801 class ReparseDeferralTest(unittest.TestCase):
802 def test_getter_setter_round_trip(self):
803 parser = expat.ParserCreate()
804 enabled = (expat.version_info >= (2, 6, 0))
805
806 self.assertIs(parser.GetReparseDeferralEnabled(), enabled)
807 parser.SetReparseDeferralEnabled(False)
808 self.assertIs(parser.GetReparseDeferralEnabled(), False)
809 parser.SetReparseDeferralEnabled(True)
810 self.assertIs(parser.GetReparseDeferralEnabled(), enabled)
811
812 def test_reparse_deferral_enabled(self):
813 if expat.version_info < (2, 6, 0):
814 self.skipTest(f'Expat {expat.version_info} does not '
815 'support reparse deferral')
816
817 started = []
818
819 def start_element(name, _):
820 started.append(name)
821
822 parser = expat.ParserCreate()
823 parser.StartElementHandler = start_element
824 self.assertTrue(parser.GetReparseDeferralEnabled())
825
826 for chunk in (b'<doc', b'/>'):
827 parser.Parse(chunk, False)
828
829 # The key test: Have handlers already fired? Expecting: no.
830 self.assertEqual(started, [])
831
832 parser.Parse(b'', True)
833
834 self.assertEqual(started, ['doc'])
835
836 def test_reparse_deferral_disabled(self):
837 started = []
838
839 def start_element(name, _):
840 started.append(name)
841
842 parser = expat.ParserCreate()
843 parser.StartElementHandler = start_element
844 if expat.version_info >= (2, 6, 0):
845 parser.SetReparseDeferralEnabled(False)
846 self.assertFalse(parser.GetReparseDeferralEnabled())
847
848 for chunk in (b'<doc', b'/>'):
849 parser.Parse(chunk, False)
850
851 # The key test: Have handlers already fired? Expecting: yes.
852 self.assertEqual(started, ['doc'])
853
854
855 class AttackProtectionTestBase(abc.ABC):
856 """
857 Base class for testing protections against XML payloads with
858 disproportionate amplification.
859
860 The protections being tested should detect and prevent attacks
861 that leverage disproportionate amplification from small inputs.
862 """
863
864 @staticmethod
865 def exponential_expansion_payload(*, nrows, ncols, text='.'):
866 """Create a billion laughs attack payload.
867
868 Be careful: the number of total items is pow(n, k), thereby
869 requiring at least pow(ncols, nrows) * sizeof(text) memory!
870 """
871 template = textwrap.dedent(f"""\
872 <?xml version="1.0"?>
873 <!DOCTYPE doc [
874 <!ENTITY row0 "{text}">
875 <!ELEMENT doc (#PCDATA)>
876 {{body}}
877 ]>
878 <doc>&row{nrows};</doc>
879 """).rstrip()
880
881 body = '\n'.join(
882 f'<!ENTITY row{i + 1} "{f"&row{i};" * ncols}">'
883 for i in range(nrows)
884 )
885 body = textwrap.indent(body, ' ' * 4)
886 return template.format(body=body)
887
888 def test_payload_generation(self):
889 # self-test for exponential_expansion_payload()
890 payload = self.exponential_expansion_payload(nrows=2, ncols=3)
891 self.assertEqual(payload, textwrap.dedent("""\
892 <?xml version="1.0"?>
893 <!DOCTYPE doc [
894 <!ENTITY row0 ".">
895 <!ELEMENT doc (#PCDATA)>
896 <!ENTITY row1 "&row0;&row0;&row0;">
897 <!ENTITY row2 "&row1;&row1;&row1;">
898 ]>
899 <doc>&row2;</doc>
900 """).rstrip())
901
902 def assert_root_parser_failure(self, func, /, *args, **kwargs):
903 """Check that func(*args, **kwargs) is invalid for a sub-parser."""
904 msg = "parser must be a root parser"
905 self.assertRaisesRegex(expat.ExpatError, msg, func, *args, **kwargs)
906
907 @abc.abstractmethod
908 def assert_rejected(self, func, /, *args, **kwargs):
909 """Assert that func(*args, **kwargs) triggers the attack protection.
910
911 Note: this method must ensure that the attack protection being tested
912 is the one that is actually triggered at runtime, e.g., by matching
913 the exact error message.
914 """
915
916 @abc.abstractmethod
917 def set_activation_threshold(self, parser, threshold):
918 """Set the activation threshold for the tested protection."""
919
920 @abc.abstractmethod
921 def set_maximum_amplification(self, parser, max_factor):
922 """Set the maximum amplification factor for the tested protection."""
923
924 @abc.abstractmethod
925 def test_set_activation_threshold__threshold_reached(self):
926 """Test when the activation threshold is exceeded."""
927
928 @abc.abstractmethod
929 def test_set_activation_threshold__threshold_not_reached(self):
930 """Test when the activation threshold is not exceeded."""
931
932 def test_set_activation_threshold__invalid_threshold_type(self):
933 parser = expat.ParserCreate()
934 setter = functools.partial(self.set_activation_threshold, parser)
935
936 self.assertRaises(TypeError, setter, 1.0)
937 self.assertRaises(TypeError, setter, -1.5)
938 self.assertRaises(ValueError, setter, -5)
939
940 def test_set_activation_threshold__invalid_threshold_range(self):
941 _testcapi = import_helper.import_module("_testcapi")
942 parser = expat.ParserCreate()
943 setter = functools.partial(self.set_activation_threshold, parser)
944
945 self.assertRaises(OverflowError, setter, _testcapi.ULLONG_MAX + 1)
946
947 def test_set_activation_threshold__fail_for_subparser(self):
948 parser = expat.ParserCreate()
949 subparser = parser.ExternalEntityParserCreate(None)
950 setter = functools.partial(self.set_activation_threshold, subparser)
951 self.assert_root_parser_failure(setter, 12345)
952
953 @abc.abstractmethod
954 def test_set_maximum_amplification__amplification_exceeded(self):
955 """Test when the amplification factor is exceeded."""
956
957 @abc.abstractmethod
958 def test_set_maximum_amplification__amplification_not_exceeded(self):
959 """Test when the amplification factor is not exceeded."""
960
961 def test_set_maximum_amplification__infinity(self):
962 inf = float('inf') # an 'inf' threshold is allowed by Expat
963 parser = expat.ParserCreate()
964 self.assertIsNone(self.set_maximum_amplification(parser, inf))
965
966 def test_set_maximum_amplification__invalid_max_factor_type(self):
967 parser = expat.ParserCreate()
968 setter = functools.partial(self.set_maximum_amplification, parser)
969
970 self.assertRaises(TypeError, setter, None)
971 self.assertRaises(TypeError, setter, 'abc')
972
973 def test_set_maximum_amplification__invalid_max_factor_range(self):
974 parser = expat.ParserCreate()
975 setter = functools.partial(self.set_maximum_amplification, parser)
976
977 msg = re.escape("'max_factor' must be at least 1.0")
978 self.assertRaisesRegex(expat.ExpatError, msg, setter, float('nan'))
979 self.assertRaisesRegex(expat.ExpatError, msg, setter, 0.99)
980
981 def test_set_maximum_amplification__fail_for_subparser(self):
982 parser = expat.ParserCreate()
983 subparser = parser.ExternalEntityParserCreate(None)
984 setter = functools.partial(self.set_maximum_amplification, subparser)
985 self.assert_root_parser_failure(setter, 123.45)
986
987
988 @unittest.skipIf(expat.version_info < (2, 7, 2), "requires Expat >= 2.7.2")
989 class MemoryProtectionTest(AttackProtectionTestBase, unittest.TestCase):
990
991 # NOTE: with the default Expat configuration, the billion laughs protection
992 # may hit before the allocation limiter if exponential_expansion_payload()
993 # is not carefully parametrized. As such, the payloads should be chosen so
994 # that either the allocation limiter is hit before other protections are
995 # triggered or no protection at all is triggered.
996
997 def assert_rejected(self, func, /, *args, **kwargs):
998 """Check that func(*args, **kwargs) hits the allocation limit."""
999 msg = r"out of memory: line \d+, column \d+"
1000 self.assertRaisesRegex(expat.ExpatError, msg, func, *args, **kwargs)
1001
1002 def set_activation_threshold(self, parser, threshold):
1003 return parser.SetAllocTrackerActivationThreshold(threshold)
1004
1005 def set_maximum_amplification(self, parser, max_factor):
1006 return parser.SetAllocTrackerMaximumAmplification(max_factor)
1007
1008 def test_set_activation_threshold__threshold_reached(self):
1009 parser = expat.ParserCreate()
1010 # Choose a threshold expected to be always reached.
1011 self.set_activation_threshold(parser, 3)
1012 # Check that the threshold is reached by choosing a small factor
1013 # and a payload whose peak amplification factor exceeds it.
1014 self.assertIsNone(self.set_maximum_amplification(parser, 1.0))
1015 payload = self.exponential_expansion_payload(ncols=10, nrows=4)
1016 self.assert_rejected(parser.Parse, payload, True)
1017
1018 def test_set_activation_threshold__threshold_not_reached(self):
1019 parser = expat.ParserCreate()
1020 # Choose a threshold expected to be never reached.
1021 self.set_activation_threshold(parser, pow(10, 5))
1022 # Check that the threshold is reached by choosing a small factor
1023 # and a payload whose peak amplification factor exceeds it.
1024 self.assertIsNone(self.set_maximum_amplification(parser, 1.0))
1025 payload = self.exponential_expansion_payload(ncols=10, nrows=4)
1026 self.assertIsNotNone(parser.Parse(payload, True))
1027
1028 def test_set_maximum_amplification__amplification_exceeded(self):
1029 parser = expat.ParserCreate()
1030 # Unconditionally enable maximum activation factor.
1031 self.set_activation_threshold(parser, 0)
1032 # Choose a max amplification factor expected to always be exceeded.
1033 self.assertIsNone(self.set_maximum_amplification(parser, 1.0))
1034 # Craft a payload for which the peak amplification factor is > 1.0.
1035 payload = self.exponential_expansion_payload(ncols=1, nrows=2)
1036 self.assert_rejected(parser.Parse, payload, True)
1037
1038 def test_set_maximum_amplification__amplification_not_exceeded(self):
1039 parser = expat.ParserCreate()
1040 # Unconditionally enable maximum activation factor.
1041 self.set_activation_threshold(parser, 0)
1042 # Choose a max amplification factor expected to never be exceeded.
1043 self.assertIsNone(self.set_maximum_amplification(parser, 1e4))
1044 # Craft a payload for which the peak amplification factor is < 1e4.
1045 payload = self.exponential_expansion_payload(ncols=1, nrows=2)
1046 self.assertIsNotNone(parser.Parse(payload, True))
1047
1048
1049 if __name__ == "__main__":
1050 unittest.main()