File: test_untangle.py

package info (click to toggle)
python-untangle 1.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 236 kB
  • sloc: python: 482; makefile: 149; xml: 74; sh: 9
file content (405 lines) | stat: -rwxr-xr-x 13,636 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import unittest
import untangle
import xml

import defusedxml


class FromStringTestCase(unittest.TestCase):
    """Basic parsing tests with input as string"""

    def test_basic(self):
        o = untangle.parse("<a><b/><c/></a>")
        self.assertTrue(o is not None)
        self.assertTrue(o.a is not None)
        self.assertTrue(o.a.b is not None)
        self.assertTrue(o.a.c is not None)
        self.assertTrue("a" in o)
        self.assertTrue("b" in o.a)
        self.assertTrue("c" in o.a)
        self.assertTrue("d" not in o.a)

    def test_basic_with_decl(self):
        o = untangle.parse("<?xml version='1.0'?><a><b/><c/></a>")
        self.assertTrue(o is not None)
        self.assertTrue(o.a is not None)
        self.assertTrue(o.a.b is not None)
        self.assertTrue(o.a.c is not None)
        self.assertTrue("a" in o)
        self.assertTrue("b" in o.a)
        self.assertTrue("c" in o.a)
        self.assertTrue("d" not in o.a)

    def test_truthiness(self):
        o = untangle.parse("<a><b/><c/></a>")
        self.assertTrue(o)
        self.assertTrue(o.a)
        self.assertTrue(o.a.b)
        self.assertTrue(o.a.c)

    def test_with_attributes(self):
        o = untangle.parse(
            """
                    <Soup name="Tomato soup" version="1">
                     <Ingredients>
                        <Water qty="1l" />
                        <Tomatoes qty="1kg" />
                        <Salt qty="1tsp" />
                     </Ingredients>
                     <Instructions>
                        <boil-water/>
                        <add-ingredients/>
                        <done/>
                     </Instructions>
                    </Soup>
                     """
        )
        self.assertEqual("Tomato soup", o.Soup["name"])
        self.assertEqual(1, int(o.Soup["version"]))
        self.assertEqual("1l", o.Soup.Ingredients.Water["qty"])
        self.assertTrue(o.Soup.Instructions.add_ingredients is not None)

    def test_grouping(self):
        o = untangle.parse(
            """
                    <root>
                     <child name="child1">
                        <subchild name="sub1"/>
                     </child>
                     <child name="child2"/>
                     <child name="child3">
                        <subchild name="sub2"/>
                        <subchild name="sub3"/>
                     </child>
                    </root>
                     """
        )
        self.assertTrue(o.root)

        children = o.root.child
        self.assertEqual(3, len(children))
        self.assertEqual("child1", children[0]["name"])
        self.assertEqual("sub1", children[0].subchild["name"])
        self.assertEqual(2, len(children[2].subchild))
        self.assertEqual("sub2", children[2].subchild[0]["name"])

    def test_single_root(self):
        self.assertTrue(untangle.parse("<single_root_node/>"))

    def test_attribute_protocol(self):
        o = untangle.parse(
            """
                    <root>
                     <child name="child1">
                        <subchild name="sub1"/>
                     </child>
                     <child name="child2"/>
                     <child name="child3">
                        <subchild name="sub2"/>
                        <subchild name="sub3"/>
                     </child>
                    </root>
                     """
        )
        try:
            self.assertEqual(None, o.root.child.inexistent)
            self.fail("Was able to access inexistent child as None")
        except AttributeError:
            pass  # this is the expected error
        except IndexError:
            self.fail("Caught IndexError quen expecting AttributeError")

        self.assertTrue(hasattr(o.root, "child"))
        self.assertFalse(hasattr(o.root, "inexistent"))

        self.assertEqual("child1", getattr(o.root, "child")[0]["name"])

    def test_python_keyword(self):
        o = untangle.parse("<class><return/><pass/><None/></class>")
        self.assertTrue(o is not None)
        self.assertTrue(o.class_ is not None)
        self.assertTrue(o.class_.return_ is not None)
        self.assertTrue(o.class_.pass_ is not None)
        self.assertTrue(o.class_.None_ is not None)


class InvalidTestCase(unittest.TestCase):
    """Test corner cases"""

    def test_invalid_xml(self):
        self.assertRaises(xml.sax.SAXParseException, untangle.parse, "<unclosed>")

    def test_empty_xml(self):
        self.assertRaises(ValueError, untangle.parse, "")

    def test_none_xml(self):
        self.assertRaises(ValueError, untangle.parse, None)


class PomXmlTestCase(unittest.TestCase):
    """Tests parsing a Maven pom.xml"""

    def setUp(self):
        self.o = untangle.parse("tests/res/pom.xml")

    def test_parent(self):
        project = self.o.project
        self.assertTrue(project)

        parent = project.parent
        self.assertTrue(parent)
        self.assertEqual("com.atlassian.confluence.plugin.base", parent.groupId)
        self.assertEqual("confluence-plugin-base", parent.artifactId)
        self.assertEqual("17", parent.version)

        self.assertEqual("4.0.0", project.modelVersion)
        self.assertEqual("com.this.that.groupId", project.groupId)

        self.assertEqual("", project.name)
        self.assertEqual(
            "${pom.groupId}.${pom.artifactId}", project.properties.atlassian_plugin_key
        )
        self.assertEqual("1.4.1", project.properties.atlassian_product_test_lib_version)
        self.assertEqual("2.9", project.properties.atlassian_product_data_version)

    def test_lengths(self):
        self.assertEqual(1, len(self.o))
        self.assertEqual(8, len(self.o.project))
        self.assertEqual(3, len(self.o.project.parent))
        self.assertEqual(4, len(self.o.project.properties))


class NamespaceTestCase(unittest.TestCase):
    """Tests for XMLs with namespaces"""

    def setUp(self):
        self.o = untangle.parse("tests/res/some.xslt")

    def test_namespace(self):
        self.assertTrue(self.o)

        stylesheet = self.o.xsl_stylesheet
        self.assertTrue(stylesheet)
        self.assertEqual("1.0", stylesheet["version"])

        template = stylesheet.xsl_template[0]
        self.assertTrue(template)
        self.assertEqual("math", template["match"])
        self.assertEqual("compact", template.table["class"])
        self.assertEqual("compact vam", template.table.tr.xsl_for_each.td["class"])
        self.assertEqual(
            untangle.Element("", ""),
            template.table.tr.xsl_for_each.td.xsl_apply_templates,
        )

        last_template = stylesheet.xsl_template[-1]
        self.assertTrue(last_template)
        self.assertEqual("m_var", last_template["match"])
        self.assertEqual("compact tac formula italic", last_template.p["class"])
        self.assertEqual(
            untangle.Element("xsl_apply_templates", ""),
            last_template.p.xsl_apply_templates,
        )


class IterationTestCase(unittest.TestCase):
    """Tests various cases of iteration over child nodes."""

    def test_multiple_children(self):
        """Regular case of iteration."""
        o = untangle.parse("<a><b/><b/></a>")
        cnt = 0
        for i in o.a.b:
            cnt += 1
        self.assertEqual(2, cnt)

    def test_single_child(self):
        """Special case when there is only a single child element.
        Does not work without an __iter__ implemented.
        """
        o = untangle.parse("<a><b/></a>")
        cnt = 0
        for i in o.a.b:
            cnt += 1
        self.assertEqual(1, cnt)


class TwimlTestCase(unittest.TestCase):
    """Github Issue #5: can't dir the parsed object"""

    def test_twiml_dir(self):
        xml = """<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Gather action="http://example.com/calls/1/twiml?event=start"
  numDigits="1" timeout="0">
    <Play>http://example.com/barcall_message_url.wav</Play>
  </Gather>
  <Redirect>http://example.com/calls/1/twiml?event=start</Redirect>
</Response>
        """
        o = untangle.parse(xml)
        self.assertEqual(["Response"], dir(o))
        resp = o.Response
        self.assertEqual(["Gather", "Redirect"], dir(resp))
        gather = resp.Gather
        redir = resp.Redirect
        self.assertEqual(["Play"], dir(gather))
        self.assertEqual([], dir(redir))
        self.assertEqual(
            "http://example.com/calls/1/twiml?event=start", o.Response.Redirect.cdata
        )


class UnicodeTestCase(unittest.TestCase):
    """Github issue #8: UnicodeEncodeError"""

    def test_unicode_file(self):
        o = untangle.parse("tests/res/unicode.xml")
        self.assertEqual("ðÒÉ×ÅÔ ÍÉÒ", o.page.menu.name)

    def test_lengths(self):
        o = untangle.parse("tests/res/unicode.xml")
        self.assertEqual(1, len(o))
        self.assertEqual(1, len(o.page))
        self.assertEqual(2, len(o.page.menu))
        self.assertEqual(2, len(o.page.menu.items))
        self.assertEqual(2, len(o.page.menu.items.item))
        self.assertEqual(0, len(o.page.menu.items.item[0].name))
        self.assertEqual(0, len(o.page.menu.items.item[1].name))

    def test_unicode_string(self):
        o = untangle.parse("<Element>valüé ◔‿◔</Element>")
        self.assertEqual("valüé ◔‿◔", o.Element.cdata)

    def test_unicode_element(self):
        o = untangle.parse("<Francés></Francés>")
        self.assertTrue(o is not None)
        self.assertTrue(o.Francés is not None)


class FileObjects(unittest.TestCase):
    """Test reading from file-like objects"""

    def test_file_object(self):
        with open("tests/res/pom.xml") as pom_file:
            o = untangle.parse(pom_file)
            project = o.project
            self.assertTrue(project)

            parent = project.parent
            self.assertTrue(parent)
            self.assertEqual("com.atlassian.confluence.plugin.base", parent.groupId)
            self.assertEqual("confluence-plugin-base", parent.artifactId)
            self.assertEqual("17", parent.version)


class Foo(object):
    """Used in UntangleInObjectsTestCase"""

    def __init__(self):
        self.doc = untangle.parse('<a><b x="1">foo</b></a>')


class UntangleInObjectsTestCase(unittest.TestCase):
    """tests usage of untangle in classes"""

    def test_object(self):
        foo = Foo()
        self.assertEqual("1", foo.doc.a.b["x"])
        self.assertEqual("foo", foo.doc.a.b.cdata)


class UrlStringTestCase(unittest.TestCase):
    """tests is_url() function"""

    def test_is_url(self):
        self.assertFalse(untangle.is_url("foo"))
        self.assertFalse(untangle.is_url("httpfoo"))
        self.assertFalse(untangle.is_url(7))
        self.assertTrue(untangle.is_url("http://foobar"))
        self.assertTrue(untangle.is_url("https://foobar"))


class TestSaxHandler(unittest.TestCase):
    """Tests the SAX ContentHandler"""

    def test_empty_handler(self):
        h = untangle.Handler()
        self.assertRaises(IndexError, h.endElement, "foo")
        self.assertRaises(IndexError, h.characters, "bar")

    def test_handler(self):
        h = untangle.Handler()
        h.startElement("foo", {})
        h.endElement("foo")
        self.assertEqual("foo", h.root.children[0]._name)

    def test_cdata(self):
        h = untangle.Handler()
        h.startElement("foo", {})
        h.characters("baz")
        self.assertEqual("baz", h.root.children[0].cdata)


class FigsTestCase(unittest.TestCase):
    def test_figs(self):
        doc = untangle.parse("tests/res/figs.xml")
        expected_pairs = [("key1", "value1"), ("key2", "value2"), ("key", "value")]
        pairs = []
        for group in doc.props.children:
            for prop in group.children:
                pairs.append((prop["key"], prop.cdata))
        assert expected_pairs == pairs


class ParserFeatureTestCase(unittest.TestCase):
    """Tests adding xml.sax parser features via parse()"""

    # External DTD that will never be loadable (invalid address)
    bad_dtd_xml = """<?xml version="1.0" standalone="no" ?>
        <!DOCTYPE FOO PUBLIC "foo" "http://256.0.0.1/foo.dtd">
        <foo bar="baz" />"""

    def test_valid_feature(self):
        # xml.sax.handler.feature_external_ges -> load external general (text)
        # entities, such as DTDs
        with self.assertRaises(defusedxml.common.ExternalReferenceForbidden):
            untangle.parse(self.bad_dtd_xml)

    def test_invalid_feature(self):
        with self.assertRaises(AttributeError):
            untangle.parse(self.bad_dtd_xml, invalid_feature=True)

    def test_invalid_external_dtd(self):
        with self.assertRaises(defusedxml.common.ExternalReferenceForbidden):
            untangle.parse(self.bad_dtd_xml)


class TestEquals(unittest.TestCase):
    def test_equals(self):
        a = untangle.Element("a", "1")
        b = untangle.Element("b", "1")
        self.assertTrue(a == b)

    def test_list_equals(self):
        a = untangle.Element("a", "1")
        b = untangle.Element("b", "1")
        listA = [a, b]
        c = untangle.Element("c", "1")
        self.assertTrue(c in listA)


class TestExternalEntityExpansion(unittest.TestCase):
    def test_xxe(self):
        # from https://pypi.org/project/defusedxml/#external-entity-expansion-remote
        with self.assertRaises(defusedxml.common.EntitiesForbidden):
            untangle.parse("tests/res/xxe.xml")


if __name__ == "__main__":
    unittest.main()

# vim: set expandtab ts=4 sw=4