Debian Codegraph @

tests/unit/utils_test/test_utils.py

raw
1 import os
2
3 import h5py
4 import numpy as np
5 from hdmf.data_utils import DataChunkIterator, DataIO
6 from hdmf.testing import TestCase
7 from hdmf.utils import get_data_shape, to_uint_array
8
9
10 class TestGetDataShape(TestCase):
11
12 def test_h5dataset(self):
13 """Test get_data_shape on h5py.Datasets of various shapes and maxshape."""
14 path = 'test_get_data_shape.h5'
15 with h5py.File(path, 'w') as f:
16 dset = f.create_dataset('data', data=((1, 2), (3, 4), (5, 6)))
17 res = get_data_shape(dset)
18 self.assertTupleEqual(res, (3, 2))
19
20 dset = f.create_dataset('shape', shape=(3, 2))
21 res = get_data_shape(dset)
22 self.assertTupleEqual(res, (3, 2))
23
24 # test that maxshape takes priority
25 dset = f.create_dataset('shape_maxshape', shape=(3, 2), maxshape=(None, 100))
26 res = get_data_shape(dset)
27 self.assertTupleEqual(res, (None, 100))
28
29 os.remove(path)
30
31 def test_dci(self):
32 """Test get_data_shape on DataChunkIterators of various shapes and maxshape."""
33 dci = DataChunkIterator(dtype=np.dtype(int))
34 res = get_data_shape(dci)
35 self.assertIsNone(res)
36
37 dci = DataChunkIterator(data=[1, 2])
38 res = get_data_shape(dci)
39 self.assertTupleEqual(res, (2, ))
40
41 dci = DataChunkIterator(data=[[1, 2], [3, 4], [5, 6]])
42 res = get_data_shape(dci)
43 self.assertTupleEqual(res, (3, 2))
44
45 # test that maxshape takes priority
46 dci = DataChunkIterator(data=[[1, 2], [3, 4], [5, 6]], maxshape=(None, 100))
47 res = get_data_shape(dci)
48 self.assertTupleEqual(res, (None, 100))
49
50 def test_dataio(self):
51 """Test get_data_shape on DataIO of various shapes and maxshape."""
52 dio = DataIO(data=[1, 2])
53 res = get_data_shape(dio)
54 self.assertTupleEqual(res, (2, ))
55
56 dio = DataIO(data=[[1, 2], [3, 4], [5, 6]])
57 res = get_data_shape(dio)
58 self.assertTupleEqual(res, (3, 2))
59
60 dio = DataIO(data=np.array([[1, 2], [3, 4], [5, 6]]))
61 res = get_data_shape(dio)
62 self.assertTupleEqual(res, (3, 2))
63
64 def test_list(self):
65 """Test get_data_shape on lists of various shapes."""
66 res = get_data_shape(list())
67 self.assertTupleEqual(res, (0, ))
68
69 res = get_data_shape([1, 2])
70 self.assertTupleEqual(res, (2, ))
71
72 res = get_data_shape([[1, 2], [3, 4], [5, 6]])
73 self.assertTupleEqual(res, (3, 2))
74
75 def test_tuple(self):
76 """Test get_data_shape on tuples of various shapes."""
77 res = get_data_shape(tuple())
78 self.assertTupleEqual(res, (0, ))
79
80 res = get_data_shape((1, 2))
81 self.assertTupleEqual(res, (2, ))
82
83 res = get_data_shape(((1, 2), (3, 4), (5, 6)))
84 self.assertTupleEqual(res, (3, 2))
85
86 def test_nparray(self):
87 """Test get_data_shape on numpy arrays of various shapes."""
88 res = get_data_shape(np.empty([]))
89 self.assertTupleEqual(res, tuple())
90
91 res = get_data_shape(np.array([]))
92 self.assertTupleEqual(res, (0, ))
93
94 res = get_data_shape(np.array([1, 2]))
95 self.assertTupleEqual(res, (2, ))
96
97 res = get_data_shape(np.array([[1, 2], [3, 4], [5, 6]]))
98 self.assertTupleEqual(res, (3, 2))
99
100 def test_other(self):
101 """Test get_data_shape on miscellaneous edge cases."""
102 res = get_data_shape(dict())
103 self.assertIsNone(res)
104
105 res = get_data_shape(None)
106 self.assertIsNone(res)
107
108 res = get_data_shape([None, None])
109 self.assertTupleEqual(res, (2, ))
110
111 res = get_data_shape(object())
112 self.assertIsNone(res)
113
114 res = get_data_shape([object(), object()])
115 self.assertTupleEqual(res, (2, ))
116
117 def test_string(self):
118 """Test get_data_shape on strings and collections of strings."""
119 res = get_data_shape('abc')
120 self.assertIsNone(res)
121
122 res = get_data_shape(('a', 'b'))
123 self.assertTupleEqual(res, (2, ))
124
125 res = get_data_shape((('a', 'b'), ('c', 'd'), ('e', 'f')))
126 self.assertTupleEqual(res, (3, 2))
127
128 def test_set(self):
129 """Test get_data_shape on sets, which have __len__ but are not subscriptable."""
130 res = get_data_shape(set())
131 self.assertTupleEqual(res, (0, ))
132
133 res = get_data_shape({1, 2})
134 self.assertTupleEqual(res, (2, ))
135
136 def test_arbitrary_iterable_with_len(self):
137 """Test get_data_shape with strict_no_data_load=True on an arbitrary iterable object with __len__."""
138
139 class MyIterable:
140 """Iterable class without shape or maxshape, where loading the first element raises an error."""
141
142 def __len__(self):
143 return 10
144
145 def __iter__(self):
146 return self
147
148 def __next__(self):
149 raise DataLoadedError()
150
151 class DataLoadedError(Exception):
152 pass
153
154 data = MyIterable()
155 with self.assertRaises(DataLoadedError):
156 get_data_shape(data) # test that data is loaded
157
158 res = get_data_shape(data, strict_no_data_load=True) # no error raised means data was not loaded
159 self.assertIsNone(res)
160
161 def test_strict_no_data_load(self):
162 """Test get_data_shape with strict_no_data_load=True on nested lists/tuples is the same as when it is False."""
163 res = get_data_shape([[1, 2], [3, 4], [5, 6]], strict_no_data_load=True)
164 self.assertTupleEqual(res, (3, 2))
165
166 res = get_data_shape(((1, 2), (3, 4), (5, 6)), strict_no_data_load=True)
167 self.assertTupleEqual(res, (3, 2))
168
169
170 class TestToUintArray(TestCase):
171
172 def test_ndarray_uint(self):
173 arr = np.array([0, 1, 2], dtype=np.uint32)
174 res = to_uint_array(arr)
175 np.testing.assert_array_equal(res, arr)
176
177 def test_ndarray_int(self):
178 arr = np.array([0, 1, 2], dtype=np.int32)
179 res = to_uint_array(arr)
180 np.testing.assert_array_equal(res, arr)
181
182 def test_ndarray_int_neg(self):
183 arr = np.array([0, -1, 2], dtype=np.int32)
184 with self.assertRaisesWith(ValueError, 'Cannot convert negative integer values to uint.'):
185 to_uint_array(arr)
186
187 def test_ndarray_float(self):
188 arr = np.array([0, 1, 2], dtype=np.float64)
189 with self.assertRaisesWith(ValueError, 'Cannot convert array of dtype float64 to uint.'):
190 to_uint_array(arr)
191
192 def test_list_int(self):
193 arr = [0, 1, 2]
194 res = to_uint_array(arr)
195 expected = np.array([0, 1, 2], dtype=np.uint32)
196 np.testing.assert_array_equal(res, expected)
197
198 def test_list_int_neg(self):
199 arr = [0, -1, 2]
200 with self.assertRaisesWith(ValueError, 'Cannot convert negative integer values to uint.'):
201 to_uint_array(arr)
202
203 def test_list_float(self):
204 arr = [0., 1., 2.]
205 with self.assertRaisesWith(ValueError, 'Cannot convert array of dtype float64 to uint.'):
206 to_uint_array(arr)