/
test_hierarchy.py
1949 lines (1680 loc) · 62 KB
/
test_hierarchy.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 atexit
import operator
import os
import sys
import pickle
import shutil
import tempfile
import textwrap
import unittest
import numpy as np
import pytest
try:
import ipytree
except ImportError: # pragma: no cover
ipytree = None
from numcodecs import Zlib
from numpy.testing import assert_array_equal
from zarr._storage.store import _get_metadata_suffix, v3_api_available
from zarr.attrs import Attributes
from zarr.core import Array
from zarr.creation import open_array
from zarr.hierarchy import Group, group, open_group
from zarr.storage import (
ABSStore,
DBMStore,
KVStore,
DirectoryStore,
FSStore,
LMDBStore,
LRUStoreCache,
MemoryStore,
NestedDirectoryStore,
SQLiteStore,
ZipStore,
array_meta_key,
atexit_rmglob,
atexit_rmtree,
data_root,
group_meta_key,
init_array,
init_group,
meta_root,
)
from zarr._storage.v3 import (
ABSStoreV3,
KVStoreV3,
DirectoryStoreV3,
MemoryStoreV3,
FSStoreV3,
ZipStoreV3,
DBMStoreV3,
LMDBStoreV3,
SQLiteStoreV3,
LRUStoreCacheV3,
)
from zarr.util import InfoReporter, buffer_size
from zarr.tests.util import skip_test_env_var, have_fsspec, abs_container, mktemp
_VERSIONS = (2, 3) if v3_api_available else (2,)
# noinspection PyStatementEffect
class TestGroup(unittest.TestCase):
@staticmethod
def create_store():
# can be overridden in sub-classes
return KVStore(dict()), None
def create_group(
self, store=None, path=None, read_only=False, chunk_store=None, synchronizer=None
):
# can be overridden in sub-classes
if store is None:
store, chunk_store = self.create_store()
init_group(store, path=path, chunk_store=chunk_store)
g = Group(
store,
path=path,
read_only=read_only,
chunk_store=chunk_store,
synchronizer=synchronizer,
)
return g
def test_ipython_repr_methods(self):
g = self.create_group()
for method in [
"html",
"json",
"javascript",
"markdown",
"svg",
"png",
"jpeg",
"latex",
"pdf",
"mimebundle",
]:
assert operator.methodcaller(f"_repr_{method}_")(g) is None
with pytest.raises(AttributeError):
g._ipython_display_()
with pytest.raises(AttributeError):
g._ipython_canary_method_should_not_exist_()
def test_group_init_1(self):
store, chunk_store = self.create_store()
g = self.create_group(store, chunk_store=chunk_store)
assert store is g.store
if chunk_store is None:
assert store is g.chunk_store
else:
assert chunk_store is g.chunk_store
assert not g.read_only
assert "" == g.path
assert "/" == g.name
assert "" == g.basename
assert isinstance(g.attrs, Attributes)
g.attrs["foo"] = "bar"
assert g.attrs["foo"] == "bar"
assert isinstance(g.info, InfoReporter)
assert isinstance(repr(g.info), str)
assert isinstance(g.info._repr_html_(), str)
store.close()
def test_group_init_2(self):
store, chunk_store = self.create_store()
g = self.create_group(store, chunk_store=chunk_store, path="/foo/bar/", read_only=True)
assert store is g.store
assert g.read_only
assert "foo/bar" == g.path
assert "/foo/bar" == g.name
assert "bar" == g.basename
assert isinstance(g.attrs, Attributes)
store.close()
def test_group_init_errors_1(self):
store, chunk_store = self.create_store()
# group metadata not initialized
with pytest.raises(ValueError):
Group(store, chunk_store=chunk_store)
store.close()
def test_group_repr(self):
store, chunk_store = self.create_store()
g = self.create_group(store, chunk_store=chunk_store)
assert g.name in repr(g)
def test_group_init_errors_2(self):
store, chunk_store = self.create_store()
init_array(store, shape=1000, chunks=100, chunk_store=chunk_store)
# array blocks group
with pytest.raises(ValueError):
Group(store, chunk_store=chunk_store)
store.close()
def _subgroup_path(self, group, path):
path = path.rstrip("/")
group_path = "/".join([group.path, path])
group_path = group_path.lstrip("/")
group_name = "/" + group_path
return group_path, group_name
def test_create_group(self):
g1 = self.create_group()
if g1._version == 2:
path, name = "", "/"
else:
path, name = "group", "/group"
# check root group
assert path == g1.path
assert name == g1.name
# create level 1 child group
g2 = g1.create_group("foo")
# check with relative path
path, name = self._subgroup_path(g1, "foo")
assert isinstance(g2, Group)
assert path == g2.path
assert name == g2.name
# create level 2 child group
g3 = g2.create_group("bar")
path, name = self._subgroup_path(g2, "bar")
assert isinstance(g3, Group)
assert path == g3.path
assert name == g3.name
# create level 3 child group
g4 = g1.create_group("foo/bar/baz")
path, name = self._subgroup_path(g1, "foo/bar/baz")
assert isinstance(g4, Group)
assert path == g4.path
assert name == g4.name
# create level 3 group via root
g5 = g4.create_group("/a/b/c/")
assert isinstance(g5, Group)
assert "a/b/c" == g5.path
assert "/a/b/c" == g5.name
# test non-str keys
class Foo:
def __init__(self, s):
self.s = s
def __str__(self):
return self.s
o = Foo("test/object")
go = g1.create_group(o)
path, name = self._subgroup_path(g1, str(o))
assert isinstance(go, Group)
assert path == go.path
go = g1.create_group(b"test/bytes")
path, name = self._subgroup_path(g1, "test/bytes")
assert isinstance(go, Group)
assert path == go.path
# test bad keys
with pytest.raises(ValueError):
g1.create_group("foo") # already exists
if g1._version == 2:
with pytest.raises(ValueError):
g1.create_group("a/b/c") # already exists
elif g1._version == 3:
# for v3 'group/a/b/c' does not already exist
g1.create_group("a/b/c")
with pytest.raises(ValueError):
g4.create_group("/a/b/c") # already exists
with pytest.raises(ValueError):
g1.create_group("")
# multi
g6, g7 = g1.create_groups("y", "z")
assert isinstance(g6, Group)
assert g6.path == self._subgroup_path(g1, "y")[0]
assert isinstance(g7, Group)
assert g7.path == self._subgroup_path(g1, "z")[0]
g1.store.close()
def test_require_group(self):
g1 = self.create_group()
# test creation
g2 = g1.require_group("foo")
path, name = self._subgroup_path(g1, "foo")
assert isinstance(g2, Group)
assert path == g2.path
g3 = g2.require_group("bar")
path, name = self._subgroup_path(g2, "bar")
assert isinstance(g3, Group)
assert path == g3.path
g4 = g1.require_group("foo/bar/baz")
path, name = self._subgroup_path(g1, "foo/bar/baz")
assert isinstance(g4, Group)
assert path == g4.path
g5 = g4.require_group("/a/b/c/")
assert isinstance(g5, Group)
assert "a/b/c" == g5.path
# test when already created
g2a = g1.require_group("foo")
assert g2 == g2a
assert g2.store is g2a.store
g3a = g2a.require_group("bar")
assert g3 == g3a
assert g3.store is g3a.store
g4a = g1.require_group("foo/bar/baz")
assert g4 == g4a
assert g4.store is g4a.store
g5a = g4a.require_group("/a/b/c/")
assert g5 == g5a
assert g5.store is g5a.store
# test path normalization
if g1._version == 2:
assert g1.require_group("quux") == g1.require_group("/quux/")
elif g1._version:
# These are not equal in v3!
# 'quux' will be within the group:
# meta/root/group/quux.group.json
# '/quux/' will be outside of the group at:
# meta/root/quux.group.json
assert g1.require_group("quux") != g1.require_group("/quux/")
# multi
g6, g7 = g1.require_groups("y", "z")
assert isinstance(g6, Group)
assert g6.path == self._subgroup_path(g1, "y")[0]
assert isinstance(g7, Group)
assert g7.path == self._subgroup_path(g1, "z")[0]
g1.store.close()
def test_rmdir_group_and_array_metadata_files(self):
"""Test group.store's rmdir method.
This test case was added to complete test coverage of `ABSStore.rmdir`.
"""
g1 = self.create_group()
# create a dataset
g1.create_dataset("arr1", shape=(100,), chunks=(10,), dtype=np.uint8)
# create level 1 child group
g2 = g1.create_group("foo")
g1.create_dataset("arr2", shape=(100,), chunks=(10,), dtype=np.uint8)
if g1._version > 2 and g1.store.is_erasable():
arr_path = g1.path + "/arr1"
sfx = _get_metadata_suffix(g1.store)
array_meta_file = meta_root + arr_path + ".array" + sfx
assert array_meta_file in g1.store
group_meta_file = meta_root + g2.path + ".group" + sfx
assert group_meta_file in g1.store
# rmdir on the array path should also remove the metadata file
g1.store.rmdir(arr_path)
assert array_meta_file not in g1.store
# rmdir on the group path should also remove its metadata file
g1.store.rmdir(g2.path)
assert group_meta_file not in g1.store
def _dataset_path(self, group, path):
path = path.rstrip("/")
absolute = path.startswith("/")
if absolute:
dataset_path = path
else:
dataset_path = "/".join([group.path, path])
dataset_path = dataset_path.lstrip("/")
dataset_name = "/" + dataset_path
return dataset_path, dataset_name
def test_create_dataset(self):
g = self.create_group()
# create as immediate child
dpath = "foo"
d1 = g.create_dataset(dpath, shape=1000, chunks=100)
path, name = self._dataset_path(g, dpath)
assert isinstance(d1, Array)
assert (1000,) == d1.shape
assert (100,) == d1.chunks
assert path == d1.path
assert name == d1.name
assert g.store is d1.store
# create as descendant
dpath = "/a/b/c/"
d2 = g.create_dataset(
dpath,
shape=2000,
chunks=200,
dtype="i1",
compression="zlib",
compression_opts=9,
fill_value=42,
order="F",
)
path, name = self._dataset_path(g, dpath)
assert isinstance(d2, Array)
assert (2000,) == d2.shape
assert (200,) == d2.chunks
assert np.dtype("i1") == d2.dtype
assert "zlib" == d2.compressor.codec_id
assert 9 == d2.compressor.level
assert 42 == d2.fill_value
assert "F" == d2.order
assert path == d2.path
assert name == d2.name
assert g.store is d2.store
# create with data
data = np.arange(3000, dtype="u2")
dpath = "bar"
d3 = g.create_dataset(dpath, data=data, chunks=300)
path, name = self._dataset_path(g, dpath)
assert isinstance(d3, Array)
assert (3000,) == d3.shape
assert (300,) == d3.chunks
assert np.dtype("u2") == d3.dtype
assert_array_equal(data, d3[:])
assert path == d3.path
assert name == d3.name
assert g.store is d3.store
# compression arguments handling follows...
# compression_opts as dict
d = g.create_dataset(
"aaa",
shape=1000,
dtype="u1",
compression="blosc",
compression_opts=dict(cname="zstd", clevel=1, shuffle=2),
)
assert d.compressor.codec_id == "blosc"
assert "zstd" == d.compressor.cname
assert 1 == d.compressor.clevel
assert 2 == d.compressor.shuffle
# compression_opts as sequence
d = g.create_dataset(
"bbb", shape=1000, dtype="u1", compression="blosc", compression_opts=("zstd", 1, 2)
)
assert d.compressor.codec_id == "blosc"
assert "zstd" == d.compressor.cname
assert 1 == d.compressor.clevel
assert 2 == d.compressor.shuffle
# None compression_opts
d = g.create_dataset("ccc", shape=1000, dtype="u1", compression="zlib")
assert d.compressor.codec_id == "zlib"
assert 1 == d.compressor.level
# None compression
d = g.create_dataset("ddd", shape=1000, dtype="u1", compression=None)
assert d.compressor is None
# compressor as compression
d = g.create_dataset("eee", shape=1000, dtype="u1", compression=Zlib(1))
assert d.compressor.codec_id == "zlib"
assert 1 == d.compressor.level
g.store.close()
def test_require_dataset(self):
g = self.create_group()
# create
dpath = "foo"
d1 = g.require_dataset(dpath, shape=1000, chunks=100, dtype="f4")
d1[:] = np.arange(1000)
path, name = self._dataset_path(g, dpath)
assert isinstance(d1, Array)
assert (1000,) == d1.shape
assert (100,) == d1.chunks
assert np.dtype("f4") == d1.dtype
assert path == d1.path
assert name == d1.name
assert g.store is d1.store
assert_array_equal(np.arange(1000), d1[:])
# require
d2 = g.require_dataset(dpath, shape=1000, chunks=100, dtype="f4")
assert isinstance(d2, Array)
assert (1000,) == d2.shape
assert (100,) == d2.chunks
assert np.dtype("f4") == d2.dtype
assert path == d2.path
assert name == d2.name
assert g.store is d2.store
assert_array_equal(np.arange(1000), d2[:])
assert d1 == d2
# bad shape - use TypeError for h5py compatibility
with pytest.raises(TypeError):
g.require_dataset("foo", shape=2000, chunks=100, dtype="f4")
# dtype matching
# can cast
d3 = g.require_dataset("foo", shape=1000, chunks=100, dtype="i2")
assert np.dtype("f4") == d3.dtype
assert d1 == d3
with pytest.raises(TypeError):
# cannot cast
g.require_dataset("foo", shape=1000, chunks=100, dtype="i4")
with pytest.raises(TypeError):
# can cast but not exact match
g.require_dataset("foo", shape=1000, chunks=100, dtype="i2", exact=True)
g.store.close()
def test_create_errors(self):
g = self.create_group()
# array obstructs group, array
g.create_dataset("foo", shape=100, chunks=10)
with pytest.raises(ValueError):
g.create_group("foo/bar")
with pytest.raises(ValueError):
g.require_group("foo/bar")
with pytest.raises(ValueError):
g.create_dataset("foo/bar", shape=100, chunks=10)
with pytest.raises(ValueError):
g.require_dataset("foo/bar", shape=100, chunks=10)
# array obstructs group, array
g.create_dataset("a/b", shape=100, chunks=10)
with pytest.raises(ValueError):
g.create_group("a/b")
with pytest.raises(ValueError):
g.require_group("a/b")
with pytest.raises(ValueError):
g.create_dataset("a/b", shape=100, chunks=10)
# group obstructs array
g.create_group("c/d")
with pytest.raises(ValueError):
g.create_dataset("c", shape=100, chunks=10)
with pytest.raises(ValueError):
g.require_dataset("c", shape=100, chunks=10)
with pytest.raises(ValueError):
g.create_dataset("c/d", shape=100, chunks=10)
with pytest.raises(ValueError):
g.require_dataset("c/d", shape=100, chunks=10)
# h5py compatibility, accept 'fillvalue'
d = g.create_dataset("x", shape=100, chunks=10, fillvalue=42)
assert 42 == d.fill_value
# h5py compatibility, ignore 'shuffle'
with pytest.warns(UserWarning, match="ignoring keyword argument 'shuffle'"):
g.create_dataset("y", shape=100, chunks=10, shuffle=True)
# read-only
g = self.create_group(read_only=True)
with pytest.raises(PermissionError):
g.create_group("zzz")
with pytest.raises(PermissionError):
g.require_group("zzz")
with pytest.raises(PermissionError):
g.create_dataset("zzz", shape=100, chunks=10)
with pytest.raises(PermissionError):
g.require_dataset("zzz", shape=100, chunks=10)
g.store.close()
def test_create_overwrite(self):
try:
for method_name in "create_dataset", "create", "empty", "zeros", "ones":
g = self.create_group()
getattr(g, method_name)("foo", shape=100, chunks=10)
# overwrite array with array
d = getattr(g, method_name)("foo", shape=200, chunks=20, overwrite=True)
assert (200,) == d.shape
# overwrite array with group
g2 = g.create_group("foo", overwrite=True)
assert 0 == len(g2)
# overwrite group with array
d = getattr(g, method_name)("foo", shape=300, chunks=30, overwrite=True)
assert (300,) == d.shape
# overwrite array with group
d = getattr(g, method_name)("foo/bar", shape=400, chunks=40, overwrite=True)
assert (400,) == d.shape
assert isinstance(g["foo"], Group)
g.store.close()
except NotImplementedError:
pass
def test_getitem_contains_iterators(self):
# setup
g1 = self.create_group()
g2 = g1.create_group("foo/bar")
if g1._version == 2:
d1 = g2.create_dataset("/a/b/c", shape=1000, chunks=100)
else:
# v3: cannot create a dataset at the root by starting with /
# instead, need to create the dataset on g1 directly
d1 = g1.create_dataset("a/b/c", shape=1000, chunks=100)
d1[:] = np.arange(1000)
d2 = g1.create_dataset("foo/baz", shape=3000, chunks=300)
d2[:] = np.arange(3000)
# test __getitem__
assert isinstance(g1["foo"], Group)
assert isinstance(g1["foo"]["bar"], Group)
assert isinstance(g1["foo/bar"], Group)
if g1._version == 2:
assert isinstance(g1["/foo/bar/"], Group)
else:
# start or end with / raises KeyError
# TODO: should we allow stripping of these on v3?
with pytest.raises(KeyError):
assert isinstance(g1["/foo/bar/"], Group)
assert isinstance(g1["foo/baz"], Array)
assert g2 == g1["foo/bar"]
assert g1["foo"]["bar"] == g1["foo/bar"]
assert d2 == g1["foo/baz"]
assert_array_equal(d2[:], g1["foo/baz"])
assert isinstance(g1["a"], Group)
assert isinstance(g1["a"]["b"], Group)
assert isinstance(g1["a/b"], Group)
assert isinstance(g1["a"]["b"]["c"], Array)
assert isinstance(g1["a/b/c"], Array)
assert d1 == g1["a/b/c"]
assert g1["a"]["b"]["c"] == g1["a/b/c"]
assert_array_equal(d1[:], g1["a/b/c"][:])
# test __contains__
assert "foo" in g1
assert "foo/bar" in g1
assert "foo/baz" in g1
assert "bar" in g1["foo"]
assert "a" in g1
assert "a/b" in g1
assert "a/b/c" in g1
assert "baz" not in g1
assert "a/b/c/d" not in g1
assert "a/z" not in g1
assert "quux" not in g1["foo"]
# test key errors
with pytest.raises(KeyError):
g1["baz"]
with pytest.raises(KeyError):
g1["x/y/z"]
# test __len__
assert 2 == len(g1)
assert 2 == len(g1["foo"])
assert 0 == len(g1["foo/bar"])
assert 1 == len(g1["a"])
assert 1 == len(g1["a/b"])
# test __iter__, keys()
if g1._version == 2:
# currently assumes sorted by key
assert ["a", "foo"] == list(g1)
assert ["a", "foo"] == list(g1.keys())
assert ["bar", "baz"] == list(g1["foo"])
assert ["bar", "baz"] == list(g1["foo"].keys())
else:
# v3 is not necessarily sorted by key
assert ["a", "foo"] == sorted(list(g1))
assert ["a", "foo"] == sorted(list(g1.keys()))
assert ["bar", "baz"] == sorted(list(g1["foo"]))
assert ["bar", "baz"] == sorted(list(g1["foo"].keys()))
assert [] == sorted(g1["foo/bar"])
assert [] == sorted(g1["foo/bar"].keys())
# test items(), values()
# currently assumes sorted by key
items = list(g1.items())
values = list(g1.values())
if g1._version == 3:
# v3 are not automatically sorted by key
items, values = zip(*sorted(zip(items, values), key=lambda x: x[0]))
assert "a" == items[0][0]
assert g1["a"] == items[0][1]
assert g1["a"] == values[0]
assert "foo" == items[1][0]
assert g1["foo"] == items[1][1]
assert g1["foo"] == values[1]
items = list(g1["foo"].items())
values = list(g1["foo"].values())
if g1._version == 3:
# v3 are not automatically sorted by key
items, values = zip(*sorted(zip(items, values), key=lambda x: x[0]))
assert "bar" == items[0][0]
assert g1["foo"]["bar"] == items[0][1]
assert g1["foo"]["bar"] == values[0]
assert "baz" == items[1][0]
assert g1["foo"]["baz"] == items[1][1]
assert g1["foo"]["baz"] == values[1]
# test array_keys(), arrays(), group_keys(), groups()
groups = list(g1.groups())
arrays = list(g1.arrays())
if g1._version == 2:
# currently assumes sorted by key
assert ["a", "foo"] == list(g1.group_keys())
else:
assert ["a", "foo"] == sorted(list(g1.group_keys()))
groups = sorted(groups)
arrays = sorted(arrays)
assert "a" == groups[0][0]
assert g1["a"] == groups[0][1]
assert "foo" == groups[1][0]
assert g1["foo"] == groups[1][1]
assert [] == list(g1.array_keys())
assert [] == arrays
assert ["bar"] == list(g1["foo"].group_keys())
assert ["baz"] == list(g1["foo"].array_keys())
groups = list(g1["foo"].groups())
arrays = list(g1["foo"].arrays())
if g1._version == 3:
groups = sorted(groups)
arrays = sorted(arrays)
assert "bar" == groups[0][0]
assert g1["foo"]["bar"] == groups[0][1]
assert "baz" == arrays[0][0]
assert g1["foo"]["baz"] == arrays[0][1]
# visitor collection tests
items = []
def visitor2(obj):
items.append(obj.path)
# noinspection PyUnusedLocal
def visitor3(name, obj=None):
items.append(name)
def visitor4(name, obj):
items.append((name, obj))
del items[:]
g1.visitvalues(visitor2)
expected_items = [
"a",
"a/b",
"a/b/c",
"foo",
"foo/bar",
"foo/baz",
]
if g1._version == 3:
expected_items = [g1.path + "/" + i for i in expected_items]
assert expected_items == items
del items[:]
g1["foo"].visitvalues(visitor2)
expected_items = [
"foo/bar",
"foo/baz",
]
if g1._version == 3:
expected_items = [g1.path + "/" + i for i in expected_items]
assert expected_items == items
del items[:]
g1.visit(visitor3)
assert [
"a",
"a/b",
"a/b/c",
"foo",
"foo/bar",
"foo/baz",
] == items
del items[:]
g1["foo"].visit(visitor3)
assert [
"bar",
"baz",
] == items
del items[:]
g1.visitkeys(visitor3)
assert [
"a",
"a/b",
"a/b/c",
"foo",
"foo/bar",
"foo/baz",
] == items
del items[:]
g1["foo"].visitkeys(visitor3)
assert [
"bar",
"baz",
] == items
del items[:]
g1.visititems(visitor3)
assert [
"a",
"a/b",
"a/b/c",
"foo",
"foo/bar",
"foo/baz",
] == items
del items[:]
g1["foo"].visititems(visitor3)
assert [
"bar",
"baz",
] == items
del items[:]
g1.visititems(visitor4)
for n, o in items:
assert g1[n] == o
del items[:]
g1["foo"].visititems(visitor4)
for n, o in items:
assert g1["foo"][n] == o
# visitor filter tests
# noinspection PyUnusedLocal
def visitor0(val, *args):
name = getattr(val, "path", val)
if name == "a/b/c/d":
return True # pragma: no cover
# noinspection PyUnusedLocal
def visitor1(val, *args):
name = getattr(val, "path", val)
if name.startswith("group/"):
# strip the group path for v3
name = name[6:]
if name == "a/b/c":
return True
assert g1.visit(visitor0) is None
assert g1.visitkeys(visitor0) is None
assert g1.visitvalues(visitor0) is None
assert g1.visititems(visitor0) is None
assert g1.visit(visitor1) is True
assert g1.visitkeys(visitor1) is True
assert g1.visitvalues(visitor1) is True
assert g1.visititems(visitor1) is True
g1.store.close()
# regression test for https://github.com/zarr-developers/zarr-python/issues/1228
def test_double_counting_group_v3(self):
root_group = self.create_group()
group_names = ["foo", "foo-", "foo_"]
for name in group_names:
sub_group = root_group.create_group(name)
sub_group.create("bar", shape=10, dtype="i4")
assert list(root_group.group_keys()) == sorted(group_names)
assert list(root_group.groups()) == [
(name, root_group[name]) for name in sorted(group_names)
]
def test_empty_getitem_contains_iterators(self):
# setup
g = self.create_group()
# test
assert [] == list(g)
assert [] == list(g.keys())
assert 0 == len(g)
assert "foo" not in g
g.store.close()
def test_iterators_recurse(self):
# setup
g1 = self.create_group()
g2 = g1.create_group("foo/bar")
d1 = g2.create_dataset("/a/b/c", shape=1000, chunks=100)
d1[:] = np.arange(1000)
d2 = g1.create_dataset("foo/baz", shape=3000, chunks=300)
d2[:] = np.arange(3000)
d3 = g2.create_dataset("zab", shape=2000, chunks=200)
d3[:] = np.arange(2000)
# test recursive array_keys
array_keys = list(g1["foo"].array_keys(recurse=False))
array_keys_recurse = list(g1["foo"].array_keys(recurse=True))
assert len(array_keys_recurse) > len(array_keys)
assert sorted(array_keys_recurse) == ["baz", "zab"]
# test recursive arrays
arrays = list(g1["foo"].arrays(recurse=False))
arrays_recurse = list(g1["foo"].arrays(recurse=True))
assert len(arrays_recurse) > len(arrays)
assert "zab" == arrays_recurse[0][0]
assert g1["foo"]["bar"]["zab"] == arrays_recurse[0][1]
g1.store.close()
def test_getattr(self):
# setup
g1 = self.create_group()
g2 = g1.create_group("foo")
g2.create_dataset("bar", shape=100)
# test
assert g1["foo"] == g1.foo
assert g2["bar"] == g2.bar
# test that hasattr returns False instead of an exception (issue #88)
assert not hasattr(g1, "unexistingattribute")
g1.store.close()
def test_setitem(self):
g = self.create_group()
try:
data = np.arange(100)
g["foo"] = data
assert_array_equal(data, g["foo"])
data = np.arange(200)
g["foo"] = data
assert_array_equal(data, g["foo"])
# 0d array
g["foo"] = 42
assert () == g["foo"].shape
assert 42 == g["foo"][()]
except NotImplementedError:
pass
g.store.close()
def test_delitem(self):
g = self.create_group()
g.create_group("foo")
g.create_dataset("bar/baz", shape=100, chunks=10)
assert "foo" in g
assert "bar" in g
assert "bar/baz" in g
try:
del g["bar"]
with pytest.raises(KeyError):
del g["xxx"]
except NotImplementedError:
pass
else:
assert "foo" in g
assert "bar" not in g
assert "bar/baz" not in g
g.store.close()
def test_move(self):
g = self.create_group()
data = np.arange(100)
g["boo"] = data
data = np.arange(100)
g["foo"] = data
g.move("foo", "bar")
assert "foo" not in g
assert "bar" in g
assert_array_equal(data, g["bar"])
g.move("bar", "foo/bar")
assert "bar" not in g
assert "foo" in g
assert "foo/bar" in g
assert isinstance(g["foo"], Group)
assert_array_equal(data, g["foo/bar"])
g.move("foo", "foo2")
assert "foo" not in g
assert "foo/bar" not in g
assert "foo2" in g
assert "foo2/bar" in g
assert isinstance(g["foo2"], Group)
assert_array_equal(data, g["foo2/bar"])
g2 = g["foo2"]
g2.move("bar", "/bar")
assert "foo2" in g
assert "foo2/bar" not in g
if g2._version == 2:
assert "bar" in g
else:
# The `g2.move` call above moved bar to meta/root/bar and
# meta/data/bar. This is outside the `g` group located at
# /meta/root/group, so bar is no longer within `g`.
assert "bar" not in g
assert "meta/root/bar.array.json" in g._store
if g._chunk_store:
assert "data/root/bar/c0" in g._chunk_store
else:
assert "data/root/bar/c0" in g._store
assert isinstance(g["foo2"], Group)
if g2._version == 2:
assert_array_equal(data, g["bar"])
else:
# TODO: How to access element created outside of group.path in v3?
# One option is to make a Hierarchy class representing the
# root. Currently Group requires specification of `path`,
# but the path of the root would be just '' which is not
# currently allowed.
pass
with pytest.raises(ValueError):
g2.move("bar", "bar2")
with pytest.raises(ValueError):
g.move("bar", "boo")
g.store.close()
def test_array_creation(self):
grp = self.create_group()
a = grp.create("a", shape=100, chunks=10)
assert isinstance(a, Array)
b = grp.empty("b", shape=100, chunks=10)
assert isinstance(b, Array)
assert b.fill_value is None
c = grp.zeros("c", shape=100, chunks=10)