File: test_yaml.py

package info (click to toggle)
python-asdf 2.7.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 3,248 kB
  • sloc: python: 13,104; makefile: 125
file content (312 lines) | stat: -rw-r--r-- 8,395 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
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-

import io
from collections import namedtuple, OrderedDict
from typing import NamedTuple

import numpy as np

import pytest

import yaml

import asdf
from asdf import tagged
from asdf import treeutil
from asdf import yamlutil
from asdf.compat.numpycompat import NUMPY_LT_1_14
from asdf.exceptions import AsdfWarning

from . import helpers


def test_ordered_dict(tmpdir):
    # Test that we can write out and read in ordered dicts.

    tree = {
        "ordered_dict": OrderedDict(
            [('first', 'foo'),
             ('second', 'bar'),
             ('third', 'baz')]),

        "unordered_dict": {
            'first': 'foo',
            'second': 'bar',
            'third': 'baz'
        }
    }

    def check_asdf(asdf):
        tree = asdf.tree

        assert isinstance(tree['ordered_dict'], OrderedDict)
        assert list(tree['ordered_dict'].keys()) == ['first', 'second', 'third']

        assert not isinstance(tree['unordered_dict'], OrderedDict)
        assert isinstance(tree['unordered_dict'], dict)

    def check_raw_yaml(content):
        assert b'OrderedDict' not in content

    helpers.assert_roundtrip_tree(tree, tmpdir, asdf_check_func=check_asdf,
                                  raw_yaml_check_func=check_raw_yaml)


def test_unicode_write(tmpdir):
    # We want to write unicode out as regular utf-8-encoded
    # characters, not as escape sequences

    tree = {
        "ɐʇɐp‾ǝpoɔıun": 42,
        "ascii_only": "this is ascii"
    }

    def check_asdf(asdf):
        assert "ɐʇɐp‾ǝpoɔıun" in asdf.tree
        assert isinstance(asdf.tree['ascii_only'], str)

    def check_raw_yaml(content):
        # Ensure that unicode is written out as UTF-8 without escape
        # sequences
        assert "ɐʇɐp‾ǝpoɔıun".encode('utf-8') in content
        # Ensure that the unicode "tag" is not used
        assert b"unicode" not in content

    helpers.assert_roundtrip_tree(tree, tmpdir, asdf_check_func=check_asdf,
                                  raw_yaml_check_func=check_raw_yaml)


def test_arbitrary_python_object():
    # Putting "just any old" Python object in the tree should raise an
    # exception.

    class Foo:
        pass

    tree = {'object': Foo()}

    buff = io.BytesIO()
    ff = asdf.AsdfFile(tree)
    with pytest.raises(yaml.YAMLError):
        ff.write_to(buff)


def run_tuple_test(tree, tmpdir):
    def check_asdf(asdf):
        assert isinstance(asdf.tree['val'], list)

    def check_raw_yaml(content):
        assert b'tuple' not in content

    # Ignore these warnings for the tests that don't actually test the warning
    init_options = dict(ignore_implicit_conversion=True)

    helpers.assert_roundtrip_tree(tree, tmpdir, asdf_check_func=check_asdf,
                                  raw_yaml_check_func=check_raw_yaml,
                                  init_options=init_options)


def test_python_tuple(tmpdir):
    # We don't want to store tuples as tuples, because that's not a
    # built-in YAML data type.  This test ensures that they are
    # converted to lists.

    tree = {
        "val": (1, 2, 3)
    }

    run_tuple_test(tree, tmpdir)


def test_named_tuple_collections(tmpdir):
    # Ensure that we are able to serialize a collections.namedtuple.

    nt = namedtuple("TestNamedTuple1", ("one", "two", "three"))

    tree = {
        "val": nt(1, 2, 3)
    }

    run_tuple_test(tree, tmpdir)

def test_named_tuple_typing(tmpdir):
    # Ensure that we are able to serialize a typing.NamedTuple.

    nt = NamedTuple("TestNamedTuple2",
                    (("one", int), ("two", int), ("three", int)))
    tree = {
        "val": nt(1, 2, 3)
    }

    run_tuple_test(tree, tmpdir)


def test_named_tuple_collections_recursive(tmpdir):
    nt = namedtuple("TestNamedTuple3", ("one", "two", "three"))

    tree = {
        "val": nt(1, 2, np.ones(3))
    }

    def check_asdf(asdf):
        assert (asdf.tree['val'][2] == np.ones(3)).all()

    init_options = dict(ignore_implicit_conversion=True)
    helpers.assert_roundtrip_tree(tree, tmpdir, asdf_check_func=check_asdf,
                                  init_options=init_options)


def test_named_tuple_typing_recursive(tmpdir):
    nt = NamedTuple("TestNamedTuple4",
                    (("one", int), ("two", int), ("three", np.ndarray)))

    tree = {
        "val": nt(1, 2, np.ones(3))
    }

    def check_asdf(asdf):
        assert (asdf.tree['val'][2] == np.ones(3)).all()

    init_options = dict(ignore_implicit_conversion=True)
    helpers.assert_roundtrip_tree(tree, tmpdir, asdf_check_func=check_asdf,
                                  init_options=init_options)


def test_implicit_conversion_warning():
    nt = namedtuple("TestTupleWarning", ("one", "two", "three"))

    tree = {
        "val": nt(1, 2, np.ones(3))
    }

    with pytest.warns(AsdfWarning, match="Failed to serialize instance"):
        with asdf.AsdfFile(tree):
            pass

    with helpers.assert_no_warnings():
        with asdf.AsdfFile(tree, ignore_implicit_conversion=True):
            pass


@pytest.mark.xfail(reason='pyyaml has a bug and does not support tuple keys')
def test_python_tuple_key(tmpdir):
    """
    This tests whether tuple keys are round-tripped properly.

    As of this writing, this does not work in pyyaml but does work in
    ruamel.yaml. If/when we decide to switch to ruamel.yaml, this test should
    pass.
    """
    tree = { (42, 1): 'foo' }
    helpers.assert_roundtrip_tree(tree, tmpdir)


def test_tags_removed_after_load(tmpdir):
    tree = {
        "foo": ["bar", (1, 2, None)]
        }

    def check_asdf(asdf):
        for node in treeutil.iter_tree(asdf.tree):
            if node != asdf.tree:
                assert not isinstance(node, tagged.Tagged)

    helpers.assert_roundtrip_tree(tree, tmpdir, asdf_check_func=check_asdf)


def test_explicit_tags():
    yaml = """#ASDF {}
%YAML 1.1
--- !<tag:stsci.edu:asdf/core/asdf-1.0.0>
foo: !<tag:stsci.edu:asdf/core/ndarray-1.0.0> [1, 2, 3]
...
    """.format(asdf.versioning.default_version)

    # Check that fully qualified explicit tags work
    buff = helpers.yaml_to_asdf(yaml, yaml_headers=False)

    with asdf.open(buff) as ff:
        assert all(ff.tree['foo'] == [1, 2, 3])


def test_yaml_internal_reference(tmpdir):
    # Test that YAML internal references (anchors and aliases) work,
    # as well as recursive data structures.

    d = {
        'foo': '2',
        }
    d['bar'] = d

    l = []
    l.append(l)

    tree = {
        'first': d,
        'second': d,
        'list': l
    }

    def check_yaml(content):
        assert b'list:&id002-*id002' in b''.join(content.split())
    helpers.assert_roundtrip_tree(tree, tmpdir, raw_yaml_check_func=check_yaml)


def test_yaml_nan_inf():
    tree = {
        'a': np.nan,
        'b': np.inf,
        'c': -np.inf
        }

    buff = io.BytesIO()
    ff = asdf.AsdfFile(tree)
    ff.write_to(buff)
    buff.seek(0)
    with asdf.open(buff) as ff:
        assert np.isnan(ff.tree['a'])
        assert np.isinf(ff.tree['b'])
        assert np.isinf(ff.tree['c'])


def test_tag_object():
    class SomeObject:
        pass

    tag = 'tag:nowhere.org:none/some/thing'
    instance = tagged.tag_object(tag, SomeObject())
    assert instance._tag == tag


@pytest.mark.parametrize("numpy_value,expected_value", [
    (np.str_("foo"), "foo"),
    (np.bytes_("foo"), b"foo"),
    (np.float16(3.14), 3.14),
    (np.float32(3.14159), 3.14159),
    (np.float64(3.14159), 3.14159),
    # Evidently float128 is not available on Windows:
    (getattr(np, "float128", np.float64)(3.14159), 3.14159),
    (np.int8(42), 42),
    (np.int16(42), 42),
    (np.int32(42), 42),
    (np.int64(42), 42),
    (np.longlong(42), 42),
    (np.uint8(42), 42),
    (np.uint16(42), 42),
    (np.uint32(42), 42),
    (np.uint64(42), 42),
    (np.ulonglong(42), 42),
])
def test_numpy_scalar(numpy_value, expected_value):
    ctx = asdf.AsdfFile()
    tree = {"value": numpy_value}
    buffer = io.BytesIO()

    yamlutil.dump_tree(tree, buffer, ctx)
    buffer.seek(0)

    if isinstance(expected_value, float) and NUMPY_LT_1_14:
        assert yamlutil.load_tree(buffer)["value"] == pytest.approx(expected_value, rel=0.001)
    else:
        assert yamlutil.load_tree(buffer)["value"] == expected_value