File: test_incremental_tree.py

package info (click to toggle)
python-et-xmlfile 2.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 808 kB
  • sloc: python: 8,133; xml: 13; makefile: 7
file content (417 lines) | stat: -rw-r--r-- 16,068 bytes parent folder | download | duplicates (2)
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
406
407
408
409
410
411
412
413
414
415
416
417
import io
import operator
import unittest
import xml.etree.ElementTree as ET

from et_xmlfile import incremental_tree as inc_tree


def serialize(elem, to_string=True, encoding="unicode", **options):
    if encoding != "unicode":
        file = io.BytesIO()
    else:
        file = io.StringIO()
    tree = inc_tree.IncrementalTree(elem)
    tree.write(file, encoding=encoding, **options)
    if to_string:
        return file.getvalue()
    else:
        file.seek(0)
        return file


class BaseETTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls._orig_namespace_map = ET.register_namespace._namespace_map.copy()

    def tearDown(self):
        # Clear any namespaces registered during tests
        ET.register_namespace._namespace_map.clear()
        ET.register_namespace._namespace_map.update(self._orig_namespace_map)

    def assertEqualElements(self, alice, bob):
        self.assertEqual(len(list(alice)), len(list(bob)))
        for x, y in zip(alice, bob):
            self.assertEqualElements(x, y)


class ETModTests(BaseETTestCase):

    def test_namespaces_returns_only_used(self):
        "_namespaces only returns uris that were used in the docuemnt"
        elem = ET.Element("{namespace0}foo")
        out_nsmap = inc_tree._namespaces(
            elem,
        )
        self.assertEqual(
            out_nsmap,
            {"ns0": "namespace0"},
        )

    def test_namespaces_default_namespace_not_used(self):
        "_namespaces doesn't return default_namespace if not used"
        elem = ET.Element("{namespace1}foo")
        out_nsmap = inc_tree._namespaces(
            elem,
            default_namespace="other",
        )
        self.assertEqual(
            out_nsmap,
            {"ns1": "namespace1"},
        )

    def test_default_namespace_not_used(self):
        "Serializing will declare the default_namespace even if unused"
        elem = ET.Element("{namespace1}foo")
        self.assertEqual(
            serialize(elem, default_namespace="other"),
            '<ns1:foo xmlns="other" xmlns:ns1="namespace1" />'
        )

    def test_default_namespace_not_used_minimal(self):
        "Serializing will declare the default_namespace even if unused unless minimal ns declared"
        elem = ET.Element("{namespace1}foo")
        self.assertEqual(
            serialize(elem, default_namespace="other", minimal_ns_only=True),
            '<ns1:foo xmlns:ns1="namespace1" />'
        )

    def test_nsmap_not_used_minimal(self):
        "Serializing will declare the default_namespace even if unused unless minimal ns declared"
        elem = ET.Element("{namespace0}foo")
        self.assertEqual(
            serialize(elem, nsmap={"oth": "other"}, minimal_ns_only=True),
            '<ns0:foo xmlns:ns0="namespace0" />'
        )

    def test_minimal_ns_only_implies_root_ns_only(self):
        elem = ET.Element("{namespace1}foo")
        ET.SubElement(elem, "{namespace2}bar")
        self.assertEqual(
            serialize(
                elem,
                default_namespace="default",
                nsmap={"oth": "other"},
                minimal_ns_only=True,
            ),
            '<ns1:foo xmlns:ns1="namespace1" xmlns:ns2="namespace2"><ns2:bar /></ns1:foo>'
        )


class CommonFixesTests(BaseETTestCase):
    """A collection of tests added to PRs for cpython for bug fixes / enhancements.

    The bug fixes are:
    - conflicts of registered namespaces and default_namespace uri
    - incorrect handling of attributes with a URI that is the same as the
      default_uri (attributes in that namespace must have a prefix - unprefixed
      attrs are not in the default namespace)

    Feature:
    - Add local namespace map arg, `nsmap` to write()`
    """
    compat_serialize = False

    def serialize(self, elem, to_string=True, encoding="unicode", **options):
        if self.compat_serialize:
            options["root_ns_only"] = True

        return serialize(elem, to_string=to_string, encoding=encoding, **options)

    def test_tostring_nsmap(self):
        elem = ET.XML(
            '<body xmlns="http://effbot.org/ns" xmlns:foo="bar"><foo:tag/></body>'
        )
        if self.compat_serialize:
            expected = '<ns0:body xmlns:ns0="http://effbot.org/ns" xmlns:ns1="bar"><ns1:tag /></ns0:body>'
        else:
            expected = '<ns0:body xmlns:ns0="http://effbot.org/ns"><ns1:tag xmlns:ns1="bar" /></ns0:body>'
        self.assertEqual(self.serialize(elem, encoding="unicode"), expected)

        self.assertEqual(
            self.serialize(
                elem,
                encoding="unicode",
                nsmap={
                    "": "http://effbot.org/ns",
                    "foo": "bar",
                    "unused": "nothing",
                },
            ),
            '<body xmlns="http://effbot.org/ns" xmlns:foo="bar" xmlns:unused="nothing">'
            "<foo:tag /></body>",
        )

    def test_tostring_nsmap_default_namespace(self):
        elem = ET.XML('<body xmlns="http://effbot.org/ns"><tag/></body>')
        self.assertEqual(
            self.serialize(elem, encoding="unicode"),
            '<ns0:body xmlns:ns0="http://effbot.org/ns"><ns0:tag /></ns0:body>',
        )
        self.assertEqual(
            self.serialize(
                elem,
                encoding="unicode",
                nsmap={"": "http://effbot.org/ns"},
            ),
            '<body xmlns="http://effbot.org/ns"><tag /></body>',
        )

    def test_tostring_nsmap_default_namespace_none(self):
        elem = ET.XML('<body xmlns="http://effbot.org/ns"><tag/></body>')
        self.assertEqual(
            self.serialize(elem, encoding="unicode"),
            '<ns0:body xmlns:ns0="http://effbot.org/ns"><ns0:tag /></ns0:body>',
        )
        msg = '^Found None as default nsmap prefix in nsmap. Use "" as the default namespace prefix.$'

        with self.assertRaisesRegex(ValueError, msg):
            self.serialize(
                elem,
                encoding="unicode",
                nsmap={None: "http://effbot.org/ns"},
            )

    def test_tostring_nsmap_default_namespace_overrides(self):
        elem = ET.XML('<body xmlns="http://effbot.org/ns"><tag/></body>')
        self.assertEqual(
            self.serialize(
                elem,
                encoding="unicode",
                default_namespace="other",
                nsmap={"": "http://effbot.org/ns"},
            ),
            '<ns1:body xmlns="other" xmlns:ns1="http://effbot.org/ns">'
            "<ns1:tag />"
            "</ns1:body>",
        )
        self.assertEqual(
            self.serialize(
                elem,
                encoding="unicode",
                default_namespace="http://effbot.org/ns",
                nsmap={"": "other"},
            ),
            '<body xmlns="http://effbot.org/ns"><tag /></body>',
        )

    def test_tostring_nsmap_default_namespace_attr(self):
        reg_name = "gh57587"
        namespace = "ns_gh57587"
        elem = ET.XML(
            f'<body xmlns="{namespace}" xmlns:foo="{namespace}" foo:status="good">'
            "<tag/></body>"
        )
        self.assertEqual(
            self.serialize(elem, encoding="unicode"),
            f'<ns0:body xmlns:ns0="{namespace}" ns0:status="good"><ns0:tag /></ns0:body>',
        )
        ET.register_namespace(reg_name, namespace)
        self.assertEqual(
            self.serialize(
                elem,
                encoding="unicode",
                nsmap={
                    "": namespace,
                    "foo": namespace,
                },
            ),
            f'<body xmlns="{namespace}" xmlns:foo="{namespace}" foo:status="good">'
            "<tag /></body>",
        )
        # default attr gets name from global registered namespaces
        self.assertEqual(
            self.serialize(
                elem,
                encoding="unicode",
                nsmap={"": namespace},
            ),
            f'<body xmlns="{namespace}" xmlns:{reg_name}="{namespace}" {reg_name}:status="good">'
            "<tag /></body>",
        )

    def test_tostring_nsmap_default_namespace_original_no_namespace(self):
        elem = ET.XML("<body><tag/></body>")
        EXPECTED_MSG = "^cannot use non-qualified names with default_namespace option$"
        with self.assertRaisesRegex(ValueError, EXPECTED_MSG):
            self.serialize(elem, encoding="unicode", nsmap={"": "foobar"})

    def test_tostringlist_nsmap_default_namespace(self):
        elem = ET.XML('<body xmlns="http://effbot.org/ns"><tag/></body>')
        self.assertEqual(
            "".join(inc_tree.tostringlist(elem, encoding="unicode")),
            '<ns0:body xmlns:ns0="http://effbot.org/ns"><ns0:tag /></ns0:body>',
        )
        self.assertEqual(
            "".join(
                inc_tree.tostringlist(
                    elem,
                    encoding="unicode",
                    nsmap={"": "http://effbot.org/ns"},
                )
            ),
            '<body xmlns="http://effbot.org/ns"><tag /></body>',
        )

    def test_namespace_attribs(self):
        # Unprefixed attributes are unqualified even if a default
        # namespace is in effect. (This is a little unclear in some
        # versions of the XML TR but is clarified in errata and other
        # versions.) See bugs.python.org issue 17088.
        #
        # The reasoning behind this, alluded to in the spec, is that
        # attribute meanings already depend on the element they're
        # attached to; attributes have always lived in per-element
        # namespaces even before explicit XML namespaces were
        # introduced.  For that reason qualified attribute names are
        # only really needed when one XML module defines attributes
        # that can be placed on elements defined in a different module
        # (such as happens with XLINK or, for that matter, the XML
        # namespace spec itself).
        e = ET.XML(
            '<pf:elt xmlns:pf="space1" xmlns:pf2="space2" foo="value">'
            '<pf:foo foo="value2" pf2:foo="value3"/>'
            '<pf2:foo foo="value4" pf:foo="value5" pf2:foo="value6"/>'
            '<foo foo="value7" pf:foo="value8"/>'
            "</pf:elt>"
        )
        self.assertEqual(e.tag, "{space1}elt")
        self.assertEqual(e.get("foo"), "value")
        self.assertIsNone(e.get("{space1}foo"))
        self.assertIsNone(e.get("{space2}foo"))
        self.assertEqual(e[0].tag, "{space1}foo")
        self.assertEqual(e[0].attrib, {"foo": "value2", "{space2}foo": "value3"})
        self.assertEqual(e[1].tag, "{space2}foo")
        self.assertEqual(
            e[1].attrib,
            {"foo": "value4", "{space1}foo": "value5", "{space2}foo": "value6"},
        )
        self.assertEqual(e[2].tag, "foo")
        self.assertEqual(e[2].attrib, {"foo": "value7", "{space1}foo": "value8"})

        if self.compat_serialize:
            serialized1 = (
                '<ns0:elt xmlns:ns0="space1" xmlns:ns1="space2" foo="value">'
                '<ns0:foo foo="value2" ns1:foo="value3" />'
                '<ns1:foo foo="value4" ns0:foo="value5" ns1:foo="value6" />'
                '<foo foo="value7" ns0:foo="value8" />'
                "</ns0:elt>"
            )
        else:
            serialized1 = (
                '<ns0:elt xmlns:ns0="space1" foo="value">'
                '<ns0:foo xmlns:ns1="space2" foo="value2" ns1:foo="value3" />'
                '<ns1:foo xmlns:ns1="space2" foo="value4" ns0:foo="value5" ns1:foo="value6" />'
                '<foo foo="value7" ns0:foo="value8" />'
                "</ns0:elt>"
            )
        self.assertEqual(self.serialize(e), serialized1)
        self.assertEqualElements(e, ET.XML(serialized1))

        # Test writing with a default namespace.
        with self.assertRaisesRegex(
            ValueError, "cannot use non-qualified name.* with default_namespace option"
        ):
            self.serialize(e, default_namespace="space1")

        # Remove the unqualified element from the tree so we can test
        # further.
        del e[2]

        # Serialization can require a namespace prefix to be declared for
        # space1 even if no elements use that prefix, in order to
        # write an attribute name in that namespace.
        if self.compat_serialize:
            serialized2 = (
                '<ns1:elt xmlns="space2" xmlns:ns1="space1" xmlns:ns2="space2" foo="value">'
                '<ns1:foo foo="value2" ns2:foo="value3" />'
                '<foo foo="value4" ns1:foo="value5" ns2:foo="value6" />'
                "</ns1:elt>"
            )
        else:
            serialized2 = (
                '<ns1:elt xmlns="space2" xmlns:ns1="space1" foo="value">'
                '<ns1:foo xmlns:ns2="space2" foo="value2" ns2:foo="value3" />'
                '<foo xmlns:ns2="space2" foo="value4" ns1:foo="value5" ns2:foo="value6" />'
                "</ns1:elt>"
            )
        self.assertEqual(self.serialize(e, default_namespace="space2"), serialized2)
        self.assertEqualElements(e, ET.XML(serialized2))

        if self.compat_serialize:
            serialized3 = (
                '<elt xmlns="space1" xmlns:ns1="space2" xmlns:ns2="space1" foo="value">'
                '<foo foo="value2" ns1:foo="value3" />'
                '<ns1:foo foo="value4" ns2:foo="value5" ns1:foo="value6" />'
                "</elt>"
            )
        else:
            serialized3 = (
                '<elt xmlns="space1" foo="value">'
                '<foo xmlns:ns1="space2" foo="value2" ns1:foo="value3" />'
                '<ns1:foo xmlns:ns1="space2" xmlns:ns2="space1" foo="value4" ns2:foo="value5" ns1:foo="value6" />'
                "</elt>"
            )
        self.assertEqual(self.serialize(e, default_namespace="space1"), serialized3)
        self.assertEqualElements(e, ET.XML(serialized3))

    def test_pre_gh118416_register_default_namespace_behaviour(self):
        # All these examples worked prior to fixing bug gh118416
        ET.register_namespace("", "gh118416")

        # If the registered default prefix's URI is not used, don't raise an
        # error
        e = ET.Element("{other}elem")
        self.assertEqual(
            self.serialize(e),
            '<ns0:elem xmlns:ns0="other" />',
        )
        # no error even with unqualified tags
        e = ET.Element("elem")
        self.assertEqual(
            self.serialize(e),
            "<elem />",
        )

        # Uses registered default prefix, if used in tree
        e = ET.Element("{gh118416}elem")
        self.assertEqual(
            self.serialize(e),
            '<elem xmlns="gh118416" />',
        )

        # Use explicitly provided default_namespace if registered default
        # prefix is not used.
        e = ET.Element("{default}elem")
        ET.SubElement(e, "{other}otherEl")
        if self.compat_serialize:
            expected_xml = '<elem xmlns="default" xmlns:ns1="other"><ns1:otherEl /></elem>'
        else:
            expected_xml = '<elem xmlns="default"><ns1:otherEl xmlns:ns1="other" /></elem>'
        self.assertEqual(
            self.serialize(e, default_namespace="default"),
            expected_xml,
        )

    def test_gh118416_register_default_namespace(self):
        ET.register_namespace("", "gh118416")
        e = ET.Element("{gh118416}elem")
        ET.SubElement(e, "noPrefixElem")
        with self.assertRaises(ValueError) as cm:
            self.serialize(e)
        self.assertEqual(
            str(cm.exception),
            "cannot use non-qualified names with default_namespace option",
        )

        e = ET.Element("{gh118416}elem")
        # explicitly set default_namespace takes precedence
        self.assertEqual(
            self.serialize(e, default_namespace="otherdefault"),
            '<ns1:elem xmlns="otherdefault" xmlns:ns1="gh118416" />',
        )


class CommonFixesTestsCompat(CommonFixesTests):
    compat_serialize = True