Debian Codegraph @

tests/test_utils.py

raw
1 import io
2
3 import fsspec
4 import json
5 import kerchunk.utils
6 import kerchunk.zarr
7 import numpy as np
8 import pytest
9 import zarr
10
11 from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper
12
13
14 def test_rename():
15 old = {"version": 1, "refs": {"v0": ["oldpath", 0, 0], "bin": "data"}}
16 new = kerchunk.utils.rename_target(old, {"oldpath": "newpath"})
17 assert new == {"version": 1, "refs": {"v0": ["newpath", 0, 0], "bin": "data"}}
18
19
20 def test_rename_files(m):
21 m.pipe(
22 "ref.json", b'{"version": 1, "refs": {"v0": ["oldpath", 0, 0], "bin": "data"}}'
23 )
24 kerchunk.utils.rename_target_files("memory://ref.json", {"oldpath": "newpath"})
25 out = m.cat("ref.json")
26 assert out == b'{"version":1,"refs":{"v0":["newpath",0,0],"bin":"data"}}'
27 kerchunk.utils.rename_target_files(
28 "memory://ref.json", {"newpath": "newerpath"}, url_out="memory://ref2.json"
29 )
30 out = m.cat("ref.json")
31 assert out == b'{"version":1,"refs":{"v0":["newpath",0,0],"bin":"data"}}'
32 out = m.cat("ref2.json")
33 assert out == b'{"version":1,"refs":{"v0":["newerpath",0,0],"bin":"data"}}'
34
35
36 def test_inline(m):
37 m.pipe("data", b"stuff")
38 refs = {
39 "key0": b"00",
40 "key1": ["memory://data"],
41 "key2": ["memory://data", 1, 1],
42 "key1": ["memory://data", 2, 4],
43 }
44 out = kerchunk.utils.do_inline(refs, 2)
45 expected = {
46 "key0": b"00",
47 "key1": ["memory://data"],
48 "key2": b"t",
49 "key1": ["memory://data", 2, 4],
50 }
51 assert out == expected
52
53
54 def test_inline_array():
55 refs = {
56 ".zgroup": b'{"zarr_format": 2}',
57 "data/.zarray": """
58 {
59 "chunks": [
60 1
61 ],
62 "compressor": null,
63 "dtype": "<i4",
64 "fill_value": 0,
65 "filters": null,
66 "order": "C",
67 "shape": [
68 2
69 ],
70 "zarr_format": 2
71 }
72 """,
73 "data/0": b"\x01\x00\x00\x00",
74 "data/1": b"\x02\x00\x00\x00",
75 "data/.zattrs": '{"foo": "bar"}',
76 }
77 out1 = kerchunk.utils.inline_array(refs, threshold=1) # does nothing
78 assert out1 == refs
79 out2 = kerchunk.utils.inline_array(refs, threshold=1, names=["data"]) # explicit
80 assert json.loads(out2["data/.zattrs"]) == json.loads(refs["data/.zattrs"])
81
82 localfs = fsspec.filesystem("file")
83 store = kerchunk.utils.refs_as_store(out2, fs=localfs)
84 g = zarr.open(store, mode="r", zarr_format=2)
85 assert g["data"][:].tolist() == [1, 2] # What is g.data???
86
87 out3 = kerchunk.utils.inline_array(refs, threshold=1000) # inlines because of size
88 store = kerchunk.utils.refs_as_store(out3, localfs)
89 g = zarr.open(store, mode="r", zarr_format=2)
90 assert g["data"][:].tolist() == [1, 2] # What is g.data???
91
92
93 def test_json():
94 data = {"a": "a", "b": b"b", "c": [None, None, None], "d": '{"key": 0}'}
95 out = kerchunk.utils._encode_for_JSON(data)
96 expected = {"a": "a", "b": "b", "c": [None, None, None], "d": '{"key":0}'}
97 assert out == expected
98
99
100 @pytest.mark.parametrize("chunks", [[10, 10], [5, 10]])
101 def test_subchunk_exact(m, chunks):
102 g = zarr.open_group("memory://test.zarr", mode="w", zarr_format=2)
103 data = np.arange(100).reshape(10, 10)
104 arr = g.create_array(
105 "data", dtype=data.dtype, shape=data.shape, chunks=chunks, compressor=None
106 )
107 arr[:] = data
108 ref = kerchunk.zarr.single_zarr("memory://test.zarr")["refs"]
109
110 extra = [] if chunks[0] == 10 else ["data/1.0"]
111 ref2 = list(_ for _ in ref if not _.endswith("zattrs")) # ignore empty attrs
112 assert ref2 == [".zgroup", "data/.zarray", "data/0.0"] + extra
113
114 out = kerchunk.utils.subchunk(ref, "data", 5)
115 nchunk = 10 // chunks[0] * 5
116 out2 = list(_ for _ in out if not _.endswith("zattrs"))
117 assert out2 == [".zgroup", "data/.zarray"] + [f"data/{_}.0" for _ in range(nchunk)]
118
119 store = kerchunk.utils.refs_as_store(out, remote_protocol="memory")
120 g2 = zarr.open_group(store, mode="r", zarr_format=2)
121
122 # g2 = zarr.open_group(
123 # "reference://", storage_options={"fo": out, "remote_protocol": "memory"}, zarr_format=2
124 # )
125 assert (g2["data"][:] == data).all()
126
127
128 @pytest.mark.parametrize("archive", ["zip", "tar"])
129 def test_archive(m, archive):
130 import zipfile
131 import tarfile
132
133 data = b"piece of data"
134 with fsspec.open("memory://archive", "wb") as f:
135 if archive == "zip":
136 arc = zipfile.ZipFile(file=f, mode="w")
137 arc.writestr("data1", data)
138 arc.close()
139 else:
140 arc = tarfile.TarFile(fileobj=f, mode="w")
141 ti = tarfile.TarInfo("data1")
142 ti.size = len(data)
143 arc.addfile(ti, io.BytesIO(data))
144 arc.close()
145 refs = {
146 "a": b"stuff",
147 "b": [f"{archive}://data1::memory://archive"],
148 "c": [f"{archive}://data1::memory://archive", 5, 2],
149 }
150
151 refs2 = kerchunk.utils.dereference_archives(refs)
152
153 fs = fsspec.filesystem("reference", fo=refs2)
154 assert fs.cat("a") == b"stuff"
155 assert fs.cat("b") == data
156 assert fs.cat("c") == data[5:7]
157
158
159 def test_deflate_zip_archive(m):
160 import zipfile
161 from kerchunk.codecs import DeflateCodec
162
163 dec = DeflateCodec()
164
165 data = b"piece of data"
166 with fsspec.open("memory://archive", "wb") as f:
167 arc = zipfile.ZipFile(file=f, mode="w", compression=zipfile.ZIP_DEFLATED)
168 arc.writestr("data1", data)
169 arc.close()
170 refs = {
171 "b": [f"zip://data1::memory://archive"],
172 }
173
174 with pytest.warns(UserWarning):
175 refs2 = kerchunk.utils.dereference_archives(refs)
176
177 fs = fsspec.filesystem("reference", fo=refs2)
178 assert dec.decode(fs.cat("b")) == data
179
180
181 def test_encode_fill_value():
182 assert kerchunk.utils.encode_fill_value(np.array([9999]), np.dtype("int")) == 9999
183 assert kerchunk.utils.encode_fill_value(np.array(9999), np.dtype("int")) == 9999
184 assert kerchunk.utils.encode_fill_value([9999], np.dtype("int")) == 9999
185 assert kerchunk.utils.encode_fill_value(9999, np.dtype("int")) == 9999