Coverage for gws-app/gws/lib/xmlx/_test/parser_test.py: 100%
48 statements
« prev ^ index » next coverage.py v7.11.0, created at 2025-10-16 23:09 +0200
« prev ^ index » next coverage.py v7.11.0, created at 2025-10-16 23:09 +0200
1"""Tests for the parser module"""
3import gws
4import gws.test.util as u
6import gws.lib.xmlx as xmlx
9def test_from_path(tmpdir):
10 s = '<foo><bar/></foo>'
11 tf = tmpdir.join('test.xml')
12 tf.write(s)
13 doc = xmlx.parser.from_path(str(tf))
14 assert _noempty(doc.to_dict()) == {'children': [{'tag': 'bar'}], 'tag': 'foo'}
17def test_from_string():
18 s = '<foo><bar/></foo>'
19 doc = xmlx.parser.from_string(s)
20 assert _noempty(doc.to_dict()) == {'children': [{'tag': 'bar'}], 'tag': 'foo'}
23def test_from_string_compact():
24 s = '<foo> x <bar> abc </bar> y </foo>'
25 doc = xmlx.parser.from_string(s, gws.XmlOptions(compactWhitespace=True))
26 assert _noempty(doc.to_dict()) == {'children': [{'tag': 'bar', 'text': 'abc', 'tail': 'y'}], 'tag': 'foo', 'text': 'x'}
29def test_from_string_namespaces():
30 s = '<ns:a xmlns:ns="http://ns1"><b xmlns="http://ns2" ns:x="1"><c/></b></ns:a>'
31 doc = xmlx.parser.from_string(s, gws.XmlOptions(removeNamespaces=False))
32 assert _noempty(doc.to_dict()) == {'tag': '{http://ns1}a', 'children': [{'tag': '{http://ns2}b', 'attrib': {'{http://ns1}x': '1'}, 'children': [{'tag': '{http://ns2}c'}]}]}
33 doc = xmlx.parser.from_string(s, gws.XmlOptions(removeNamespaces=True))
34 assert _noempty(doc.to_dict()) == {'tag': 'a', 'children': [{'tag': 'b', 'attrib': {'x': '1'}, 'children': [{'tag': 'c'}]}]}
37def test_decode_str_valid_encoding():
38 s = '<?xml version="1.0" encoding="UTF-8"?><foo>äß</foo>'
39 doc = xmlx.parser.from_string(s)
40 assert _noempty(doc.to_dict()) == {'tag': 'foo', 'text': 'äß'}
43def test_decode_str_invalid_encoding():
44 s = '<?xml version="1.0" encoding="iso-8859-1"?><foo>äß</foo>'
45 doc = xmlx.parser.from_string(s)
46 assert _noempty(doc.to_dict()) == {'tag': 'foo', 'text': 'äß'}
49def test_decode_bytes_valid_encoding():
50 s = b'<?xml version="1.0" encoding="UTF-8"?><foo>\xc3\xa4\xc3\x9f</foo>'
51 doc = xmlx.parser.from_string(s)
52 assert _noempty(doc.to_dict()) == {'tag': 'foo', 'text': 'äß'}
53 s = b'<?xml version="1.0" encoding="iso-8859-1"?><foo>\xe4\xdf</foo>'
54 doc = xmlx.parser.from_string(s)
55 assert _noempty(doc.to_dict()) == {'tag': 'foo', 'text': 'äß'}
58def test_decode_bytes_invalid_encoding():
59 s = b'<?xml version="1.0" encoding="UTF-8"?><foo>\xe4\xdf</foo>'
60 doc = xmlx.parser.from_string(s)
61 assert _noempty(doc.to_dict()) == {'tag': 'foo', 'text': 'äß'}
64def _noempty(d):
65 if isinstance(d, dict):
66 return {k: _noempty(v) for k, v in d.items() if v not in (None, '', [], {})}
67 if isinstance(d, list):
68 return [_noempty(v) for v in d if v not in (None, '', [], {})]
69 return d