Debian Codegraph @

tests/test_xmltodict.py

raw
1 from xmltodict import parse, ParsingInterrupted
2 import collections
3 import pytest
4 from io import BytesIO
5
6 from xml.parsers.expat import ParserCreate
7 from xml.parsers import expat
8
9
10 def test_string_vs_file():
11 xml = '<a>data</a>'
12 assert parse(xml) == parse(BytesIO(xml.encode('ascii')))
13
14
15 def test_minimal():
16 assert parse('<a/>') == {'a': None}
17 assert parse('<a/>', force_cdata=True) == {'a': None}
18
19
20 def test_simple():
21 assert parse('<a>data</a>') == {'a': 'data'}
22
23
24 def test_force_cdata():
25 assert parse('<a>data</a>', force_cdata=True) == {'a': {'#text': 'data'}}
26
27
28 def test_selective_force_cdata_tuple():
29 xml = "<a><b>data1</b><c>data2</c><d>data3</d></a>"
30 # Test with tuple of specific element names
31 result = parse(xml, force_cdata=("b", "d"))
32 expected = {
33 "a": {"b": {"#text": "data1"}, "c": "data2", "d": {"#text": "data3"}}
34 }
35 assert result == expected
36
37
38 def test_selective_force_cdata_single_element():
39 xml = "<a><b>data1</b><c>data2</c></a>"
40 # Test with single element name
41 result = parse(xml, force_cdata=("b",))
42 expected = {"a": {"b": {"#text": "data1"}, "c": "data2"}}
43 assert result == expected
44
45
46 def test_selective_force_cdata_empty_tuple():
47 xml = "<a><b>data1</b><c>data2</c></a>"
48 # Test with empty tuple (should behave like force_cdata=False)
49 result = parse(xml, force_cdata=())
50 expected = {"a": {"b": "data1", "c": "data2"}}
51 assert result == expected
52
53
54 def test_selective_force_cdata_callable():
55 xml = "<a><b>data1</b><c>data2</c><d>data3</d></a>"
56
57 # Test with callable function
58 def should_force_cdata(path, key, value):
59 return key in ["b", "d"]
60
61 result = parse(xml, force_cdata=should_force_cdata)
62 expected = {
63 "a": {"b": {"#text": "data1"}, "c": "data2", "d": {"#text": "data3"}}
64 }
65 assert result == expected
66
67
68 def test_selective_force_cdata_nested_elements():
69 xml = "<a><b><c>data1</c></b><d>data2</d></a>"
70 # Test with nested elements - only 'c' should be forced
71 result = parse(xml, force_cdata=("c",))
72 expected = {"a": {"b": {"c": {"#text": "data1"}}, "d": "data2"}}
73 assert result == expected
74
75
76 def test_selective_force_cdata_with_attributes():
77 xml = '<a><b attr="value">data1</b><c>data2</c></a>'
78 # Test with attributes - force_cdata should still work
79 result = parse(xml, force_cdata=("b",))
80 expected = {"a": {"b": {"@attr": "value", "#text": "data1"}, "c": "data2"}}
81 assert result == expected
82
83
84 def test_selective_force_cdata_backwards_compatibility():
85 xml = "<a><b>data1</b><c>data2</c></a>"
86 # Test that boolean True still works (backwards compatibility)
87 result_true = parse(xml, force_cdata=True)
88 expected_true = {"a": {"b": {"#text": "data1"}, "c": {"#text": "data2"}}}
89 assert result_true == expected_true
90
91 # Test that boolean False still works (backwards compatibility)
92 result_false = parse(xml, force_cdata=False)
93 expected_false = {"a": {"b": "data1", "c": "data2"}}
94 assert result_false == expected_false
95
96
97 def test_custom_cdata():
98 assert parse('<a>data</a>', force_cdata=True, cdata_key='_CDATA_') == {'a': {'_CDATA_': 'data'}}
99
100
101 def test_list():
102 assert parse('<a><b>1</b><b>2</b><b>3</b></a>') == {'a': {'b': ['1', '2', '3']}}
103
104
105 def test_attrib():
106 assert parse('<a href="xyz"/>') == {'a': {'@href': 'xyz'}}
107
108
109 def test_skip_attrib():
110 assert parse('<a href="xyz"/>', xml_attribs=False) == {'a': None}
111
112
113 def test_custom_attrib():
114 assert parse('<a href="xyz"/>', attr_prefix='!') == {'a': {'!href': 'xyz'}}
115
116
117 def test_attrib_and_cdata():
118 assert parse('<a href="xyz">123</a>') == {'a': {'@href': 'xyz', '#text': '123'}}
119
120
121 def test_semi_structured():
122 assert parse('<a>abc<b/>def</a>') == {'a': {'b': None, '#text': 'abcdef'}}
123 assert parse('<a>abc<b/>def</a>', cdata_separator='\n') == {'a': {'b': None, '#text': 'abc\ndef'}}
124
125
126 def test_nested_semi_structured():
127 assert parse('<a>abc<b>123<c/>456</b>def</a>') == {'a': {'#text': 'abcdef', 'b': {'#text': '123456', 'c': None}}}
128
129
130 def test_skip_whitespace():
131 xml = """
132 <root>
133
134
135 <emptya> </emptya>
136 <emptyb attr="attrvalue">
137
138
139 </emptyb>
140 <value>hello</value>
141 </root>
142 """
143 assert parse(xml) == {'root': {'emptya': None, 'emptyb': {'@attr': 'attrvalue'}, 'value': 'hello'}}
144
145
146 def test_keep_whitespace():
147 xml = "<root> </root>"
148 assert parse(xml) == dict(root=None)
149 assert parse(xml, strip_whitespace=False) == dict(root=' ')
150
151
152 def test_streaming():
153 def cb(path, item):
154 cb.count += 1
155 assert path == [('a', {'x': 'y'}), ('b', None)]
156 assert item == str(cb.count)
157 return True
158 cb.count = 0
159 parse('<a x="y"><b>1</b><b>2</b><b>3</b></a>', item_depth=2, item_callback=cb)
160 assert cb.count == 3
161
162
163 def test_streaming_interrupt():
164 def cb(path, item):
165 return False
166 with pytest.raises(ParsingInterrupted):
167 parse('<a>x</a>', item_depth=1, item_callback=cb)
168
169
170 def test_streaming_generator():
171 def cb(path, item):
172 cb.count += 1
173 assert path == [('a', {'x': 'y'}), ('b', None)]
174 assert item == str(cb.count)
175 return True
176 cb.count = 0
177 parse((n for n in '<a x="y"><b>1</b><b>2</b><b>3</b></a>'), item_depth=2, item_callback=cb)
178 assert cb.count == 3
179
180
181 def test_streaming_returns_none():
182 # When streaming (item_depth > 0), parse should return None
183 def cb(path, item):
184 return True
185
186 result = parse("<a><b>1</b><b>2</b></a>", item_depth=2, item_callback=cb)
187 assert result is None
188
189
190 def test_postprocessor():
191 def postprocessor(path, key, value):
192 try:
193 return key + ':int', int(value)
194 except (ValueError, TypeError):
195 return key, value
196 assert {'a': {'b:int': [1, 2], 'b': 'x'}} == parse('<a><b>1</b><b>2</b><b>x</b></a>', postprocessor=postprocessor)
197
198
199 def test_postprocessor_attribute():
200 def postprocessor(path, key, value):
201 try:
202 return key + ':int', int(value)
203 except (ValueError, TypeError):
204 return key, value
205 assert {'a': {'@b:int': 1}} == parse('<a b="1"/>', postprocessor=postprocessor)
206
207
208 def test_postprocessor_skip():
209 def postprocessor(path, key, value):
210 if key == 'b':
211 value = int(value)
212 if value == 3:
213 return None
214 return key, value
215 assert {'a': {'b': [1, 2]}} == parse('<a><b>1</b><b>2</b><b>3</b></a>', postprocessor=postprocessor)
216
217
218 def test_unicode():
219 value = chr(39321)
220 assert {'a': value} == parse(f'<a>{value}</a>')
221
222
223 def test_encoded_string():
224 value = chr(39321)
225 xml = f'<a>{value}</a>'
226 assert parse(xml) == parse(xml.encode('utf-8'))
227
228
229 def test_namespace_support():
230 xml = """
231 <root xmlns="http://defaultns.com/"
232 xmlns:a="http://a.com/"
233 xmlns:b="http://b.com/"
234 version="1.00">
235 <x a:attr="val">1</x>
236 <a:y>2</a:y>
237 <b:z>3</b:z>
238 </root>
239 """
240 d = {
241 'http://defaultns.com/:root': {
242 '@version': '1.00',
243 '@xmlns': {
244 '': 'http://defaultns.com/',
245 'a': 'http://a.com/',
246 'b': 'http://b.com/',
247 },
248 'http://defaultns.com/:x': {
249 '@http://a.com/:attr': 'val',
250 '#text': '1',
251 },
252 'http://a.com/:y': '2',
253 'http://b.com/:z': '3',
254 }
255 }
256 res = parse(xml, process_namespaces=True)
257 assert res == d
258
259
260 def test_namespace_collapse():
261 xml = """
262 <root xmlns="http://defaultns.com/"
263 xmlns:a="http://a.com/"
264 xmlns:b="http://b.com/"
265 version="1.00">
266 <x a:attr="val">1</x>
267 <a:y>2</a:y>
268 <b:z>3</b:z>
269 </root>
270 """
271 namespaces = {
272 'http://defaultns.com/': '',
273 'http://a.com/': 'ns_a',
274 }
275 d = {
276 'root': {
277 '@version': '1.00',
278 '@xmlns': {
279 '': 'http://defaultns.com/',
280 'a': 'http://a.com/',
281 'b': 'http://b.com/',
282 },
283 'x': {
284 '@ns_a:attr': 'val',
285 '#text': '1',
286 },
287 'ns_a:y': '2',
288 'http://b.com/:z': '3',
289 },
290 }
291 res = parse(xml, process_namespaces=True, namespaces=namespaces)
292 assert res == d
293
294
295 def test_namespace_collapse_all():
296 xml = """
297 <root xmlns="http://defaultns.com/"
298 xmlns:a="http://a.com/"
299 xmlns:b="http://b.com/"
300 version="1.00">
301 <x a:attr="val">1</x>
302 <a:y>2</a:y>
303 <b:z>3</b:z>
304 </root>
305 """
306 namespaces = collections.defaultdict(lambda: None)
307 d = {
308 'root': {
309 '@version': '1.00',
310 '@xmlns': {
311 '': 'http://defaultns.com/',
312 'a': 'http://a.com/',
313 'b': 'http://b.com/',
314 },
315 'x': {
316 '@attr': 'val',
317 '#text': '1',
318 },
319 'y': '2',
320 'z': '3',
321 },
322 }
323 res = parse(xml, process_namespaces=True, namespaces=namespaces)
324 assert res == d
325
326
327 def test_namespace_ignore():
328 xml = """
329 <root xmlns="http://defaultns.com/"
330 xmlns:a="http://a.com/"
331 xmlns:b="http://b.com/"
332 version="1.00">
333 <x>1</x>
334 <a:y>2</a:y>
335 <b:z>3</b:z>
336 </root>
337 """
338 d = {
339 'root': {
340 '@xmlns': 'http://defaultns.com/',
341 '@xmlns:a': 'http://a.com/',
342 '@xmlns:b': 'http://b.com/',
343 '@version': '1.00',
344 'x': '1',
345 'a:y': '2',
346 'b:z': '3',
347 },
348 }
349 assert parse(xml) == d
350
351
352 def test_force_list_basic():
353 xml = """
354 <servers>
355 <server>
356 <name>server1</name>
357 <os>os1</os>
358 </server>
359 </servers>
360 """
361 expectedResult = {
362 'servers': {
363 'server': [
364 {
365 'name': 'server1',
366 'os': 'os1',
367 },
368 ],
369 }
370 }
371 assert parse(xml, force_list=('server',)) == expectedResult
372
373
374 def test_force_list_callable():
375 xml = """
376 <config>
377 <servers>
378 <server>
379 <name>server1</name>
380 <os>os1</os>
381 </server>
382 </servers>
383 <skip>
384 <server></server>
385 </skip>
386 </config>
387 """
388
389 def force_list(path, key, value):
390 """Only return True for servers/server, but not for skip/server."""
391 if key != 'server':
392 return False
393 return path and path[-1][0] == 'servers'
394
395 expectedResult = {
396 'config': {
397 'servers': {
398 'server': [
399 {
400 'name': 'server1',
401 'os': 'os1',
402 },
403 ],
404 },
405 'skip': {
406 'server': None,
407 },
408 },
409 }
410 assert parse(xml, force_list=force_list, dict_constructor=dict) == expectedResult
411
412
413 def test_disable_entities_true_rejects_xmlbomb():
414 xml = """
415 <!DOCTYPE xmlbomb [
416 <!ENTITY a "1234567890" >
417 <!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;">
418 <!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;">
419 ]>
420 <bomb>&c;</bomb>
421 """
422 with pytest.raises(ValueError, match="entities are disabled"):
423 parse(xml, disable_entities=True)
424
425
426 def test_disable_entities_false_returns_xmlbomb():
427 xml = """
428 <!DOCTYPE xmlbomb [
429 <!ENTITY a "1234567890" >
430 <!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;">
431 <!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;">
432 ]>
433 <bomb>&c;</bomb>
434 """
435 bomb = "1234567890" * 64
436 expectedResult = {'bomb': bomb}
437 assert parse(xml, disable_entities=False) == expectedResult
438
439
440 def test_external_entity():
441 xml = """
442 <!DOCTYPE external [
443 <!ENTITY ee SYSTEM "http://www.python.org/">
444 ]>
445 <root>&ee;</root>
446 """
447 with pytest.raises(ValueError, match="entities are disabled"):
448 parse(xml)
449 assert parse(xml, disable_entities=False) == {"root": None}
450
451
452 def test_external_entity_with_custom_expat():
453 xml = """
454 <!DOCTYPE external [
455 <!ENTITY ee SYSTEM "http://www.python.org/">
456 ]>
457 <root>&ee;</root>
458 """
459
460 class CustomExpat:
461 def __init__(self, external_entity_result):
462 self.external_entity_result = external_entity_result
463
464 def ParserCreate(self, *args, **kwargs):
465 parser = ParserCreate(*args, **kwargs)
466
467 def _handler(*args, **kwargs):
468 return self.external_entity_result
469
470 parser.ExternalEntityRefHandler = _handler
471 return parser
472
473 ExpatError = expat.ExpatError
474
475 with pytest.raises(expat.ExpatError):
476 parse(xml, disable_entities=False, expat=CustomExpat(0))
477 assert parse(xml, disable_entities=False, expat=CustomExpat(1)) == {"root": None}
478 with pytest.raises(ValueError):
479 assert parse(xml, disable_entities=True, expat=CustomExpat(1))
480 with pytest.raises(ValueError):
481 assert parse(xml, disable_entities=True, expat=CustomExpat(0))
482
483
484 def test_disable_entities_true_allows_doctype_without_entities():
485 xml = """<?xml version='1.0' encoding='UTF-8'?>
486 <!DOCTYPE data SYSTEM "diagram.dtd">
487 <foo>bar</foo>
488 """
489 assert parse(xml, disable_entities=True) == {"foo": "bar"}
490 assert parse(xml, disable_entities=False) == {"foo": "bar"}
491
492
493 def test_disable_entities_allows_comments_by_default():
494 xml = """
495 <a>
496 <!-- ignored -->
497 <b>1</b>
498 </a>
499 """
500 assert parse(xml) == {'a': {'b': '1'}}
501
502
503 def test_comments():
504 xml = """
505 <a>
506 <b>
507 <!-- b comment -->
508 <c>
509 <!-- c comment -->
510 1
511 </c>
512 <d>2</d>
513 </b>
514 </a>
515 """
516 expectedResult = {
517 'a': {
518 'b': {
519 '#comment': 'b comment',
520 'c': {
521
522 '#comment': 'c comment',
523 '#text': '1',
524 },
525 'd': '2',
526 },
527 }
528 }
529 assert parse(xml, process_comments=True) == expectedResult
530
531
532 def test_streaming_with_comments_and_attrs():
533 xml = """
534 <a>
535 <b attr1="value">
536 <!-- note -->
537 <c>cdata</c>
538 </b>
539 </a>
540 """
541
542 def handler(path, item):
543 expected = {
544 "@attr1": "value",
545 "#comment": "note",
546 "c": "cdata",
547 }
548 assert expected == item
549 return True
550
551 parse(xml, item_depth=2, item_callback=handler, process_comments=True)
552
553
554 def test_streaming_memory_usage():
555 # Guard against re-introducing accumulation of streamed items into parent
556 try:
557 import tracemalloc
558 except ImportError:
559 pytest.skip("tracemalloc not available")
560
561 NUM_ITEMS = 20000
562
563 def xml_gen():
564 yield "<a>"
565 # generate many children with attribute and text
566 for i in range(NUM_ITEMS):
567 yield f'<b attr="v">{i % 10}</b>'
568 yield "</a>"
569
570 count = 0
571
572 def cb(path, item):
573 nonlocal count
574 count += 1
575 return True
576
577 tracemalloc.start()
578 parse(xml_gen(), item_depth=2, item_callback=cb)
579 current, peak = tracemalloc.get_traced_memory()
580 tracemalloc.stop()
581
582 assert count == NUM_ITEMS
583 # Peak memory should remain reasonably bounded; choose a conservative threshold
584 # This value should stay well below pathological accumulation levels
585 MAX_BYTES = 32 * 1024 # 32 KiB
586 assert peak < MAX_BYTES, f"peak memory too high: {peak} bytes"
587
588
589 def test_streaming_attrs():
590 xml = """
591 <a>
592 <b attr1="value">
593 <c>cdata</c>
594 </b>
595 </a>
596 """
597 def handler(path, item):
598 expected = {
599 '@attr1': 'value',
600 'c': 'cdata'
601 }
602 assert expected == item
603 return True
604
605 parse(xml, item_depth=2, item_callback=handler)
606
607
608 def test_namespace_on_root_without_other_attrs():
609 xml = """
610 <MyXML xmlns="http://www.xml.org/schemas/Test">
611 <Tag1>Text1</Tag1>
612 <Tag2 attr2="en">Text2</Tag2>
613 <Tag3>Text3</Tag3>
614 <Tag4 attr4="en">Text4</Tag4>
615 </MyXML>
616 """
617 namespaces = {
618 "http://www.xml.org/schemas/Test": None,
619 }
620 expected = {
621 "MyXML": {
622 "@xmlns": {"": "http://www.xml.org/schemas/Test"},
623 "Tag1": "Text1",
624 "Tag2": {"@attr2": "en", "#text": "Text2"},
625 "Tag3": "Text3",
626 "Tag4": {"@attr4": "en", "#text": "Text4"},
627 }
628 }
629 assert parse(xml, process_namespaces=True, namespaces=namespaces) == expected