File: test_reference.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 (271 lines) | stat: -rw-r--r-- 8,266 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
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-


import io
import os

import numpy as np
from numpy.testing import assert_array_equal

import pytest

import asdf
from asdf import reference
from asdf import util
from asdf.tags.core import ndarray

from .helpers import assert_tree_match


def test_external_reference(tmpdir):
    exttree = {
        'cool_stuff': {
            'a': np.array([0, 1, 2], float),
            'b': np.array([3, 4, 5], float)
            },
        'list_of_stuff': [
            'foobar',
            42,
            np.array([7, 8, 9], float)
            ]
        }
    external_path = os.path.join(str(tmpdir), 'external.asdf')
    ext = asdf.AsdfFile(exttree)
    # Since we're testing with small arrays, force all arrays to be stored
    # in internal blocks rather than letting some of them be automatically put
    # inline.
    ext.write_to(external_path, all_array_storage='internal')

    external_path = os.path.join(str(tmpdir), 'external2.asdf')
    ff = asdf.AsdfFile(exttree)
    ff.write_to(external_path, all_array_storage='internal')

    tree = {
        # The special name "data" here must be an array.  This is
        # included so that such validation can be ignored when we just
        # have a "$ref".
        'data': {
            '$ref': 'external.asdf#/cool_stuff/a'
            },
        'science_data': {
            '$ref': 'external.asdf#/cool_stuff/a'
            },
        'science_data2': {
            '$ref': 'external2.asdf#/cool_stuff/a'
            },
        'foobar': {
            '$ref': 'external.asdf#/list_of_stuff/0',
            },
        'answer': {
            '$ref': 'external.asdf#/list_of_stuff/1'
            },
        'array': {
            '$ref': 'external.asdf#/list_of_stuff/2',
            },
        'whole_thing': {
            '$ref': 'external.asdf#'
            },
        'myself': {
            '$ref': '#',
            },
        'internal': {
            '$ref': '#science_data'
            }
        }

    def do_asserts(ff):
        assert 'unloaded' in repr(ff.tree['science_data'])
        assert 'unloaded' in str(ff.tree['science_data'])
        assert len(ff._external_asdf_by_uri) == 0

        assert_array_equal(ff.tree['science_data'], exttree['cool_stuff']['a'])
        assert len(ff._external_asdf_by_uri) == 1
        with pytest.raises((ValueError, RuntimeError)):
            # Assignment destination is readonly
            ff.tree['science_data'][0] = 42

        assert_array_equal(ff.tree['science_data2'], exttree['cool_stuff']['a'])
        assert len(ff._external_asdf_by_uri) == 2

        assert ff.tree['foobar']() == 'foobar'
        assert ff.tree['answer']() == 42
        assert_array_equal(ff.tree['array'], exttree['list_of_stuff'][2])

        assert_tree_match(ff.tree['whole_thing'](), exttree)

        assert_array_equal(
            ff.tree['whole_thing']['cool_stuff']['a'],
            exttree['cool_stuff']['a'])

        assert_array_equal(
            ff.tree['myself']['science_data'],
            exttree['cool_stuff']['a'])
        # Make sure that referencing oneself doesn't make another call
        # to disk.
        assert len(ff._external_asdf_by_uri) == 2

        assert_array_equal(ff.tree['internal'], exttree['cool_stuff']['a'])

    with asdf.AsdfFile(tree, uri=util.filepath_to_url(
            os.path.join(str(tmpdir), 'main.asdf'))) as ff:
        do_asserts(ff)

        internal_path = os.path.join(str(tmpdir), 'main.asdf')
        ff.write_to(internal_path)

    with asdf.open(internal_path) as ff:
        do_asserts(ff)

    with asdf.open(internal_path) as ff:
        assert len(ff._external_asdf_by_uri) == 0
        ff.resolve_references()
        assert len(ff._external_asdf_by_uri) == 2

        assert isinstance(ff.tree['data'], ndarray.NDArrayType)
        assert isinstance(ff.tree['science_data'], ndarray.NDArrayType)

        assert_array_equal(ff.tree['science_data'], exttree['cool_stuff']['a'])
        assert_array_equal(ff.tree['science_data2'], exttree['cool_stuff']['a'])

        assert ff.tree['foobar'] == 'foobar'
        assert ff.tree['answer'] == 42
        assert_array_equal(ff.tree['array'], exttree['list_of_stuff'][2])

        assert_tree_match(ff.tree['whole_thing'], exttree)

        assert_array_equal(
            ff.tree['whole_thing']['cool_stuff']['a'],
            exttree['cool_stuff']['a'])

        assert_array_equal(
            ff.tree['myself']['science_data'],
            exttree['cool_stuff']['a'])

        assert_array_equal(ff.tree['internal'], exttree['cool_stuff']['a'])


@pytest.mark.remote_data
def test_external_reference_invalid(tmpdir):
    tree = {
        'foo': {
            '$ref': 'fail.asdf'
            }
        }

    ff = asdf.AsdfFile(tree)
    with pytest.raises(ValueError):
        ff.resolve_references()

    ff = asdf.AsdfFile(tree, uri=util.filepath_to_url(
        os.path.join(str(tmpdir), 'main.asdf')))
    with pytest.raises(IOError):
        ff.resolve_references()


def test_external_reference_invalid_fragment(tmpdir):
    exttree = {
        'list_of_stuff': [
            'foobar',
            42,
            np.array([7, 8, 9], float)
            ]
        }
    external_path = os.path.join(str(tmpdir), 'external.asdf')
    ff = asdf.AsdfFile(exttree)
    ff.write_to(external_path)

    tree = {
        'foo': {
            '$ref': 'external.asdf#/list_of_stuff/a'
            }
        }

    with asdf.AsdfFile(tree, uri=util.filepath_to_url(
            os.path.join(str(tmpdir), 'main.asdf'))) as ff:
        with pytest.raises(ValueError):
            ff.resolve_references()

    tree = {
        'foo': {
            '$ref': 'external.asdf#/list_of_stuff/3'
            }
        }

    with asdf.AsdfFile(tree, uri=util.filepath_to_url(
            os.path.join(str(tmpdir), 'main.asdf'))) as ff:
        with pytest.raises(ValueError):
            ff.resolve_references()


def test_make_reference(tmpdir):
    exttree = {
        # Include some ~ and / in the name to make sure that escaping
        # is working correctly
        'f~o~o/': {
            'a': np.array([0, 1, 2], float),
            'b': np.array([3, 4, 5], float)
            }
        }
    external_path = os.path.join(str(tmpdir), 'external.asdf')
    ext = asdf.AsdfFile(exttree)
    ext.write_to(external_path)

    with asdf.open(external_path) as ext:
        ff = asdf.AsdfFile()
        ff.tree['ref'] = ext.make_reference(['f~o~o/', 'a'])
        assert_array_equal(ff.tree['ref'], ext.tree['f~o~o/']['a'])

        ff.write_to(os.path.join(str(tmpdir), 'source.asdf'))

    with asdf.open(os.path.join(str(tmpdir), 'source.asdf')) as ff:
        assert ff.tree['ref']._uri == 'external.asdf#f~0o~0o~1/a'


def test_internal_reference(tmpdir):
    testfile = os.path.join(str(tmpdir), 'test.asdf')

    tree = {
        'foo': 2,
        'bar': {'$ref': '#'}
    }

    ff = asdf.AsdfFile(tree)
    ff.find_references()
    assert isinstance(ff.tree['bar'], reference.Reference)
    ff.resolve_references()
    assert ff.tree['bar']['foo'] == 2

    tree = {
        'foo': 2
    }
    ff = asdf.AsdfFile(
        tree, uri=util.filepath_to_url(os.path.abspath(testfile)))
    ff.tree['bar'] = ff.make_reference([])
    buff = io.BytesIO()
    ff.write_to(buff)
    buff.seek(0)
    ff = asdf.AsdfFile()
    content = asdf.AsdfFile()._open_impl(ff, buff, _get_yaml_content=True)
    assert b"{$ref: ''}" in content


def test_implicit_internal_reference(tmpdir):
    target = {"foo": "bar"}
    nested_in_dict = {"target": target}
    nested_in_list = [target]
    tree = {"target": target, "nested_in_dict": nested_in_dict, "nested_in_list": nested_in_list}

    assert tree["target"] is tree["nested_in_dict"]["target"]
    assert tree["target"] is tree["nested_in_list"][0]

    af = asdf.AsdfFile(tree)

    assert af["target"] is af["nested_in_dict"]["target"]
    assert af["target"] is af["nested_in_list"][0]

    output_path = os.path.join(str(tmpdir), "test.asdf")
    af.write_to(output_path)
    with asdf.open(output_path) as af:
        assert af["target"] is af["nested_in_dict"]["target"]
        assert af["target"] is af["nested_in_list"][0]