-
-
Notifications
You must be signed in to change notification settings - Fork 304
/
Copy pathtest_storage.py
2607 lines (2188 loc) · 88.5 KB
/
test_storage.py
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import array
import atexit
import json
import os
import pathlib
import sys
import pickle
import shutil
import tempfile
from contextlib import contextmanager
from pickle import PicklingError
from zipfile import ZipFile
import numpy as np
import pytest
from numpy.testing import assert_array_almost_equal, assert_array_equal
from numcodecs.compat import ensure_bytes
import zarr
from zarr._storage.store import _get_hierarchy_metadata
from zarr.codecs import BZ2, AsType, Blosc, Zlib
from zarr.context import Context
from zarr.convenience import consolidate_metadata
from zarr.errors import ContainsArrayError, ContainsGroupError, MetadataError
from zarr.hierarchy import group
from zarr.meta import ZARR_FORMAT, decode_array_metadata
from zarr.n5 import N5Store, N5FSStore, N5_FORMAT, n5_attrs_key
from zarr.storage import (
ABSStore,
ConsolidatedMetadataStore,
DBMStore,
DictStore,
DirectoryStore,
KVStore,
LMDBStore,
LRUStoreCache,
MemoryStore,
MongoDBStore,
NestedDirectoryStore,
RedisStore,
SQLiteStore,
Store,
TempStore,
ZipStore,
array_meta_key,
atexit_rmglob,
atexit_rmtree,
attrs_key,
data_root,
default_compressor,
getsize,
group_meta_key,
init_array,
init_group,
migrate_1to2,
meta_root,
normalize_store_arg,
)
from zarr.storage import FSStore, rename, listdir
from zarr._storage.v3 import KVStoreV3
from zarr.tests.util import CountingDict, have_fsspec, skip_test_env_var, abs_container, mktemp
from zarr.util import ConstantMap, json_dumps
@contextmanager
def does_not_raise():
yield
@pytest.fixture(
params=[
(None, "."),
(".", "."),
("/", "/"),
]
)
def dimension_separator_fixture(request):
return request.param
def skip_if_nested_chunks(**kwargs):
if kwargs.get("dimension_separator") == "/":
pytest.skip("nested chunks are unsupported")
def test_kvstore_repr():
repr(KVStore(dict()))
def test_ensure_store():
class InvalidStore:
pass
with pytest.raises(ValueError):
Store._ensure_store(InvalidStore())
# cannot initialize with a store from a different Zarr version
with pytest.raises(ValueError):
Store._ensure_store(KVStoreV3(dict()))
# cannot initialize without a store
with pytest.raises(ValueError):
Store._ensure_store(None)
def test_capabilities():
s = KVStore(dict())
assert s.is_readable()
assert s.is_listable()
assert s.is_erasable()
assert s.is_writeable()
def test_getsize_non_implemented():
assert getsize(object()) == -1
def test_kvstore_eq():
assert KVStore(dict()) != dict()
def test_coverage_rename():
store = dict()
store["a"] = 1
rename(store, "a", "b")
def test_deprecated_listdir_nosotre():
store = dict()
with pytest.warns(UserWarning, match="has no `listdir`"):
listdir(store)
class StoreTests:
"""Abstract store tests."""
version = 2
root = ""
def create_store(self, **kwargs): # pragma: no cover
# implement in sub-class
raise NotImplementedError
def test_context_manager(self):
with self.create_store():
pass
def test_get_set_del_contains(self):
store = self.create_store()
# test __contains__, __getitem__, __setitem__
key = self.root + "foo"
assert key not in store
with pytest.raises(KeyError):
# noinspection PyStatementEffect
store[key]
store[key] = b"bar"
assert key in store
assert b"bar" == ensure_bytes(store[key])
# test __delitem__ (optional)
try:
del store[key]
except NotImplementedError:
pass
else:
assert key not in store
with pytest.raises(KeyError):
# noinspection PyStatementEffect
store[key]
with pytest.raises(KeyError):
# noinspection PyStatementEffect
del store[key]
store.close()
def test_set_invalid_content(self):
store = self.create_store()
with pytest.raises(TypeError):
store[self.root + "baz"] = list(range(5))
store.close()
def test_clear(self):
store = self.create_store()
store[self.root + "foo"] = b"bar"
store[self.root + "baz"] = b"qux"
assert len(store) == 2
store.clear()
assert len(store) == 0
assert self.root + "foo" not in store
assert self.root + "baz" not in store
store.close()
def test_pop(self):
store = self.create_store()
store[self.root + "foo"] = b"bar"
store[self.root + "baz"] = b"qux"
assert len(store) == 2
v = store.pop(self.root + "foo")
assert ensure_bytes(v) == b"bar"
assert len(store) == 1
v = store.pop(self.root + "baz")
assert ensure_bytes(v) == b"qux"
assert len(store) == 0
with pytest.raises(KeyError):
store.pop(self.root + "xxx")
v = store.pop(self.root + "xxx", b"default")
assert v == b"default"
v = store.pop(self.root + "xxx", b"")
assert v == b""
v = store.pop(self.root + "xxx", None)
assert v is None
store.close()
def test_popitem(self):
store = self.create_store()
store[self.root + "foo"] = b"bar"
k, v = store.popitem()
assert k == self.root + "foo"
assert ensure_bytes(v) == b"bar"
assert len(store) == 0
with pytest.raises(KeyError):
store.popitem()
store.close()
def test_writeable_values(self):
store = self.create_store()
# __setitem__ should accept any value that implements buffer interface
store[self.root + "foo1"] = b"bar"
store[self.root + "foo2"] = bytearray(b"bar")
store[self.root + "foo3"] = array.array("B", b"bar")
store[self.root + "foo4"] = np.frombuffer(b"bar", dtype="u1")
store.close()
def test_update(self):
store = self.create_store()
assert self.root + "foo" not in store
assert self.root + "baz" not in store
if self.version == 2:
store.update(foo=b"bar", baz=b"quux")
else:
kv = {self.root + "foo": b"bar", self.root + "baz": b"quux"}
store.update(kv)
assert b"bar" == ensure_bytes(store[self.root + "foo"])
assert b"quux" == ensure_bytes(store[self.root + "baz"])
store.close()
def test_iterators(self):
store = self.create_store()
# test iterator methods on empty store
assert 0 == len(store)
assert set() == set(store)
assert set() == set(store.keys())
assert set() == set(store.values())
assert set() == set(store.items())
# setup some values
store[self.root + "a"] = b"aaa"
store[self.root + "b"] = b"bbb"
store[self.root + "c/d"] = b"ddd"
store[self.root + "c/e/f"] = b"fff"
# test iterators on store with data
assert 4 == len(store)
expected = set(self.root + k for k in ["a", "b", "c/d", "c/e/f"])
assert expected == set(store)
assert expected == set(store.keys())
assert {b"aaa", b"bbb", b"ddd", b"fff"} == set(map(ensure_bytes, store.values()))
assert {
(self.root + "a", b"aaa"),
(self.root + "b", b"bbb"),
(self.root + "c/d", b"ddd"),
(self.root + "c/e/f", b"fff"),
} == set(map(lambda kv: (kv[0], ensure_bytes(kv[1])), store.items()))
store.close()
def test_pickle(self):
# setup store
store = self.create_store()
store[self.root + "foo"] = b"bar"
store[self.root + "baz"] = b"quux"
n = len(store)
keys = sorted(store.keys())
# round-trip through pickle
dump = pickle.dumps(store)
# some stores cannot be opened twice at the same time, need to close
# store before can round-trip through pickle
store.close()
# check can still pickle after close
assert dump == pickle.dumps(store)
store2 = pickle.loads(dump)
# verify
assert n == len(store2)
assert keys == sorted(store2.keys())
assert b"bar" == ensure_bytes(store2[self.root + "foo"])
assert b"quux" == ensure_bytes(store2[self.root + "baz"])
store2.close()
def test_getsize(self):
store = self.create_store()
if isinstance(store, dict) or hasattr(store, "getsize"):
assert 0 == getsize(store)
store["foo"] = b"x"
assert 1 == getsize(store)
assert 1 == getsize(store, "foo")
store["bar"] = b"yy"
assert 3 == getsize(store)
assert 2 == getsize(store, "bar")
store["baz"] = bytearray(b"zzz")
assert 6 == getsize(store)
assert 3 == getsize(store, "baz")
store["quux"] = array.array("B", b"zzzz")
assert 10 == getsize(store)
assert 4 == getsize(store, "quux")
store["spong"] = np.frombuffer(b"zzzzz", dtype="u1")
assert 15 == getsize(store)
assert 5 == getsize(store, "spong")
store.close()
# noinspection PyStatementEffect
def test_hierarchy(self):
# setup
store = self.create_store()
store[self.root + "a"] = b"aaa"
store[self.root + "b"] = b"bbb"
store[self.root + "c/d"] = b"ddd"
store[self.root + "c/e/f"] = b"fff"
store[self.root + "c/e/g"] = b"ggg"
# check keys
assert self.root + "a" in store
assert self.root + "b" in store
assert self.root + "c/d" in store
assert self.root + "c/e/f" in store
assert self.root + "c/e/g" in store
assert self.root + "c" not in store
assert self.root + "c/" not in store
assert self.root + "c/e" not in store
assert self.root + "c/e/" not in store
assert self.root + "c/d/x" not in store
# check __getitem__
with pytest.raises(KeyError):
store[self.root + "c"]
with pytest.raises(KeyError):
store[self.root + "c/e"]
with pytest.raises(KeyError):
store[self.root + "c/d/x"]
# test getsize (optional)
if hasattr(store, "getsize"):
# TODO: proper behavior of getsize?
# v3 returns size of all nested arrays, not just the
# size of the arrays in the current folder.
if self.version == 2:
assert 6 == store.getsize()
else:
assert 15 == store.getsize()
assert 3 == store.getsize("a")
assert 3 == store.getsize("b")
if self.version == 2:
assert 3 == store.getsize("c")
else:
assert 9 == store.getsize("c")
assert 3 == store.getsize("c/d")
assert 6 == store.getsize("c/e")
assert 3 == store.getsize("c/e/f")
assert 3 == store.getsize("c/e/g")
# non-existent paths
assert 0 == store.getsize("x")
assert 0 == store.getsize("a/x")
assert 0 == store.getsize("c/x")
assert 0 == store.getsize("c/x/y")
assert 0 == store.getsize("c/d/y")
assert 0 == store.getsize("c/d/y/z")
# access item via full path
assert 3 == store.getsize(self.root + "a")
# test listdir (optional)
if hasattr(store, "listdir"):
assert {"a", "b", "c"} == set(store.listdir(self.root))
assert {"d", "e"} == set(store.listdir(self.root + "c"))
assert {"f", "g"} == set(store.listdir(self.root + "c/e"))
# no exception raised if path does not exist or is leaf
assert [] == store.listdir(self.root + "x")
assert [] == store.listdir(self.root + "a/x")
assert [] == store.listdir(self.root + "c/x")
assert [] == store.listdir(self.root + "c/x/y")
assert [] == store.listdir(self.root + "c/d/y")
assert [] == store.listdir(self.root + "c/d/y/z")
assert [] == store.listdir(self.root + "c/e/f")
# test rename (optional)
if store.is_erasable():
store.rename("c/e", "c/e2")
assert self.root + "c/d" in store
assert self.root + "c/e" not in store
assert self.root + "c/e/f" not in store
assert self.root + "c/e/g" not in store
assert self.root + "c/e2" not in store
assert self.root + "c/e2/f" in store
assert self.root + "c/e2/g" in store
store.rename("c/e2", "c/e")
assert self.root + "c/d" in store
assert self.root + "c/e2" not in store
assert self.root + "c/e2/f" not in store
assert self.root + "c/e2/g" not in store
assert self.root + "c/e" not in store
assert self.root + "c/e/f" in store
assert self.root + "c/e/g" in store
store.rename("c", "c1/c2/c3")
assert self.root + "a" in store
assert self.root + "c" not in store
assert self.root + "c/d" not in store
assert self.root + "c/e" not in store
assert self.root + "c/e/f" not in store
assert self.root + "c/e/g" not in store
assert self.root + "c1" not in store
assert self.root + "c1/c2" not in store
assert self.root + "c1/c2/c3" not in store
assert self.root + "c1/c2/c3/d" in store
assert self.root + "c1/c2/c3/e" not in store
assert self.root + "c1/c2/c3/e/f" in store
assert self.root + "c1/c2/c3/e/g" in store
store.rename("c1/c2/c3", "c")
assert self.root + "c" not in store
assert self.root + "c/d" in store
assert self.root + "c/e" not in store
assert self.root + "c/e/f" in store
assert self.root + "c/e/g" in store
assert self.root + "c1" not in store
assert self.root + "c1/c2" not in store
assert self.root + "c1/c2/c3" not in store
assert self.root + "c1/c2/c3/d" not in store
assert self.root + "c1/c2/c3/e" not in store
assert self.root + "c1/c2/c3/e/f" not in store
assert self.root + "c1/c2/c3/e/g" not in store
# test rmdir (optional)
store.rmdir("c/e")
assert self.root + "c/d" in store
assert self.root + "c/e/f" not in store
assert self.root + "c/e/g" not in store
store.rmdir("c")
assert self.root + "c/d" not in store
store.rmdir()
assert self.root + "a" not in store
assert self.root + "b" not in store
store[self.root + "a"] = b"aaa"
store[self.root + "c/d"] = b"ddd"
store[self.root + "c/e/f"] = b"fff"
# no exceptions raised if path does not exist or is leaf
store.rmdir("x")
store.rmdir("a/x")
store.rmdir("c/x")
store.rmdir("c/x/y")
store.rmdir("c/d/y")
store.rmdir("c/d/y/z")
store.rmdir("c/e/f")
assert self.root + "a" in store
assert self.root + "c/d" in store
assert self.root + "c/e/f" in store
store.close()
def test_init_array(self, dimension_separator_fixture):
pass_dim_sep, want_dim_sep = dimension_separator_fixture
store = self.create_store(dimension_separator=pass_dim_sep)
init_array(store, shape=1000, chunks=100)
# check metadata
assert array_meta_key in store
meta = store._metadata_class.decode_array_metadata(store[array_meta_key])
assert ZARR_FORMAT == meta["zarr_format"]
assert (1000,) == meta["shape"]
assert (100,) == meta["chunks"]
assert np.dtype(None) == meta["dtype"]
assert default_compressor.get_config() == meta["compressor"]
assert meta["fill_value"] is None
# Missing MUST be assumed to be "."
assert meta.get("dimension_separator", ".") is want_dim_sep
store.close()
def test_init_array_overwrite(self):
self._test_init_array_overwrite("F")
def test_init_array_overwrite_path(self):
self._test_init_array_overwrite_path("F")
def test_init_array_overwrite_chunk_store(self):
self._test_init_array_overwrite_chunk_store("F")
def test_init_group_overwrite(self):
self._test_init_group_overwrite("F")
def test_init_group_overwrite_path(self):
self._test_init_group_overwrite_path("F")
def test_init_group_overwrite_chunk_store(self):
self._test_init_group_overwrite_chunk_store("F")
def _test_init_array_overwrite(self, order):
# setup
store = self.create_store()
if self.version == 2:
path = None
mkey = array_meta_key
meta = dict(
shape=(2000,),
chunks=(200,),
dtype=np.dtype("u1"),
compressor=Zlib(1).get_config(),
fill_value=0,
order=order,
filters=None,
)
else:
path = "arr1" # no default, have to specify for v3
mkey = meta_root + path + ".array.json"
meta = dict(
shape=(2000,),
chunk_grid=dict(type="regular", chunk_shape=(200,), separator=("/")),
data_type=np.dtype("u1"),
compressor=Zlib(1),
fill_value=0,
chunk_memory_layout=order,
filters=None,
)
store[mkey] = store._metadata_class.encode_array_metadata(meta)
# don't overwrite (default)
with pytest.raises(ContainsArrayError):
init_array(store, shape=1000, chunks=100, path=path)
# do overwrite
try:
init_array(store, shape=1000, chunks=100, dtype="i4", overwrite=True, path=path)
except NotImplementedError:
pass
else:
assert mkey in store
meta = store._metadata_class.decode_array_metadata(store[mkey])
if self.version == 2:
assert ZARR_FORMAT == meta["zarr_format"]
assert (100,) == meta["chunks"]
assert np.dtype("i4") == meta["dtype"]
else:
assert (100,) == meta["chunk_grid"]["chunk_shape"]
assert np.dtype("i4") == meta["data_type"]
assert (1000,) == meta["shape"]
store.close()
def test_init_array_path(self):
path = "foo/bar"
store = self.create_store()
init_array(store, shape=1000, chunks=100, path=path)
# check metadata
if self.version == 2:
mkey = path + "/" + array_meta_key
else:
mkey = meta_root + path + ".array.json"
assert mkey in store
meta = store._metadata_class.decode_array_metadata(store[mkey])
if self.version == 2:
assert ZARR_FORMAT == meta["zarr_format"]
assert (100,) == meta["chunks"]
assert np.dtype(None) == meta["dtype"]
assert default_compressor.get_config() == meta["compressor"]
else:
assert (100,) == meta["chunk_grid"]["chunk_shape"]
assert np.dtype(None) == meta["data_type"]
assert default_compressor == meta["compressor"]
assert (1000,) == meta["shape"]
assert meta["fill_value"] is None
store.close()
def _test_init_array_overwrite_path(self, order):
# setup
path = "foo/bar"
store = self.create_store()
if self.version == 2:
mkey = path + "/" + array_meta_key
meta = dict(
shape=(2000,),
chunks=(200,),
dtype=np.dtype("u1"),
compressor=Zlib(1).get_config(),
fill_value=0,
order=order,
filters=None,
)
else:
mkey = meta_root + path + ".array.json"
meta = dict(
shape=(2000,),
chunk_grid=dict(type="regular", chunk_shape=(200,), separator=("/")),
data_type=np.dtype("u1"),
compressor=Zlib(1),
fill_value=0,
chunk_memory_layout=order,
filters=None,
)
store[mkey] = store._metadata_class.encode_array_metadata(meta)
# don't overwrite
with pytest.raises(ContainsArrayError):
init_array(store, shape=1000, chunks=100, path=path)
# do overwrite
try:
init_array(store, shape=1000, chunks=100, dtype="i4", path=path, overwrite=True)
except NotImplementedError:
pass
else:
if self.version == 2:
assert group_meta_key in store
assert array_meta_key not in store
assert mkey in store
# should have been overwritten
meta = store._metadata_class.decode_array_metadata(store[mkey])
if self.version == 2:
assert ZARR_FORMAT == meta["zarr_format"]
assert (100,) == meta["chunks"]
assert np.dtype("i4") == meta["dtype"]
else:
assert (100,) == meta["chunk_grid"]["chunk_shape"]
assert np.dtype("i4") == meta["data_type"]
assert (1000,) == meta["shape"]
store.close()
def test_init_array_overwrite_group(self):
# setup
path = "foo/bar"
store = self.create_store()
if self.version == 2:
array_key = path + "/" + array_meta_key
group_key = path + "/" + group_meta_key
else:
array_key = meta_root + path + ".array.json"
group_key = meta_root + path + ".group.json"
store[group_key] = store._metadata_class.encode_group_metadata()
# don't overwrite
with pytest.raises(ContainsGroupError):
init_array(store, shape=1000, chunks=100, path=path)
# do overwrite
try:
init_array(store, shape=1000, chunks=100, dtype="i4", path=path, overwrite=True)
except NotImplementedError:
pass
else:
assert group_key not in store
assert array_key in store
meta = store._metadata_class.decode_array_metadata(store[array_key])
if self.version == 2:
assert ZARR_FORMAT == meta["zarr_format"]
assert (100,) == meta["chunks"]
assert np.dtype("i4") == meta["dtype"]
else:
assert (100,) == meta["chunk_grid"]["chunk_shape"]
assert np.dtype("i4") == meta["data_type"]
assert (1000,) == meta["shape"]
store.close()
def _test_init_array_overwrite_chunk_store(self, order):
# setup
store = self.create_store()
chunk_store = self.create_store()
if self.version == 2:
path = None
data_path = ""
mkey = array_meta_key
meta = dict(
shape=(2000,),
chunks=(200,),
dtype=np.dtype("u1"),
compressor=None,
fill_value=0,
filters=None,
order=order,
)
else:
path = "arr1"
data_path = data_root + "arr1/"
mkey = meta_root + path + ".array.json"
meta = dict(
shape=(2000,),
chunk_grid=dict(type="regular", chunk_shape=(200,), separator=("/")),
data_type=np.dtype("u1"),
compressor=None,
fill_value=0,
filters=None,
chunk_memory_layout=order,
)
store[mkey] = store._metadata_class.encode_array_metadata(meta)
chunk_store[data_path + "0"] = b"aaa"
chunk_store[data_path + "1"] = b"bbb"
# don't overwrite (default)
with pytest.raises(ContainsArrayError):
init_array(store, path=path, shape=1000, chunks=100, chunk_store=chunk_store)
# do overwrite
try:
init_array(
store,
path=path,
shape=1000,
chunks=100,
dtype="i4",
overwrite=True,
chunk_store=chunk_store,
)
except NotImplementedError:
pass
else:
assert mkey in store
meta = store._metadata_class.decode_array_metadata(store[mkey])
if self.version == 2:
assert ZARR_FORMAT == meta["zarr_format"]
assert (100,) == meta["chunks"]
assert np.dtype("i4") == meta["dtype"]
else:
assert (100,) == meta["chunk_grid"]["chunk_shape"]
assert np.dtype("i4") == meta["data_type"]
assert (1000,) == meta["shape"]
assert data_path + "0" not in chunk_store
assert data_path + "1" not in chunk_store
store.close()
chunk_store.close()
def test_init_array_compat(self):
store = self.create_store()
if self.version == 2:
path = None
mkey = array_meta_key
else:
path = "arr1"
mkey = meta_root + path + ".array.json"
init_array(store, path=path, shape=1000, chunks=100, compressor="none")
meta = store._metadata_class.decode_array_metadata(store[mkey])
if self.version == 2:
assert meta["compressor"] is None
else:
assert "compressor" not in meta
store.close()
def test_init_group(self):
store = self.create_store()
if self.version == 2:
path = None
mkey = group_meta_key
else:
path = "foo"
mkey = meta_root + path + ".group.json"
init_group(store, path=path)
# check metadata
assert mkey in store
meta = store._metadata_class.decode_group_metadata(store[mkey])
if self.version == 2:
assert ZARR_FORMAT == meta["zarr_format"]
else:
assert meta == {"attributes": {}}
store.close()
def _test_init_group_overwrite(self, order):
if self.version == 3:
pytest.skip("In v3 array and group names cannot overlap")
# setup
store = self.create_store()
store[array_meta_key] = store._metadata_class.encode_array_metadata(
dict(
shape=(2000,),
chunks=(200,),
dtype=np.dtype("u1"),
compressor=None,
fill_value=0,
order=order,
filters=None,
)
)
# don't overwrite array (default)
with pytest.raises(ContainsArrayError):
init_group(store)
# do overwrite
try:
init_group(store, overwrite=True)
except NotImplementedError:
pass
else:
assert array_meta_key not in store
assert group_meta_key in store
meta = store._metadata_class.decode_group_metadata(store[group_meta_key])
assert ZARR_FORMAT == meta["zarr_format"]
# don't overwrite group
with pytest.raises(ValueError):
init_group(store)
store.close()
def _test_init_group_overwrite_path(self, order):
# setup
path = "foo/bar"
store = self.create_store()
if self.version == 2:
meta = dict(
shape=(2000,),
chunks=(200,),
dtype=np.dtype("u1"),
compressor=None,
fill_value=0,
order=order,
filters=None,
)
array_key = path + "/" + array_meta_key
group_key = path + "/" + group_meta_key
else:
meta = dict(
shape=(2000,),
chunk_grid=dict(type="regular", chunk_shape=(200,), separator=("/")),
data_type=np.dtype("u1"),
compressor=None,
fill_value=0,
filters=None,
chunk_memory_layout=order,
)
array_key = meta_root + path + ".array.json"
group_key = meta_root + path + ".group.json"
store[array_key] = store._metadata_class.encode_array_metadata(meta)
# don't overwrite
with pytest.raises(ValueError):
init_group(store, path=path)
# do overwrite
try:
init_group(store, overwrite=True, path=path)
except NotImplementedError:
pass
else:
if self.version == 2:
assert array_meta_key not in store
assert group_meta_key in store
assert array_key not in store
assert group_key in store
# should have been overwritten
meta = store._metadata_class.decode_group_metadata(store[group_key])
if self.version == 2:
assert ZARR_FORMAT == meta["zarr_format"]
else:
assert meta == {"attributes": {}}
store.close()
def _test_init_group_overwrite_chunk_store(self, order):
if self.version == 3:
pytest.skip("In v3 array and group names cannot overlap")
# setup
store = self.create_store()
chunk_store = self.create_store()
store[array_meta_key] = store._metadata_class.encode_array_metadata(
dict(
shape=(2000,),
chunks=(200,),
dtype=np.dtype("u1"),
compressor=None,
fill_value=0,
filters=None,
order=order,
)
)
chunk_store["foo"] = b"bar"
chunk_store["baz"] = b"quux"
# don't overwrite array (default)
with pytest.raises(ValueError):
init_group(store, chunk_store=chunk_store)
# do overwrite
try:
init_group(store, overwrite=True, chunk_store=chunk_store)
except NotImplementedError:
pass
else:
assert array_meta_key not in store
assert group_meta_key in store
meta = store._metadata_class.decode_group_metadata(store[group_meta_key])
assert ZARR_FORMAT == meta["zarr_format"]
assert "foo" not in chunk_store
assert "baz" not in chunk_store
# don't overwrite group
with pytest.raises(ValueError):
init_group(store)
store.close()
chunk_store.close()
class TestMappingStore(StoreTests):
def create_store(self, **kwargs):
skip_if_nested_chunks(**kwargs)
return KVStore(dict())
def test_set_invalid_content(self):
# Generic mappings support non-buffer types
pass
def setdel_hierarchy_checks(store, root=""):
# these tests are for stores that are aware of hierarchy levels; this
# behaviour is not strictly required by Zarr but these tests are included
# to define behaviour of MemoryStore and DirectoryStore classes
# check __setitem__ and __delitem__ blocked by leaf
store[root + "a/b"] = b"aaa"
with pytest.raises(KeyError):
store[root + "a/b/c"] = b"xxx"
with pytest.raises(KeyError):
del store[root + "a/b/c"]
store[root + "d"] = b"ddd"
with pytest.raises(KeyError):
store[root + "d/e/f"] = b"xxx"
with pytest.raises(KeyError):
del store[root + "d/e/f"]
# test __setitem__ overwrite level
store[root + "x/y/z"] = b"xxx"
store[root + "x/y"] = b"yyy"
assert b"yyy" == ensure_bytes(store[root + "x/y"])
assert root + "x/y/z" not in store
store[root + "x"] = b"zzz"
assert b"zzz" == ensure_bytes(store[root + "x"])
assert root + "x/y" not in store
# test __delitem__ overwrite level
store[root + "r/s/t"] = b"xxx"
del store[root + "r/s"]
assert root + "r/s/t" not in store
store[root + "r/s"] = b"xxx"
del store[root + "r"]
assert root + "r/s" not in store
class TestMemoryStore(StoreTests):
def create_store(self, **kwargs):
skip_if_nested_chunks(**kwargs)
return MemoryStore(**kwargs)
def test_store_contains_bytes(self):
store = self.create_store()
store[self.root + "foo"] = np.array([97, 98, 99, 100, 101], dtype=np.uint8)
assert store[self.root + "foo"] == b"abcde"
def test_setdel(self):
store = self.create_store()
setdel_hierarchy_checks(store, self.root)
class TestDictStore(StoreTests):
def create_store(self, **kwargs):
skip_if_nested_chunks(**kwargs)