Debian Codegraph @

tests/test_dicttoxml.py

raw
1 from xmltodict import parse, unparse
2 import pytest
3 import re
4 from textwrap import dedent
5
6 _HEADER_RE = re.compile(r'^[^\n]*\n')
7
8
9 def _strip(fullxml):
10 return _HEADER_RE.sub('', fullxml)
11
12
13 def test_root():
14 obj = {'a': None}
15 assert obj == parse(unparse(obj))
16 assert unparse(obj) == unparse(parse(unparse(obj)))
17
18
19 def test_simple_cdata():
20 obj = {'a': 'b'}
21 assert obj == parse(unparse(obj))
22 assert unparse(obj) == unparse(parse(unparse(obj)))
23
24
25 def test_cdata():
26 obj = {'a': {'#text': 'y'}}
27 assert obj == parse(unparse(obj), force_cdata=True)
28 assert unparse(obj) == unparse(parse(unparse(obj)))
29
30
31 def test_attrib():
32 obj = {'a': {'@href': 'x'}}
33 assert obj == parse(unparse(obj))
34 assert unparse(obj) == unparse(parse(unparse(obj)))
35
36
37 def test_attrib_and_cdata():
38 obj = {'a': {'@href': 'x', '#text': 'y'}}
39 assert obj == parse(unparse(obj))
40 assert unparse(obj) == unparse(parse(unparse(obj)))
41
42
43 def test_list():
44 obj = {'a': {'b': ['1', '2', '3']}}
45 assert obj == parse(unparse(obj))
46 assert unparse(obj) == unparse(parse(unparse(obj)))
47
48
49 def test_list_expand_iter():
50 obj = {'a': {'b': [['1', '2'], ['3',]]}}
51 #assert obj == parse(unparse(obj, expand_iter="item")))
52 exp_xml = dedent('''\
53 <?xml version="1.0" encoding="utf-8"?>
54 <a><b><item>1</item><item>2</item></b><b><item>3</item></b></a>''')
55 assert exp_xml == unparse(obj, expand_iter="item")
56
57
58 def test_generator():
59 obj = {'a': {'b': ['1', '2', '3']}}
60
61 def lazy_obj():
62 return {'a': {'b': (i for i in ('1', '2', '3'))}}
63 assert obj == parse(unparse(lazy_obj()))
64 assert unparse(lazy_obj()) == unparse(parse(unparse(lazy_obj())))
65
66
67 def test_no_root():
68 with pytest.raises(ValueError):
69 unparse({})
70
71
72 def test_multiple_roots():
73 with pytest.raises(ValueError):
74 unparse({'a': '1', 'b': '2'})
75 with pytest.raises(ValueError):
76 unparse({'a': ['1', '2', '3']})
77
78
79 def test_no_root_nofulldoc():
80 assert unparse({}, full_document=False) == ''
81
82
83 def test_multiple_roots_nofulldoc():
84 obj = {"a": 1, "b": 2}
85 xml = unparse(obj, full_document=False)
86 assert xml == '<a>1</a><b>2</b>'
87 obj = {'a': [1, 2]}
88 xml = unparse(obj, full_document=False)
89 assert xml == '<a>1</a><a>2</a>'
90
91
92 def test_nested():
93 obj = {'a': {'b': '1', 'c': '2'}}
94 assert obj == parse(unparse(obj))
95 assert unparse(obj) == unparse(parse(unparse(obj)))
96 obj = {'a': {'b': {'c': {'@a': 'x', '#text': 'y'}}}}
97 assert obj == parse(unparse(obj))
98 assert unparse(obj) == unparse(parse(unparse(obj)))
99
100
101 def test_semistructured():
102 xml = '<a>abc<d/>efg</a>'
103 assert _strip(unparse(parse(xml))) == '<a><d></d>abcefg</a>'
104
105
106 def test_preprocessor():
107 obj = {"a": {"b:int": [1, 2], "b": "c"}}
108
109 def p(key, value):
110 try:
111 key, _ = key.split(':')
112 except ValueError:
113 pass
114 return key, value
115
116 assert _strip(unparse(obj, preprocessor=p)) == '<a><b>1</b><b>2</b><b>c</b></a>'
117
118
119 def test_preprocessor_skipkey():
120 obj = {'a': {'b': 1, 'c': 2}}
121
122 def p(key, value):
123 if key == 'b':
124 return None
125 return key, value
126
127 assert _strip(unparse(obj, preprocessor=p)) == '<a><c>2</c></a>'
128
129
130 def test_attr_order_roundtrip():
131 xml = '<root a="1" b="2" c="3"></root>'
132 assert xml == _strip(unparse(parse(xml)))
133
134
135 def test_pretty_print():
136 obj = {
137 "a": {
138 "b": [{"c": [1, 2]}, 3],
139 "x": "y",
140 }
141 }
142 newl = '\n'
143 indent = '....'
144 xml = dedent('''\
145 <?xml version="1.0" encoding="utf-8"?>
146 <a>
147 ....<b>
148 ........<c>1</c>
149 ........<c>2</c>
150 ....</b>
151 ....<b>3</b>
152 ....<x>y</x>
153 </a>''')
154 assert xml == unparse(obj, pretty=True, newl=newl, indent=indent)
155
156
157 def test_unparse_with_element_comment():
158 obj = {"a": {"#comment": "note", "b": "1"}}
159 xml = _strip(unparse(obj, full_document=True))
160 assert xml == "<a><!--note--><b>1</b></a>"
161
162
163 def test_unparse_with_multiple_element_comments():
164 obj = {"a": {"#comment": ["n1", "n2"], "b": "1"}}
165 xml = _strip(unparse(obj, full_document=True))
166 assert xml == "<a><!--n1--><!--n2--><b>1</b></a>"
167
168
169 def test_unparse_with_top_level_comment():
170 obj = {"#comment": "top", "a": "1"}
171 xml = _strip(unparse(obj, full_document=True))
172 assert xml == "<!--top--><a>1</a>"
173
174
175 def test_unparse_with_multiple_top_level_comments():
176 obj = {"#comment": ["t1", "t2"], "a": "1"}
177 xml = _strip(unparse(obj, full_document=True))
178 assert xml == "<!--t1--><!--t2--><a>1</a>"
179
180
181 def test_unparse_rejects_comment_with_double_hyphen():
182 obj = {"#comment": "bad--comment", "a": "1"}
183 with pytest.raises(ValueError, match="cannot contain '--'"):
184 unparse(obj, full_document=True)
185
186
187 def test_unparse_rejects_comment_ending_with_hyphen():
188 obj = {"#comment": "trailing-", "a": "1"}
189 with pytest.raises(ValueError, match="cannot end with '-'"):
190 unparse(obj, full_document=True)
191
192
193 def test_pretty_print_with_int_indent():
194 obj = {
195 "a": {
196 "b": [{"c": [1, 2]}, 3],
197 "x": "y",
198 }
199 }
200 newl = '\n'
201 indent = 2
202 xml = dedent('''\
203 <?xml version="1.0" encoding="utf-8"?>
204 <a>
205 <b>
206 <c>1</c>
207 <c>2</c>
208 </b>
209 <b>3</b>
210 <x>y</x>
211 </a>''')
212 assert xml == unparse(obj, pretty=True, newl=newl, indent=indent)
213
214
215 def test_comment_roundtrip_limited():
216 # Input with top-level comments and an element-level comment
217 xml = """
218 <!--top1--><a><b>1</b><!--e1--></a><!--top2-->
219 """
220 # Parse with comment processing enabled
221 parsed1 = parse(xml, process_comments=True)
222 # Unparse and parse again (roundtrip)
223 xml2 = unparse(parsed1)
224 parsed2 = parse(xml2, process_comments=True)
225
226 # Content preserved
227 assert 'a' in parsed2
228 assert parsed2['a']['b'] == '1'
229
230 # Element-level comment preserved under '#comment'
231 assert parsed2['a']['#comment'] == 'e1'
232
233 # Top-level comments preserved as a list (order not guaranteed)
234 top = parsed2.get('#comment')
235 assert top is not None
236 top_list = top if isinstance(top, list) else [top]
237 assert set(top_list) == {'top1', 'top2'}
238
239
240 def test_encoding():
241 value = chr(39321)
242 obj = {'a': value}
243 utf8doc = unparse(obj, encoding='utf-8')
244 latin1doc = unparse(obj, encoding='iso-8859-1')
245 assert parse(utf8doc) == parse(latin1doc)
246 assert parse(utf8doc) == obj
247
248
249 def test_fulldoc():
250 xml_declaration_re = re.compile(
251 '^' + re.escape('<?xml version="1.0" encoding="utf-8"?>'))
252 assert xml_declaration_re.match(unparse({'a': 1}))
253 assert not xml_declaration_re.match(unparse({'a': 1}, full_document=False))
254
255
256 def test_non_string_value():
257 obj = {'a': 1}
258 assert '<a>1</a>' == _strip(unparse(obj))
259
260
261 def test_non_string_attr():
262 obj = {'a': {'@attr': 1}}
263 assert '<a attr="1"></a>' == _strip(unparse(obj))
264
265
266 def test_short_empty_elements():
267 obj = {'a': None}
268 assert '<a/>' == _strip(unparse(obj, short_empty_elements=True))
269
270
271 def test_namespace_support():
272 obj = {
273 "http://defaultns.com/:root": {
274 "@xmlns": {
275 "": "http://defaultns.com/",
276 "a": "http://a.com/",
277 "b": "http://b.com/",
278 },
279 "http://defaultns.com/:x": {
280 "@http://a.com/:attr": "val",
281 "#text": "1",
282 },
283 "http://a.com/:y": "2",
284 "http://b.com/:z": "3",
285 },
286 }
287 ns = {
288 'http://defaultns.com/': '',
289 'http://a.com/': 'a',
290 'http://b.com/': 'b',
291 }
292
293 expected_xml = '''<?xml version="1.0" encoding="utf-8"?>
294 <root xmlns="http://defaultns.com/" xmlns:a="http://a.com/" \
295 xmlns:b="http://b.com/"><x a:attr="val">1</x><a:y>2</a:y><b:z>3</b:z></root>'''
296 xml = unparse(obj, namespaces=ns)
297
298 assert xml == expected_xml
299
300
301 def test_boolean_unparse():
302 expected_xml = '<?xml version="1.0" encoding="utf-8"?>\n<x>true</x>'
303 xml = unparse(dict(x=True))
304 assert xml == expected_xml
305
306 expected_xml = '<?xml version="1.0" encoding="utf-8"?>\n<x>false</x>'
307 xml = unparse(dict(x=False))
308 assert xml == expected_xml
309
310
311 def test_rejects_tag_name_with_angle_brackets():
312 # Minimal guard: disallow '<' or '>' to prevent breaking tag context
313 with pytest.raises(ValueError):
314 unparse({"m><tag>content</tag": "unsafe"}, full_document=False)
315
316
317 def test_rejects_attribute_name_with_angle_brackets():
318 # Now we expect bad attribute names to be rejected
319 with pytest.raises(ValueError):
320 unparse(
321 {"a": {"@m><tag>content</tag": "unsafe", "#text": "x"}},
322 full_document=False,
323 )
324
325
326 def test_rejects_malicious_xmlns_prefix():
327 # xmlns prefixes go under @xmlns mapping; reject angle brackets in prefix
328 with pytest.raises(ValueError):
329 unparse(
330 {
331 "a": {
332 "@xmlns": {"m><bad": "http://example.com/"},
333 "#text": "x",
334 }
335 },
336 full_document=False,
337 )
338
339
340 def test_attribute_values_with_angle_brackets_are_escaped():
341 # Attribute values should be escaped by XMLGenerator
342 xml = unparse({"a": {"@attr": "1<middle>2", "#text": "x"}}, full_document=False)
343 # The generated XML should contain escaped '<' and '>' within the attribute value
344 assert 'attr="1&lt;middle&gt;2"' in xml
345
346
347 def test_rejects_tag_name_starting_with_question():
348 with pytest.raises(ValueError):
349 unparse({"?pi": "data"}, full_document=False)
350
351
352 def test_rejects_tag_name_starting_with_bang():
353 with pytest.raises(ValueError):
354 unparse({"!decl": "data"}, full_document=False)
355
356
357 def test_rejects_attribute_name_starting_with_question():
358 with pytest.raises(ValueError):
359 unparse({"a": {"@?weird": "x"}}, full_document=False)
360
361
362 def test_rejects_attribute_name_starting_with_bang():
363 with pytest.raises(ValueError):
364 unparse({"a": {"@!weird": "x"}}, full_document=False)
365
366
367 def test_rejects_xmlns_prefix_starting_with_question_or_bang():
368 with pytest.raises(ValueError):
369 unparse({"a": {"@xmlns": {"?p": "http://e/"}}}, full_document=False)
370 with pytest.raises(ValueError):
371 unparse({"a": {"@xmlns": {"!p": "http://e/"}}}, full_document=False)
372
373
374 def test_rejects_non_string_names():
375 class Weird:
376 def __str__(self):
377 return "bad>name"
378
379 # Non-string element key
380 with pytest.raises(ValueError):
381 unparse({Weird(): "x"}, full_document=False)
382 # Non-string attribute key
383 with pytest.raises(ValueError):
384 unparse({"a": {Weird(): "x"}}, full_document=False)
385
386
387 def test_rejects_tag_name_with_slash():
388 with pytest.raises(ValueError):
389 unparse({"bad/name": "x"}, full_document=False)
390
391
392 def test_rejects_tag_name_with_whitespace():
393 for name in ["bad name", "bad\tname", "bad\nname"]:
394 with pytest.raises(ValueError):
395 unparse({name: "x"}, full_document=False)
396
397
398 def test_rejects_attribute_name_with_slash():
399 with pytest.raises(ValueError):
400 unparse({"a": {"@bad/name": "x"}}, full_document=False)
401
402
403 def test_rejects_attribute_name_with_whitespace():
404 for name in ["@bad name", "@bad\tname", "@bad\nname"]:
405 with pytest.raises(ValueError):
406 unparse({"a": {name: "x"}}, full_document=False)
407
408
409 def test_rejects_xmlns_prefix_with_slash_or_whitespace():
410 # Slash
411 with pytest.raises(ValueError):
412 unparse({"a": {"@xmlns": {"bad/prefix": "http://e/"}}}, full_document=False)
413 # Whitespace
414 with pytest.raises(ValueError):
415 unparse({"a": {"@xmlns": {"bad prefix": "http://e/"}}}, full_document=False)
416
417
418 def test_rejects_names_with_quotes_and_equals():
419 # Element names
420 for name in ['a"b', "a'b", "a=b"]:
421 with pytest.raises(ValueError):
422 unparse({name: "x"}, full_document=False)
423 # Attribute names
424 for name in ['@a"b', "@a'b", "@a=b"]:
425 with pytest.raises(ValueError):
426 unparse({"a": {name: "x"}}, full_document=False)
427 # xmlns prefixes
428 for prefix in ['a"b', "a'b", "a=b"]:
429 with pytest.raises(ValueError):
430 unparse({"a": {"@xmlns": {prefix: "http://e/"}}}, full_document=False)
431
432
433 def test_pretty_print_and_short_empty_elements_consistency():
434 """Test that pretty and compact modes produce equivalent results when stripped.
435
436 This test covers issue #352: Edge case with pretty_print and short_empty_elements.
437 When short_empty_elements=True, empty elements should be written as <tag/>
438 regardless of whether pretty printing is enabled.
439 """
440 # Test case from issue #352: empty list child
441 input_dict = {"Foos": {"Foo": []}}
442
443 compact = unparse(
444 input_dict, pretty=False, short_empty_elements=True, full_document=False
445 )
446 pretty = unparse(
447 input_dict, pretty=True, short_empty_elements=True, full_document=False
448 )
449 pretty_compacted = pretty.replace("\n", "").replace("\t", "")
450
451 # They should be equal when pretty formatting is stripped
452 assert pretty_compacted == compact
453 assert compact == "<Foos/>"
454 assert pretty_compacted == "<Foos/>"
455
456
457 def test_empty_list_filtering():
458 """Test that empty lists are filtered out and don't create empty child elements."""
459 # Test various cases with empty lists
460 test_cases = [
461 # Case 1: Single empty list child
462 ({"Foos": {"Foo": []}}, "<Foos/>"),
463 # Case 2: Multiple empty list children
464 ({"Foos": {"Foo": [], "Bar": []}}, "<Foos/>"),
465 # Case 3: Mixed empty and non-empty children
466 ({"Foos": {"Foo": [], "Bar": "value"}}, "<Foos><Bar>value</Bar></Foos>"),
467 # Case 4: Nested empty lists
468 ({"Foos": {"Foo": {"Bar": []}}}, "<Foos><Foo/></Foos>"),
469 # Case 5: Empty list with attributes
470 ({"Foos": {"@attr": "value", "Foo": []}}, '<Foos attr="value"/>'),
471 ]
472
473 for input_dict, expected_compact in test_cases:
474 # Test compact mode
475 compact = unparse(
476 input_dict,
477 pretty=False,
478 short_empty_elements=True,
479 full_document=False,
480 )
481 assert compact == expected_compact
482
483 # Test pretty mode
484 pretty = unparse(
485 input_dict,
486 pretty=True,
487 short_empty_elements=True,
488 full_document=False,
489 )
490 pretty_compacted = pretty.replace("\n", "").replace("\t", "")
491 assert pretty_compacted == expected_compact
492
493
494 def test_empty_list_filtering_with_short_empty_elements_false():
495 """Test that empty lists are still filtered when short_empty_elements=False."""
496 input_dict = {"Foos": {"Foo": []}}
497
498 # With short_empty_elements=False, empty elements should be <tag></tag>
499 compact = unparse(
500 input_dict, pretty=False, short_empty_elements=False, full_document=False
501 )
502 pretty = unparse(
503 input_dict, pretty=True, short_empty_elements=False, full_document=False
504 )
505 pretty_compacted = pretty.replace("\n", "").replace("\t", "")
506
507 # They should be equal when pretty formatting is stripped
508 assert pretty_compacted == compact
509 assert compact == "<Foos></Foos>"
510 assert pretty_compacted == "<Foos></Foos>"
511
512
513 def test_non_empty_lists_are_not_filtered():
514 """Test that non-empty lists are not filtered out."""
515 # Test with non-empty lists
516 input_dict = {"Foos": {"Foo": ["item1", "item2"]}}
517
518 compact = unparse(
519 input_dict, pretty=False, short_empty_elements=True, full_document=False
520 )
521 pretty = unparse(
522 input_dict, pretty=True, short_empty_elements=True, full_document=False
523 )
524 pretty_compacted = pretty.replace("\n", "").replace("\t", "")
525
526 # The lists should be processed normally
527 assert pretty_compacted == compact
528 assert compact == "<Foos><Foo>item1</Foo><Foo>item2</Foo></Foos>"
529 assert (
530 pretty_compacted == "<Foos><Foo>item1</Foo><Foo>item2</Foo></Foos>"
531 )
532
533
534 def test_empty_dict_vs_empty_list_behavior():
535 """Test the difference between empty dicts and empty lists."""
536 # Empty dict should create a child element
537 input_dict_dict = {"Foos": {"Foo": {}}}
538 compact_dict = unparse(
539 input_dict_dict,
540 pretty=False,
541 short_empty_elements=True,
542 full_document=False,
543 )
544 assert compact_dict == "<Foos><Foo/></Foos>"
545
546 # Empty list should be filtered out
547 input_dict_list = {"Foos": {"Foo": []}}
548 compact_list = unparse(
549 input_dict_list,
550 pretty=False,
551 short_empty_elements=True,
552 full_document=False,
553 )
554 assert compact_list == "<Foos/>"
555
556 # They should be different
557 assert compact_dict != compact_list
558
559
560 def test_non_string_text_with_attributes():
561 """Test that non-string #text values work when tag has attributes.
562
563 This test covers GitHub issue #366: Tag value (#text) must be a string
564 when tag has additional parameters - unparse.
565
566 Also tests that plain values and explicit #text values are treated
567 consistently (both go through the same conversion logic).
568 """
569 # Test cases for explicit #text values with attributes
570 assert unparse({"a": {"@param": "test", "#text": 1}}, full_document=False) == '<a param="test">1</a>'
571
572 assert unparse({"a": {"@param": 42, "#text": 3.14}}, full_document=False) == '<a param="42">3.14</a>'
573
574 assert unparse({"a": {"@param": "flag", "#text": True}}, full_document=False) == '<a param="flag">true</a>'
575
576 assert unparse({"a": {"@param": "test", "#text": None}}, full_document=False) == '<a param="test"></a>'
577
578 assert unparse({"a": {"@param": "test", "#text": "string"}}, full_document=False) == '<a param="test">string</a>'
579
580 assert unparse({"a": {"@attr1": "value1", "@attr2": 2, "#text": 100}}, full_document=False) == '<a attr1="value1" attr2="2">100</a>'
581
582 # Test cases for plain values (should be treated the same as #text)
583 assert unparse({"a": 1}, full_document=False) == '<a>1</a>'
584 assert unparse({"a": 3.14}, full_document=False) == '<a>3.14</a>'
585 assert unparse({"a": True}, full_document=False) == '<a>true</a>'
586 assert unparse({"a": "hello"}, full_document=False) == '<a>hello</a>'
587 assert unparse({"a": None}, full_document=False) == '<a></a>'
588
589 # Consistency tests: plain values should match explicit #text values
590 assert unparse({"a": 42}, full_document=False) == unparse({"a": {"#text": 42}}, full_document=False)
591
592 assert unparse({"a": 3.14}, full_document=False) == unparse({"a": {"#text": 3.14}}, full_document=False)
593
594 assert unparse({"a": True}, full_document=False) == unparse({"a": {"#text": True}}, full_document=False)
595
596 assert unparse({"a": "hello"}, full_document=False) == unparse({"a": {"#text": "hello"}}, full_document=False)
597 assert unparse({"a": None}, full_document=False) == unparse({"a": {"#text": None}}, full_document=False)
598
599
600 def test_none_text_with_short_empty_elements_and_attributes():
601 obj = {"x": {"#text": None, "@pro": None}, "y": None}
602 assert unparse(obj, short_empty_elements=True, full_document=False) == '<x pro=""/><y/>'
603
604
605 def test_none_attribute_serializes_as_empty_string():
606 assert unparse({"x": {"@pro": None}}, full_document=False) == '<x pro=""></x>'