File: test_instance_loader.py

package info (click to toggle)
python-check-jsonschema 0.34.1-1
  • links: PTS
  • area: main
  • in suites: sid
  • size: 3,796 kB
  • sloc: python: 5,529; makefile: 4
file content (293 lines) | stat: -rw-r--r-- 8,352 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
import pytest

from check_jsonschema.instance_loader import InstanceLoader
from check_jsonschema.parsers import BadFileTypeError, FailedFileLoadError
from check_jsonschema.parsers.json5 import ENABLED as JSON5_ENABLED


# handy helper for opening multiple files for InstanceLoader
@pytest.fixture
def open_wide():
    track_paths = []

    def func(*paths):
        open_paths = [open(p, "rb") for p in paths]
        track_paths.extend(open_paths)
        return open_paths

    yield func

    for p in track_paths:
        p.close()


@pytest.mark.parametrize(
    "filename, default_filetype",
    [
        ("foo.json", "notarealfiletype"),
        ("foo.json", "json"),
        ("foo.json", "yaml"),
        ("foo", "json"),
        # YAML is a superset of JSON, so using the YAML loader should be safe when the
        # data is JSON
        ("foo", "yaml"),
    ],
)
def test_instanceloader_json_data(tmp_path, filename, default_filetype, open_wide):
    f = tmp_path / filename
    f.write_text("{}")
    loader = InstanceLoader(open_wide(f), default_filetype=default_filetype)
    data = list(loader.iter_files())
    assert data == [(str(f), {})]


@pytest.mark.parametrize(
    "filename, default_filetype",
    [
        ("foo.yaml", "notarealfiletype"),
        ("foo.yml", "notarealfiletype"),
        ("foo.yaml", "json"),
        ("foo.yml", "json"),
        ("foo.yaml", "yaml"),
        ("foo.yml", "yaml"),
        ("foo", "yaml"),
    ],
)
def test_instanceloader_yaml_data(tmp_path, filename, default_filetype, open_wide):
    f = tmp_path / filename
    f.write_text(
        """\
a:
  b:
   - 1
   - 2
  c: d
"""
    )
    loader = InstanceLoader(open_wide(f), default_filetype=default_filetype)
    data = list(loader.iter_files())
    assert data == [(str(f), {"a": {"b": [1, 2], "c": "d"}})]


@pytest.mark.parametrize(
    "filename, default_filetype",
    [
        ("foo.toml", "notarealfiletype"),
        ("foo.toml", "json"),
        ("foo.toml", "yaml"),
        ("foo", "toml"),
    ],
)
def test_instanceloader_toml_data(tmp_path, filename, default_filetype, open_wide):
    f = tmp_path / filename
    f.write_text('[foo]\nbar = "baz"\n')
    loader = InstanceLoader(open_wide(f), default_filetype=default_filetype)
    data = list(loader.iter_files())
    assert data == [(str(f), {"foo": {"bar": "baz"}})]


@pytest.mark.parametrize(
    "filename, force_filetype",
    [
        ("foo.test", "toml"),
        ("foo", "toml"),
    ],
)
def test_instanceloader_force_filetype_toml(
    tmp_path, filename, force_filetype, open_wide
):
    f = tmp_path / filename
    f.write_text('[foo]\nbar = "baz"\n')
    loader = InstanceLoader(open_wide(f), force_filetype=force_filetype)
    data = list(loader.iter_files())
    assert data == [(str(f), {"foo": {"bar": "baz"}})]


@pytest.mark.skipif(not JSON5_ENABLED, reason="test requires json5")
@pytest.mark.parametrize(
    "filename, force_filetype",
    [
        ("foo.test", "json5"),
        ("foo.json", "json5"),
    ],
)
def test_instanceloader_force_filetype_json(
    tmp_path, filename, force_filetype, open_wide
):
    f = tmp_path / filename
    f.write_text("// a comment\n{}")
    loader = InstanceLoader(open_wide(f), force_filetype=force_filetype)
    data = list(loader.iter_files())
    print(data)
    assert data == [(str(f), {})]


def test_instanceloader_unknown_type_nonjson_content(tmp_path, open_wide):
    f = tmp_path / "foo"  # no extension here
    f.write_text("a:b")  # non-json data (cannot be detected as JSON)
    loader = InstanceLoader(open_wide(f), default_filetype="unknown")
    # at iteration time, the file should error and be reported as such
    data = list(loader.iter_files())
    assert len(data) == 1
    assert isinstance(data[0], tuple)
    assert len(data[0]) == 2
    assert data[0][0] == str(f)
    assert isinstance(data[0][1], BadFileTypeError)


@pytest.mark.parametrize(
    "enabled_flag, extension, file_content, expect_data, expect_error_message",
    [
        (
            JSON5_ENABLED,
            "json5",
            "{}",
            {},
            "pip install json5",
        ),
    ],
)
def test_instanceloader_optional_format_handling(
    tmp_path,
    enabled_flag,
    extension,
    file_content,
    expect_data,
    expect_error_message,
    open_wide,
):
    f = tmp_path / f"foo.{extension}"
    f.write_text(file_content)
    loader = InstanceLoader(open_wide(f))
    if enabled_flag:
        # at iteration time, the file should load fine
        data = list(loader.iter_files())
        assert data == [(str(f), expect_data)]
    else:
        # at iteration time, an error should be raised
        data = list(loader.iter_files())
        assert len(data) == 1
        assert isinstance(data[0], tuple)
        assert len(data[0]) == 2
        assert data[0][0] == str(f)
        assert isinstance(data[0][1], BadFileTypeError)

        # error message should be instructive
        assert expect_error_message in str(data[0])


def test_instanceloader_yaml_dup_anchor(tmp_path, open_wide):
    f = tmp_path / "foo.yaml"
    f.write_text(
        """\
a:
  b: &anchor
   - 1
   - 2
  c: &anchor d
"""
    )
    loader = InstanceLoader(open_wide(f))
    data = list(loader.iter_files())
    assert data == [(str(f), {"a": {"b": [1, 2], "c": "d"}})]


@pytest.mark.parametrize(
    "file_format, filename, content",
    [
        ("json", "foo.json", '{"a":\n'),
        ("yaml", "foo.yaml", "a: {b\n"),
        ("yaml", "foo.yaml", "a: b\nc\n"),
        ("json5", "foo.json5", '{"a":\n'),
        ("toml", "foo.toml", "abc\n"),
    ],
)
def test_instanceloader_invalid_data(
    tmp_path, file_format, filename, content, open_wide
):
    if file_format == "json5" and not JSON5_ENABLED:
        pytest.skip("test requires 'json5' support")

    f = tmp_path / filename
    f.write_text(content)
    loader = InstanceLoader(open_wide(f))
    data = list(loader.iter_files())
    assert len(data) == 1
    assert isinstance(data[0], tuple)
    assert len(data[0]) == 2
    assert data[0][0] == str(f)
    assert isinstance(data[0][1], FailedFileLoadError)


def test_instanceloader_invalid_data_mixed_with_valid_data(tmp_path, open_wide):
    a = tmp_path / "a.json"
    b = tmp_path / "b.json"
    c = tmp_path / "c.json"
    a.write_text("{}")
    b.write_text("{")
    c.write_text('{"c":true}')

    loader = InstanceLoader(open_wide(a, b, c))

    data = list(loader.iter_files())
    assert len(data) == 3

    assert data[0] == (str(a), {})

    assert isinstance(data[1], tuple)
    assert len(data[1]) == 2
    assert data[1][0] == str(b)
    assert isinstance(data[1][1], FailedFileLoadError)

    assert data[2] == (str(c), {"c": True})


@pytest.mark.parametrize(
    "filetypes",
    (
        ("json", "yaml"),
        ("json", "json5"),
        ("yaml", "toml"),
        ("json", "yaml", "toml", "json5"),
    ),
)
def test_instanceloader_mixed_filetypes(tmp_path, filetypes, open_wide):
    if not JSON5_ENABLED and "json5" in filetypes:
        pytest.skip("test requires json5")
    files = {}
    file_order = []
    if "json" in filetypes:
        files["json"] = tmp_path / "F.json"
        files["json"].write_text("{}")
        file_order.append("json")
    if "yaml" in filetypes:
        files["yaml"] = tmp_path / "F.yaml"
        files["yaml"].write_text("foo: bar")
        file_order.append("yaml")
    if "json5" in filetypes:
        files["json5"] = tmp_path / "F.json5"
        files["json5"].write_text('{//hi\n"c": 1}')
        file_order.append("json5")
    if "toml" in filetypes:
        files["toml"] = tmp_path / "F.toml"
        files["toml"].write_text('[foo]  # bar\nname = "value"\n')
        file_order.append("toml")

    loader = InstanceLoader(open_wide(*files.values()))

    data = list(loader.iter_files())
    assert len(data) == len(files)

    for i, filetype in enumerate(file_order):
        assert isinstance(data[i], tuple)
        assert len(data[i]) == 2
        path, value = data[i]
        assert path == str(files[filetype])
        if filetype == "json":
            assert value == {}
        elif filetype == "yaml":
            assert value == {"foo": "bar"}
        elif filetype == "json5":
            assert value == {"c": 1}
        elif filetype == "toml":
            assert value == {"foo": {"name": "value"}}