Debian Codegraph @

Lib/test/test_pyexpat.py

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