Skip to content

Commit 3ee6e11

Browse files
committed
increase test coverage
1 parent ff4111b commit 3ee6e11

File tree

7 files changed

+211
-91
lines changed

7 files changed

+211
-91
lines changed

zarr/compat.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,13 @@
99

1010
if PY2: # pragma: no cover
1111

12-
def itervalues(d, **kw):
13-
return d.itervalues(**kw)
14-
1512
text_type = unicode
1613
binary_type = str
1714
integer_types = (int, long)
1815
reduce = reduce
1916

2017
else:
2118

22-
def itervalues(d, **kw):
23-
return iter(d.values(**kw))
24-
2519
text_type = str
2620
binary_type = bytes
2721
integer_types = int,

zarr/core.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,10 +82,6 @@ def __init__(self, store, path=None, readonly=False):
8282
self._key_prefix = ''
8383
self._readonly = readonly
8484

85-
# guard conditions
86-
if contains_group(store, path=self._path):
87-
raise ValueError('store contains a group')
88-
8985
# initialise metadata
9086
try:
9187
mkey = self._key_prefix + array_meta_key

zarr/creation.py

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -320,33 +320,42 @@ def open_array(path, mode='a', shape=None, chunks=None, dtype=None,
320320
# w- or x : create, fail if exists
321321
# a : read/write if exists, create otherwise (default)
322322

323-
# ensure directory exists
324-
# TODO is this needed any more? DirectoryStore creates directory on demand
325-
if not os.path.exists(path):
326-
if mode in ['w', 'w-', 'x', 'a']:
327-
os.makedirs(path)
328-
elif mode in ['r', 'r+']:
329-
raise ValueError('path does not exist: %r' % path)
330-
331323
# setup store
332324
store = DirectoryStore(path)
333325

334-
# store can either hold array or group, not both
335-
if contains_group(store):
336-
raise ValueError('path contains group')
326+
# ensure store is initialized
337327

338-
exists = contains_array(store)
328+
if mode in ['r', 'r+']:
329+
if contains_group(store):
330+
raise ValueError('store contains group')
331+
elif not contains_array(store):
332+
raise ValueError('array does not exist')
339333

340-
# ensure store is initialized
341-
if mode in ['r', 'r+'] and not exists:
342-
raise ValueError('array does not exist')
343-
elif mode in ['w-', 'x'] and exists:
344-
raise ValueError('array exists')
345-
elif mode == 'w' or (mode in ['a', 'w-', 'x'] and not exists):
334+
elif mode == 'w':
346335
init_array(store, shape=shape, chunks=chunks, dtype=dtype,
347336
compression=compression, compression_opts=compression_opts,
348337
fill_value=fill_value, order=order, overwrite=True)
349338

339+
elif mode == 'a':
340+
if contains_group(store):
341+
raise ValueError('store contains group')
342+
elif not contains_array(store):
343+
init_array(store, shape=shape, chunks=chunks, dtype=dtype,
344+
compression=compression,
345+
compression_opts=compression_opts,
346+
fill_value=fill_value, order=order)
347+
348+
elif mode in ['w-', 'x']:
349+
if contains_group(store):
350+
raise ValueError('store contains group')
351+
elif contains_array(store):
352+
raise ValueError('store contains array')
353+
else:
354+
init_array(store, shape=shape, chunks=chunks, dtype=dtype,
355+
compression=compression,
356+
compression_opts=compression_opts,
357+
fill_value=fill_value, order=order)
358+
350359
# determine readonly status
351360
readonly = mode == 'r'
352361

zarr/tests/test_core.py

Lines changed: 99 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,14 @@
66
import shutil
77
import pickle
88
import os
9+
from collections import OrderedDict
910

1011

1112
import numpy as np
1213
from numpy.testing import assert_array_equal
1314
from nose.tools import eq_ as eq, assert_is_instance, \
14-
assert_raises, assert_true, assert_false
15-
from zarr.storage import DirectoryStore, ZipStore, init_array
15+
assert_raises, assert_true, assert_false, assert_is, assert_is_none
16+
from zarr.storage import DirectoryStore, ZipStore, init_array, init_group
1617

1718

1819
from zarr.core import Array
@@ -22,44 +23,99 @@
2223
class TestArray(unittest.TestCase):
2324

2425
def test_array_init(self):
25-
store = dict() # store not initialised
26+
27+
# normal initialization
28+
store = dict()
29+
init_array(store, shape=100, chunks=10)
30+
a = Array(store)
31+
assert_is_instance(a, Array)
32+
eq((100,), a.shape)
33+
eq((10,), a.chunks)
34+
eq('', a.path)
35+
assert_is_none(a.name)
36+
assert_is(store, a.store)
37+
38+
# initialize at path
39+
store = dict()
40+
init_array(store, shape=100, chunks=10, path='foo/bar')
41+
a = Array(store, path='foo/bar')
42+
assert_is_instance(a, Array)
43+
eq((100,), a.shape)
44+
eq((10,), a.chunks)
45+
eq('foo/bar', a.path)
46+
eq('/foo/bar', a.name)
47+
assert_is(store, a.store)
48+
49+
# store not initialized
50+
store = dict()
2651
with assert_raises(ValueError):
2752
Array(store)
2853

54+
# group is in the way
55+
store = dict()
56+
init_group(store, path='baz')
57+
with assert_raises(ValueError):
58+
Array(store, path='baz')
59+
2960
@staticmethod
30-
def create_array(store=None, readonly=False, **kwargs):
61+
def create_array(store=None, path=None, readonly=False, **kwargs):
3162
if store is None:
3263
store = dict()
33-
init_array(store, **kwargs)
34-
return Array(store, readonly=readonly)
64+
init_array(store, path=path, **kwargs)
65+
return Array(store, path=path, readonly=readonly)
3566

3667
def test_nbytes_stored(self):
3768

69+
# custom store, does not implement getsize()
70+
class CustomMapping(object):
71+
def __init__(self):
72+
self.inner = dict()
73+
74+
def __getitem__(self, item):
75+
return self.inner[item]
76+
77+
def __setitem__(self, item, value):
78+
self.inner[item] = value
79+
80+
def __contains__(self, item):
81+
return item in self.inner
82+
83+
store = CustomMapping()
84+
z = self.create_array(store=store, shape=1000, chunks=100)
85+
eq(-1, z.nbytes_stored)
86+
z[:] = 42
87+
eq(-1, z.nbytes_stored)
88+
89+
# dict as store
3890
store = dict()
3991
z = self.create_array(store=store, shape=1000, chunks=100)
4092
eq(sum(len(v) for v in store.values()), z.nbytes_stored)
4193
z[:] = 42
4294
eq(sum(len(v) for v in store.values()), z.nbytes_stored)
95+
# mess with store
96+
store['foo'] = list(range(10))
97+
eq(-1, z.nbytes_stored)
98+
99+
# for comparison
100+
z = self.create_array(store=dict(), shape=1000, chunks=100,
101+
compression='zlib', compression_opts=1)
102+
z[:] = 42
43103

44104
# DirectoryStore
45105
path = mkdtemp()
46106
atexit.register(shutil.rmtree, path)
47107
store = DirectoryStore(path)
48-
z = self.create_array(store=store, shape=1000, chunks=100,
49-
compression='zlib', compression_opts=1,
50-
fill_value=0)
51-
eq(sum(len(v) for v in store.values()), z.nbytes_stored)
52-
z[:] = 42
53-
eq(sum(len(v) for v in store.values()), z.nbytes_stored)
108+
zz = self.create_array(store=store, shape=1000, chunks=100,
109+
compression='zlib', compression_opts=1)
110+
zz[:] = 42
111+
eq(z.nbytes_stored, zz.nbytes_stored)
54112

55113
# ZipStore
56114
if os.path.exists('test.zip'):
57115
os.remove('test.zip')
58116
store = ZipStore('test.zip')
59-
z = self.create_array(store=store, shape=1000, chunks=100,
60-
compression='zlib', compression_opts=1,
61-
fill_value=0)
62-
zz = Array(store)
117+
zz = self.create_array(store=store, shape=1000, chunks=100,
118+
compression='zlib', compression_opts=1)
63119
zz[:] = 42
64120
eq(z.nbytes_stored, zz.nbytes_stored)
65121

@@ -454,3 +510,30 @@ def test_pickle(self):
454510
eq(z.compression_opts, z2.compression_opts)
455511
eq(z.fill_value, z2.fill_value)
456512
assert_array_equal(z[:], z2[:])
513+
514+
def test_repr(self):
515+
516+
# no path
517+
z = self.create_array(shape=100, chunks=10, dtype='f4',
518+
compression='zlib', compression_opts=1)
519+
expect = """zarr.core.Array((100,), float32, chunks=(10,), order=C)
520+
compression: zlib; compression_opts: 1
521+
nbytes: 400; nbytes_stored: 210; ratio: 1.9; initialized: 0/10
522+
store: builtins.dict
523+
"""
524+
actual = repr(z)
525+
for l1, l2 in zip(expect.split('\n'), actual.split('\n')):
526+
eq(l1, l2)
527+
528+
# with path
529+
z = self.create_array(path='foo/bar', shape=100, chunks=10, dtype='f4',
530+
compression='zlib', compression_opts=1)
531+
# flake8: noqa
532+
expect = """zarr.core.Array(/foo/bar, (100,), float32, chunks=(10,), order=C)
533+
compression: zlib; compression_opts: 1
534+
nbytes: 400; nbytes_stored: 210; ratio: 1.9; initialized: 0/10
535+
store: builtins.dict
536+
"""
537+
actual = repr(z)
538+
for l1, l2 in zip(expect.split('\n'), actual.split('\n')):
539+
eq(l1, l2)

zarr/tests/test_creation.py

Lines changed: 62 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@
1212
from numpy.testing import assert_array_equal
1313

1414

15-
from zarr.creation import array, empty, zeros, ones, full, open, empty_like, \
16-
zeros_like, ones_like, full_like, open_like, create
15+
from zarr.creation import array, empty, zeros, ones, full, open_array, \
16+
empty_like, zeros_like, ones_like, full_like, open_like, create
1717
from zarr.sync import ThreadSynchronizer, SynchronizedArray
1818
from zarr.core import Array
1919
from zarr.storage import DirectoryStore, init_array
20+
from zarr.hierarchy import open_group
21+
from zarr.errors import ReadOnlyError
2022

2123

2224
def test_array():
@@ -93,45 +95,72 @@ def test_full():
9395
assert_array_equal(np.full(100, fill_value=42, dtype='i4'), z[:])
9496

9597

96-
def test_open():
98+
def test_open_array():
9799

98-
path = tempfile.mktemp()
99-
atexit.register(
100-
lambda: shutil.rmtree(path) if os.path.exists(path) else None
101-
)
102-
z = open(path, mode='w', shape=100, chunks=10, dtype='i4')
100+
path = 'example'
101+
102+
# mode == 'w'
103+
z = open_array(path, mode='w', shape=100, chunks=10)
103104
z[:] = 42
105+
assert_is_instance(z, Array)
106+
assert_is_instance(z.store, DirectoryStore)
104107
eq((100,), z.shape)
105108
eq((10,), z.chunks)
106-
assert_array_equal(np.full(100, fill_value=42, dtype='i4'), z[:])
107-
z2 = open(path, mode='r')
108-
eq((100,), z2.shape)
109-
eq((10,), z2.chunks)
110-
assert_array_equal(z[:], z2[:])
111-
112-
# path does not exist
113-
path = 'doesnotexist'
114-
with assert_raises(ValueError):
115-
open(path, mode='r')
116-
117-
# path exists but store not initialised
118-
path = tempfile.mkdtemp()
119-
atexit.register(shutil.rmtree, path)
120-
with assert_raises(ValueError):
121-
open(path, mode='r')
122-
with assert_raises(ValueError):
123-
open(path, mode='r+')
109+
assert_array_equal(np.full(100, fill_value=42), z[:])
110+
111+
# mode in 'r', 'r+'
112+
open_group('example_group', mode='w')
113+
for mode in 'r', 'r+':
114+
with assert_raises(ValueError):
115+
open_array('doesnotexist', mode=mode)
116+
with assert_raises(ValueError):
117+
open_array('example_group', mode=mode)
118+
z = open_array(path, mode='r')
119+
assert_is_instance(z, Array)
120+
assert_is_instance(z.store, DirectoryStore)
121+
eq((100,), z.shape)
122+
eq((10,), z.chunks)
123+
assert_array_equal(np.full(100, fill_value=42), z[:])
124+
with assert_raises(ReadOnlyError):
125+
z[:] = 43
126+
z = open_array(path, mode='r+')
127+
assert_is_instance(z, Array)
128+
assert_is_instance(z.store, DirectoryStore)
129+
eq((100,), z.shape)
130+
eq((10,), z.chunks)
131+
assert_array_equal(np.full(100, fill_value=42), z[:])
132+
z[:] = 43
133+
assert_array_equal(np.full(100, fill_value=43), z[:])
124134

125-
# store initialised, mode w-
126-
store = DirectoryStore(path)
127-
init_array(store, shape=100, chunks=10)
128-
with assert_raises(ValueError):
129-
open(path, mode='w-')
135+
# mode == 'a'
136+
shutil.rmtree(path)
137+
z = open_array(path, mode='a', shape=100, chunks=10)
138+
z[:] = 42
139+
assert_is_instance(z, Array)
140+
assert_is_instance(z.store, DirectoryStore)
141+
eq((100,), z.shape)
142+
eq((10,), z.chunks)
143+
assert_array_equal(np.full(100, fill_value=42), z[:])
130144
with assert_raises(ValueError):
131-
open(path, mode='x')
145+
open_array('example_group', mode='a')
146+
147+
# mode in 'w-', 'x'
148+
for mode in 'w-', 'x':
149+
shutil.rmtree(path)
150+
z = open_array(path, mode=mode, shape=100, chunks=10)
151+
z[:] = 42
152+
assert_is_instance(z, Array)
153+
assert_is_instance(z.store, DirectoryStore)
154+
eq((100,), z.shape)
155+
eq((10,), z.chunks)
156+
assert_array_equal(np.full(100, fill_value=42), z[:])
157+
with assert_raises(ValueError):
158+
open_array(path, mode=mode)
159+
with assert_raises(ValueError):
160+
open_array('example_group', mode=mode)
132161

133162
# with synchronizer
134-
z = open(path, synchronizer=ThreadSynchronizer())
163+
z = open_array(path, synchronizer=ThreadSynchronizer())
135164
assert_is_instance(z, SynchronizedArray)
136165

137166

0 commit comments

Comments
 (0)