| 1 |
"""Test module to validate that HDF5IO is working""" |
| 2 |
import os |
| 3 |
import unittest |
| 4 |
import warnings |
| 5 |
from io import BytesIO |
| 6 |
from pathlib import Path |
| 7 |
import shutil |
| 8 |
import tempfile |
| 9 |
from glob import glob |
| 10 |
import zipfile |
| 11 |
|
| 12 |
import h5py |
| 13 |
import numpy as np |
| 14 |
from h5py import SoftLink, HardLink, ExternalLink, File |
| 15 |
from h5py import filters as h5py_filters |
| 16 |
from hdmf.backends.hdf5 import H5DataIO |
| 17 |
from hdmf.backends.hdf5.h5tools import HDF5IO, SPEC_LOC_ATTR, H5PY_3 |
| 18 |
from hdmf.backends.io import HDMFIO |
| 19 |
from hdmf.backends.warnings import BrokenLinkWarning |
| 20 |
from hdmf.backends.errors import UnsupportedOperation |
| 21 |
from hdmf.build import GroupBuilder, DatasetBuilder, BuildManager, TypeMap, OrphanContainerBuildError, LinkBuilder |
| 22 |
from hdmf.container import Container |
| 23 |
from hdmf import Data, docval |
| 24 |
from hdmf.data_utils import DataChunkIterator, GenericDataChunkIterator, InvalidDataIOError |
| 25 |
from hdmf.spec.catalog import SpecCatalog |
| 26 |
from hdmf.spec.namespace import NamespaceCatalog, SpecNamespace |
| 27 |
from hdmf.spec.spec import GroupSpec, DtypeSpec |
| 28 |
from hdmf.testing import TestCase, remove_test_file |
| 29 |
from hdmf.common.resources import HERD |
| 30 |
from hdmf.term_set import TermSet, TermSetWrapper |
| 31 |
|
| 32 |
|
| 33 |
from tests.unit.helpers.utils import (Foo, FooBucket, FooFile, get_foo_buildmanager, |
| 34 |
Baz, BazData, BazCpdData, BazBucket, get_baz_buildmanager, |
| 35 |
CORE_NAMESPACE, get_temp_filepath, CacheSpecTestHelper, |
| 36 |
CustomGroupSpec, CustomDatasetSpec, CustomSpecNamespace) |
| 37 |
|
| 38 |
try: |
| 39 |
import zarr |
| 40 |
SKIP_ZARR_TESTS = False |
| 41 |
except ImportError: |
| 42 |
SKIP_ZARR_TESTS = True |
| 43 |
|
| 44 |
try: |
| 45 |
import linkml_runtime # noqa: F401 |
| 46 |
LINKML_INSTALLED = True |
| 47 |
except ImportError: |
| 48 |
LINKML_INSTALLED = False |
| 49 |
|
| 50 |
|
| 51 |
class NumpyArrayGenericDataChunkIterator(GenericDataChunkIterator): |
| 52 |
def __init__(self, array: np.ndarray, **kwargs): |
| 53 |
self.array = array |
| 54 |
super().__init__(**kwargs) |
| 55 |
|
| 56 |
def _get_data(self, selection): |
| 57 |
return self.array[selection] |
| 58 |
|
| 59 |
def _get_maxshape(self): |
| 60 |
return self.array.shape |
| 61 |
|
| 62 |
def _get_dtype(self): |
| 63 |
return self.array.dtype |
| 64 |
|
| 65 |
|
| 66 |
class H5IOTest(TestCase): |
| 67 |
"""Tests for h5tools IO tools""" |
| 68 |
|
| 69 |
def setUp(self): |
| 70 |
self.path = get_temp_filepath() |
| 71 |
self.io = HDF5IO(self.path, mode='a') |
| 72 |
self.f = self.io._file |
| 73 |
|
| 74 |
def tearDown(self): |
| 75 |
self.io.close() |
| 76 |
os.remove(self.path) |
| 77 |
|
| 78 |
########################################## |
| 79 |
# __chunked_iter_fill__(...) tests |
| 80 |
########################################## |
| 81 |
def test__chunked_iter_fill(self): |
| 82 |
"""Matrix test of HDF5IO.__chunked_iter_fill__ using a DataChunkIterator with different parameters""" |
| 83 |
data_opts = {'iterator': range(10), |
| 84 |
'numpy': np.arange(30).reshape(5, 2, 3), |
| 85 |
'list': np.arange(30).reshape(5, 2, 3).tolist(), |
| 86 |
'sparselist1': [1, 2, 3, None, None, None, None, 8, 9, 10], |
| 87 |
'sparselist2': [None, None, 3], |
| 88 |
'sparselist3': [1, 2, 3, None, None], # note: cannot process None in ndarray |
| 89 |
'nanlist': [[[1, 2, 3, np.nan, np.nan, 6], [np.nan, np.nan, 3, 4, np.nan, np.nan]], |
| 90 |
[[10, 20, 30, 40, np.nan, np.nan], [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]]]} |
| 91 |
buffer_size_opts = [1, 2, 3, 4] # data is divisible by some of these, some not |
| 92 |
for data_type, data in data_opts.items(): |
| 93 |
iter_axis_opts = [0, 1, 2] |
| 94 |
if data_type == 'iterator' or data_type.startswith('sparselist'): |
| 95 |
iter_axis_opts = [0] # only one dimension |
| 96 |
|
| 97 |
for iter_axis in iter_axis_opts: |
| 98 |
for buffer_size in buffer_size_opts: |
| 99 |
with self.subTest(data_type=data_type, iter_axis=iter_axis, buffer_size=buffer_size): |
| 100 |
with warnings.catch_warnings(record=True): |
| 101 |
# init may throw UserWarning for iterating over not-first dim of a list. ignore here |
| 102 |
msg = ("Iterating over an axis other than the first dimension of list or tuple data " |
| 103 |
"involves converting the data object to a numpy ndarray, which may incur a " |
| 104 |
"computational cost.") |
| 105 |
warnings.filterwarnings("ignore", message=msg, category=UserWarning) |
| 106 |
dci = DataChunkIterator(data=data, buffer_size=buffer_size, iter_axis=iter_axis) |
| 107 |
|
| 108 |
dset_name = '%s, %d, %d' % (data_type, iter_axis, buffer_size) |
| 109 |
my_dset = HDF5IO.__chunked_iter_fill__(self.f, dset_name, dci) |
| 110 |
|
| 111 |
if data_type == 'iterator': |
| 112 |
self.assertListEqual(my_dset[:].tolist(), list(data)) |
| 113 |
elif data_type == 'numpy': |
| 114 |
self.assertTrue(np.all(my_dset[:] == data)) |
| 115 |
self.assertTupleEqual(my_dset.shape, data.shape) |
| 116 |
elif data_type == 'list' or data_type == 'nanlist': |
| 117 |
data_np = np.array(data) |
| 118 |
np.testing.assert_array_equal(my_dset[:], data_np) |
| 119 |
self.assertTupleEqual(my_dset.shape, data_np.shape) |
| 120 |
elif data_type.startswith('sparselist'): |
| 121 |
# replace None in original data with default hdf5 fillvalue 0 |
| 122 |
data_zeros = np.where(np.equal(np.array(data), None), 0, data) |
| 123 |
np.testing.assert_array_equal(my_dset[:], data_zeros) |
| 124 |
self.assertTupleEqual(my_dset.shape, data_zeros.shape) |
| 125 |
|
| 126 |
########################################## |
| 127 |
# write_dataset tests: scalars |
| 128 |
########################################## |
| 129 |
def test_write_dataset_scalar(self): |
| 130 |
a = 10 |
| 131 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) |
| 132 |
dset = self.f['test_dataset'] |
| 133 |
self.assertTupleEqual(dset.shape, ()) |
| 134 |
self.assertEqual(dset[()], a) |
| 135 |
|
| 136 |
def test_write_dataset_string(self): |
| 137 |
a = 'test string' |
| 138 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) |
| 139 |
dset = self.f['test_dataset'] |
| 140 |
self.assertTupleEqual(dset.shape, ()) |
| 141 |
# self.assertEqual(dset[()].decode('utf-8'), a) |
| 142 |
read_a = dset[()] |
| 143 |
if isinstance(read_a, bytes): |
| 144 |
read_a = read_a.decode('utf-8') |
| 145 |
self.assertEqual(read_a, a) |
| 146 |
|
| 147 |
def test_write_dataset_scalar_compound(self): |
| 148 |
cmpd_dtype = np.dtype([('x', np.int32), ('y', np.float64)]) |
| 149 |
a = np.array((1, 0.1), dtype=cmpd_dtype) |
| 150 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, |
| 151 |
dtype=[DtypeSpec('x', doc='x', dtype='int32'), |
| 152 |
DtypeSpec('y', doc='y', dtype='float64')])) |
| 153 |
dset = self.f['test_dataset'] |
| 154 |
self.assertTupleEqual(dset.shape, ()) |
| 155 |
self.assertEqual(dset[()].tolist(), a.tolist()) |
| 156 |
|
| 157 |
########################################## |
| 158 |
# write_dataset tests: TermSetWrapper |
| 159 |
########################################## |
| 160 |
@unittest.skipIf(not LINKML_INSTALLED, "optional LinkML module is not installed") |
| 161 |
def test_write_dataset_TermSetWrapper(self): |
| 162 |
terms = TermSet(term_schema_path='tests/unit/example_test_term_set.yaml') |
| 163 |
a = TermSetWrapper(value=['Homo sapiens'], termset=terms) |
| 164 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) |
| 165 |
dset = self.f['test_dataset'] |
| 166 |
self.assertEqual(dset[0].decode('utf-8'), a.value[0]) |
| 167 |
|
| 168 |
########################################## |
| 169 |
# write_dataset tests: lists |
| 170 |
########################################## |
| 171 |
def test_write_dataset_list(self): |
| 172 |
a = np.arange(30).reshape(5, 2, 3) |
| 173 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a.tolist(), attributes={})) |
| 174 |
dset = self.f['test_dataset'] |
| 175 |
self.assertTrue(np.all(dset[:] == a)) |
| 176 |
|
| 177 |
def test_write_dataset_lol_strings(self): |
| 178 |
a = [['aa', 'bb'], ['cc', 'dd']] |
| 179 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) |
| 180 |
dset = self.f['test_dataset'] |
| 181 |
decoded_dset = [[item.decode('utf-8') if isinstance(item, bytes) else item for item in sublist] |
| 182 |
for sublist in dset[:]] |
| 183 |
self.assertTrue(decoded_dset == a) |
| 184 |
|
| 185 |
def test_write_dataset_list_compound_datatype(self): |
| 186 |
a = np.array([(1, 2, 0.5), (3, 4, 0.5)], dtype=[('x', 'int'), ('y', 'int'), ('z', 'float')]) |
| 187 |
dset_builder = DatasetBuilder( |
| 188 |
name='test_dataset', |
| 189 |
data=a.tolist(), |
| 190 |
attributes={}, |
| 191 |
dtype=[ |
| 192 |
DtypeSpec('x', doc='x', dtype='int'), |
| 193 |
DtypeSpec('y', doc='y', dtype='int'), |
| 194 |
DtypeSpec('z', doc='z', dtype='float'), |
| 195 |
], |
| 196 |
) |
| 197 |
self.io.write_dataset(self.f, dset_builder) |
| 198 |
dset = self.f['test_dataset'] |
| 199 |
for field in a.dtype.names: |
| 200 |
self.assertTrue(np.all(dset[field][:] == a[field])) |
| 201 |
|
| 202 |
def test_write_dataset_list_compress_gzip(self): |
| 203 |
a = H5DataIO(np.arange(30).reshape(5, 2, 3), |
| 204 |
compression='gzip', |
| 205 |
compression_opts=5, |
| 206 |
shuffle=True, |
| 207 |
fletcher32=True) |
| 208 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) |
| 209 |
dset = self.f['test_dataset'] |
| 210 |
self.assertTrue(np.all(dset[:] == a.data)) |
| 211 |
self.assertEqual(dset.compression, 'gzip') |
| 212 |
self.assertEqual(dset.compression_opts, 5) |
| 213 |
self.assertEqual(dset.shuffle, True) |
| 214 |
self.assertEqual(dset.fletcher32, True) |
| 215 |
|
| 216 |
@unittest.skipIf("lzf" not in h5py_filters.encode, |
| 217 |
"LZF compression not supported in this h5py library install") |
| 218 |
def test_write_dataset_list_compress_lzf(self): |
| 219 |
warn_msg = ("lzf compression may not be available on all installations of HDF5. Use of gzip is " |
| 220 |
"recommended to ensure portability of the generated HDF5 files.") |
| 221 |
with self.assertWarnsWith(UserWarning, warn_msg): |
| 222 |
a = H5DataIO(np.arange(30).reshape(5, 2, 3), |
| 223 |
compression='lzf', |
| 224 |
shuffle=True, |
| 225 |
fletcher32=True) |
| 226 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) |
| 227 |
dset = self.f['test_dataset'] |
| 228 |
self.assertTrue(np.all(dset[:] == a.data)) |
| 229 |
self.assertEqual(dset.compression, 'lzf') |
| 230 |
self.assertEqual(dset.shuffle, True) |
| 231 |
self.assertEqual(dset.fletcher32, True) |
| 232 |
|
| 233 |
@unittest.skipIf("szip" not in h5py_filters.encode, |
| 234 |
"SZIP compression not supported in this h5py library install") |
| 235 |
def test_write_dataset_list_compress_szip(self): |
| 236 |
warn_msg = ("szip compression may not be available on all installations of HDF5. Use of gzip is " |
| 237 |
"recommended to ensure portability of the generated HDF5 files.") |
| 238 |
with self.assertWarnsWith(UserWarning, warn_msg): |
| 239 |
a = H5DataIO(np.arange(30).reshape(5, 2, 3), |
| 240 |
compression='szip', |
| 241 |
compression_opts=('ec', 16), |
| 242 |
shuffle=True, |
| 243 |
fletcher32=True) |
| 244 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) |
| 245 |
dset = self.f['test_dataset'] |
| 246 |
self.assertTrue(np.all(dset[:] == a.data)) |
| 247 |
self.assertEqual(dset.compression, 'szip') |
| 248 |
self.assertEqual(dset.shuffle, True) |
| 249 |
self.assertEqual(dset.fletcher32, True) |
| 250 |
|
| 251 |
def test_write_dataset_list_compress_available_int_filters(self): |
| 252 |
a = H5DataIO(np.arange(30).reshape(5, 2, 3), |
| 253 |
compression=1, |
| 254 |
shuffle=True, |
| 255 |
fletcher32=True, |
| 256 |
allow_plugin_filters=True) |
| 257 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) |
| 258 |
dset = self.f['test_dataset'] |
| 259 |
self.assertTrue(np.all(dset[:] == a.data)) |
| 260 |
self.assertEqual(dset.compression, 'gzip') |
| 261 |
self.assertEqual(dset.shuffle, True) |
| 262 |
self.assertEqual(dset.fletcher32, True) |
| 263 |
|
| 264 |
def test_write_dataset_list_enable_default_compress(self): |
| 265 |
a = H5DataIO(np.arange(30).reshape(5, 2, 3), |
| 266 |
compression=True) |
| 267 |
self.assertEqual(a.io_settings['compression'], 'gzip') |
| 268 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) |
| 269 |
dset = self.f['test_dataset'] |
| 270 |
self.assertTrue(np.all(dset[:] == a.data)) |
| 271 |
self.assertEqual(dset.compression, 'gzip') |
| 272 |
|
| 273 |
def test_write_dataset_list_disable_default_compress(self): |
| 274 |
msg = ("Compression disabled by compression=False setting. compression_opts parameter will, therefore, " |
| 275 |
"be ignored.") |
| 276 |
with self.assertWarnsWith(UserWarning, msg): |
| 277 |
a = H5DataIO(np.arange(30).reshape(5, 2, 3), |
| 278 |
compression=False, |
| 279 |
compression_opts=5) |
| 280 |
self.assertFalse('compression_ops' in a.io_settings) |
| 281 |
self.assertFalse('compression' in a.io_settings) |
| 282 |
|
| 283 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) |
| 284 |
dset = self.f['test_dataset'] |
| 285 |
self.assertTrue(np.all(dset[:] == a.data)) |
| 286 |
self.assertEqual(dset.compression, None) |
| 287 |
|
| 288 |
def test_write_dataset_list_chunked(self): |
| 289 |
a = H5DataIO(np.arange(30).reshape(5, 2, 3), |
| 290 |
chunks=(1, 1, 3)) |
| 291 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) |
| 292 |
dset = self.f['test_dataset'] |
| 293 |
self.assertTrue(np.all(dset[:] == a.data)) |
| 294 |
self.assertEqual(dset.chunks, (1, 1, 3)) |
| 295 |
|
| 296 |
def test_write_dataset_list_fillvalue(self): |
| 297 |
a = H5DataIO(np.arange(20).reshape(5, 4), fillvalue=-1) |
| 298 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={})) |
| 299 |
dset = self.f['test_dataset'] |
| 300 |
self.assertTrue(np.all(dset[:] == a.data)) |
| 301 |
self.assertEqual(dset.fillvalue, -1) |
| 302 |
|
| 303 |
########################################## |
| 304 |
# write_dataset tests: tables |
| 305 |
########################################## |
| 306 |
def test_write_table(self): |
| 307 |
cmpd_dt = np.dtype([('a', np.int32), ('b', np.float64)]) |
| 308 |
data = np.zeros(10, dtype=cmpd_dt) |
| 309 |
data['a'][1] = 101 |
| 310 |
data['b'][1] = 0.1 |
| 311 |
dt = [{'name': 'a', 'dtype': 'int32', 'doc': 'a column'}, |
| 312 |
{'name': 'b', 'dtype': 'float64', 'doc': 'b column'}] |
| 313 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', data, attributes={}, dtype=dt)) |
| 314 |
dset = self.f['test_dataset'] |
| 315 |
self.assertEqual(dset['a'].tolist(), data['a'].tolist()) |
| 316 |
self.assertEqual(dset['b'].tolist(), data['b'].tolist()) |
| 317 |
|
| 318 |
def test_write_table_nested(self): |
| 319 |
b_cmpd_dt = np.dtype([('c', np.int32), ('d', np.float64)]) |
| 320 |
cmpd_dt = np.dtype([('a', np.int32), ('b', b_cmpd_dt)]) |
| 321 |
data = np.zeros(10, dtype=cmpd_dt) |
| 322 |
data['a'][1] = 101 |
| 323 |
data['b']['c'] = 202 |
| 324 |
data['b']['d'] = 10.1 |
| 325 |
b_dt = [{'name': 'c', 'dtype': 'int32', 'doc': 'c column'}, |
| 326 |
{'name': 'd', 'dtype': 'float64', 'doc': 'd column'}] |
| 327 |
dt = [{'name': 'a', 'dtype': 'int32', 'doc': 'a column'}, |
| 328 |
{'name': 'b', 'dtype': b_dt, 'doc': 'b column'}] |
| 329 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', data, attributes={}, dtype=dt)) |
| 330 |
dset = self.f['test_dataset'] |
| 331 |
self.assertEqual(dset['a'].tolist(), data['a'].tolist()) |
| 332 |
self.assertEqual(dset['b'].tolist(), data['b'].tolist()) |
| 333 |
|
| 334 |
########################################## |
| 335 |
# write_dataset tests: Iterable |
| 336 |
########################################## |
| 337 |
def test_write_dataset_iterable(self): |
| 338 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', range(10), attributes={})) |
| 339 |
dset = self.f['test_dataset'] |
| 340 |
self.assertListEqual(dset[:].tolist(), list(range(10))) |
| 341 |
|
| 342 |
def test_write_dataset_iterable_multidimensional_array(self): |
| 343 |
a = np.arange(30).reshape(5, 2, 3) |
| 344 |
aiter = iter(a) |
| 345 |
daiter = DataChunkIterator.from_iterable(aiter, buffer_size=2) |
| 346 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', daiter, attributes={})) |
| 347 |
dset = self.f['test_dataset'] |
| 348 |
self.assertListEqual(dset[:].tolist(), a.tolist()) |
| 349 |
|
| 350 |
def test_write_multi_dci_oaat(self): |
| 351 |
""" |
| 352 |
Test writing multiple DataChunkIterators, one at a time |
| 353 |
""" |
| 354 |
a = np.arange(30).reshape(5, 2, 3) |
| 355 |
b = np.arange(30, 60).reshape(5, 2, 3) |
| 356 |
aiter = iter(a) |
| 357 |
biter = iter(b) |
| 358 |
daiter1 = DataChunkIterator.from_iterable(aiter, buffer_size=2) |
| 359 |
daiter2 = DataChunkIterator.from_iterable(biter, buffer_size=2) |
| 360 |
builder = GroupBuilder("root") |
| 361 |
dataset1 = DatasetBuilder('test_dataset1', daiter1) |
| 362 |
dataset2 = DatasetBuilder('test_dataset2', daiter2) |
| 363 |
builder.set_dataset(dataset1) |
| 364 |
builder.set_dataset(dataset2) |
| 365 |
self.io.write_builder(builder) |
| 366 |
dset1 = self.f['test_dataset1'] |
| 367 |
self.assertListEqual(dset1[:].tolist(), a.tolist()) |
| 368 |
dset2 = self.f['test_dataset2'] |
| 369 |
self.assertListEqual(dset2[:].tolist(), b.tolist()) |
| 370 |
|
| 371 |
def test_write_multi_dci_conc(self): |
| 372 |
""" |
| 373 |
Test writing multiple DataChunkIterators, concurrently |
| 374 |
""" |
| 375 |
a = np.arange(30).reshape(5, 2, 3) |
| 376 |
b = np.arange(30, 60).reshape(5, 2, 3) |
| 377 |
aiter = iter(a) |
| 378 |
biter = iter(b) |
| 379 |
daiter1 = DataChunkIterator.from_iterable(aiter, buffer_size=2) |
| 380 |
daiter2 = DataChunkIterator.from_iterable(biter, buffer_size=2) |
| 381 |
builder = GroupBuilder("root") |
| 382 |
dataset1 = DatasetBuilder('test_dataset1', daiter1) |
| 383 |
dataset2 = DatasetBuilder('test_dataset2', daiter2) |
| 384 |
builder.set_dataset(dataset1) |
| 385 |
builder.set_dataset(dataset2) |
| 386 |
self.io.write_builder(builder) |
| 387 |
dset1 = self.f['test_dataset1'] |
| 388 |
self.assertListEqual(dset1[:].tolist(), a.tolist()) |
| 389 |
dset2 = self.f['test_dataset2'] |
| 390 |
self.assertListEqual(dset2[:].tolist(), b.tolist()) |
| 391 |
|
| 392 |
def test_write_dataset_iterable_multidimensional_array_compression(self): |
| 393 |
a = np.arange(30).reshape(5, 2, 3) |
| 394 |
aiter = iter(a) |
| 395 |
daiter = DataChunkIterator.from_iterable(aiter, buffer_size=2) |
| 396 |
wrapped_daiter = H5DataIO(data=daiter, |
| 397 |
compression='gzip', |
| 398 |
compression_opts=5, |
| 399 |
shuffle=True, |
| 400 |
fletcher32=True) |
| 401 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', wrapped_daiter, attributes={})) |
| 402 |
dset = self.f['test_dataset'] |
| 403 |
self.assertEqual(dset.shape, a.shape) |
| 404 |
self.assertListEqual(dset[:].tolist(), a.tolist()) |
| 405 |
self.assertEqual(dset.compression, 'gzip') |
| 406 |
self.assertEqual(dset.compression_opts, 5) |
| 407 |
self.assertEqual(dset.shuffle, True) |
| 408 |
self.assertEqual(dset.fletcher32, True) |
| 409 |
|
| 410 |
############################################# |
| 411 |
# write_dataset tests: data chunk iterator |
| 412 |
############################################# |
| 413 |
def test_write_dataset_data_chunk_iterator(self): |
| 414 |
dci = DataChunkIterator(data=np.arange(10), buffer_size=2) |
| 415 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', dci, attributes={}, dtype=dci.dtype)) |
| 416 |
dset = self.f['test_dataset'] |
| 417 |
self.assertListEqual(dset[:].tolist(), list(range(10))) |
| 418 |
self.assertEqual(dset[:].dtype, dci.dtype) |
| 419 |
|
| 420 |
def test_write_dataset_data_chunk_iterator_with_compression(self): |
| 421 |
dci = DataChunkIterator(data=np.arange(10), buffer_size=2) |
| 422 |
wrapped_dci = H5DataIO(data=dci, |
| 423 |
compression='gzip', |
| 424 |
compression_opts=5, |
| 425 |
shuffle=True, |
| 426 |
fletcher32=True, |
| 427 |
chunks=(2,)) |
| 428 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', wrapped_dci, attributes={})) |
| 429 |
dset = self.f['test_dataset'] |
| 430 |
self.assertListEqual(dset[:].tolist(), list(range(10))) |
| 431 |
self.assertEqual(dset.compression, 'gzip') |
| 432 |
self.assertEqual(dset.compression_opts, 5) |
| 433 |
self.assertEqual(dset.shuffle, True) |
| 434 |
self.assertEqual(dset.fletcher32, True) |
| 435 |
self.assertEqual(dset.chunks, (2,)) |
| 436 |
|
| 437 |
def test_pass_through_of_recommended_chunks(self): |
| 438 |
|
| 439 |
class DC(DataChunkIterator): |
| 440 |
def recommended_chunk_shape(self): |
| 441 |
return (5, 1, 1) |
| 442 |
|
| 443 |
dci = DC(data=np.arange(30).reshape(5, 2, 3)) |
| 444 |
wrapped_dci = H5DataIO(data=dci, |
| 445 |
compression='gzip', |
| 446 |
compression_opts=5, |
| 447 |
shuffle=True, |
| 448 |
fletcher32=True) |
| 449 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', wrapped_dci, attributes={})) |
| 450 |
dset = self.f['test_dataset'] |
| 451 |
self.assertEqual(dset.chunks, (5, 1, 1)) |
| 452 |
self.assertEqual(dset.compression, 'gzip') |
| 453 |
self.assertEqual(dset.compression_opts, 5) |
| 454 |
self.assertEqual(dset.shuffle, True) |
| 455 |
self.assertEqual(dset.fletcher32, True) |
| 456 |
|
| 457 |
def test_dci_h5dataset(self): |
| 458 |
data = np.arange(30).reshape(5, 2, 3) |
| 459 |
dci1 = DataChunkIterator(data=data, buffer_size=1, iter_axis=0) |
| 460 |
HDF5IO.__chunked_iter_fill__(self.f, 'test_dataset', dci1) |
| 461 |
dset = self.f['test_dataset'] |
| 462 |
dci2 = DataChunkIterator(data=dset, buffer_size=2, iter_axis=2) |
| 463 |
|
| 464 |
chunk = dci2.next() |
| 465 |
self.assertTupleEqual(chunk.shape, (5, 2, 2)) |
| 466 |
chunk = dci2.next() |
| 467 |
self.assertTupleEqual(chunk.shape, (5, 2, 1)) |
| 468 |
|
| 469 |
# TODO test chunk data, shape, selection |
| 470 |
|
| 471 |
self.assertTupleEqual(dci2.recommended_data_shape(), data.shape) |
| 472 |
self.assertIsNone(dci2.recommended_chunk_shape()) |
| 473 |
|
| 474 |
def test_dci_h5dataset_sparse_matched(self): |
| 475 |
data = [1, 2, 3, None, None, None, None, 8, 9, 10] |
| 476 |
dci1 = DataChunkIterator(data=data, buffer_size=3) |
| 477 |
HDF5IO.__chunked_iter_fill__(self.f, 'test_dataset', dci1) |
| 478 |
dset = self.f['test_dataset'] |
| 479 |
dci2 = DataChunkIterator(data=dset, buffer_size=2) |
| 480 |
# dataset is read such that Nones in original data were not written, but are read as 0s |
| 481 |
|
| 482 |
self.assertTupleEqual(dci2.maxshape, (10,)) |
| 483 |
self.assertEqual(dci2.dtype, np.dtype(int)) |
| 484 |
count = 0 |
| 485 |
for chunk in dci2: |
| 486 |
self.assertEqual(len(chunk.selection), 1) |
| 487 |
if count == 0: |
| 488 |
self.assertListEqual(chunk.data.tolist(), [1, 2]) |
| 489 |
self.assertEqual(chunk.selection[0], slice(0, 2)) |
| 490 |
elif count == 1: |
| 491 |
self.assertListEqual(chunk.data.tolist(), [3, 0]) |
| 492 |
self.assertEqual(chunk.selection[0], slice(2, 4)) |
| 493 |
elif count == 2: |
| 494 |
self.assertListEqual(chunk.data.tolist(), [0, 0]) |
| 495 |
self.assertEqual(chunk.selection[0], slice(4, 6)) |
| 496 |
elif count == 3: |
| 497 |
self.assertListEqual(chunk.data.tolist(), [0, 8]) |
| 498 |
self.assertEqual(chunk.selection[0], slice(6, 8)) |
| 499 |
elif count == 4: |
| 500 |
self.assertListEqual(chunk.data.tolist(), [9, 10]) |
| 501 |
self.assertEqual(chunk.selection[0], slice(8, 10)) |
| 502 |
count += 1 |
| 503 |
|
| 504 |
self.assertEqual(count, 5) |
| 505 |
self.assertTupleEqual(dci2.recommended_data_shape(), (10,)) |
| 506 |
self.assertIsNone(dci2.recommended_chunk_shape()) |
| 507 |
|
| 508 |
def test_dci_h5dataset_sparse_unmatched(self): |
| 509 |
data = [1, 2, 3, None, None, None, None, 8, 9, 10] |
| 510 |
dci1 = DataChunkIterator(data=data, buffer_size=3) |
| 511 |
HDF5IO.__chunked_iter_fill__(self.f, 'test_dataset', dci1) |
| 512 |
dset = self.f['test_dataset'] |
| 513 |
dci2 = DataChunkIterator(data=dset, buffer_size=4) |
| 514 |
# dataset is read such that Nones in original data were not written, but are read as 0s |
| 515 |
|
| 516 |
self.assertTupleEqual(dci2.maxshape, (10,)) |
| 517 |
self.assertEqual(dci2.dtype, np.dtype(int)) |
| 518 |
count = 0 |
| 519 |
for chunk in dci2: |
| 520 |
self.assertEqual(len(chunk.selection), 1) |
| 521 |
if count == 0: |
| 522 |
self.assertListEqual(chunk.data.tolist(), [1, 2, 3, 0]) |
| 523 |
self.assertEqual(chunk.selection[0], slice(0, 4)) |
| 524 |
elif count == 1: |
| 525 |
self.assertListEqual(chunk.data.tolist(), [0, 0, 0, 8]) |
| 526 |
self.assertEqual(chunk.selection[0], slice(4, 8)) |
| 527 |
elif count == 2: |
| 528 |
self.assertListEqual(chunk.data.tolist(), [9, 10]) |
| 529 |
self.assertEqual(chunk.selection[0], slice(8, 10)) |
| 530 |
count += 1 |
| 531 |
|
| 532 |
self.assertEqual(count, 3) |
| 533 |
self.assertTupleEqual(dci2.recommended_data_shape(), (10,)) |
| 534 |
self.assertIsNone(dci2.recommended_chunk_shape()) |
| 535 |
|
| 536 |
def test_dci_h5dataset_scalar(self): |
| 537 |
data = [1] |
| 538 |
dci1 = DataChunkIterator(data=data, buffer_size=3) |
| 539 |
HDF5IO.__chunked_iter_fill__(self.f, 'test_dataset', dci1) |
| 540 |
dset = self.f['test_dataset'] |
| 541 |
dci2 = DataChunkIterator(data=dset, buffer_size=4) |
| 542 |
# dataset is read such that Nones in original data were not written, but are read as 0s |
| 543 |
|
| 544 |
self.assertTupleEqual(dci2.maxshape, (1,)) |
| 545 |
self.assertEqual(dci2.dtype, np.dtype(int)) |
| 546 |
count = 0 |
| 547 |
for chunk in dci2: |
| 548 |
self.assertEqual(len(chunk.selection), 1) |
| 549 |
if count == 0: |
| 550 |
self.assertListEqual(chunk.data.tolist(), [1]) |
| 551 |
self.assertEqual(chunk.selection[0], slice(0, 1)) |
| 552 |
count += 1 |
| 553 |
|
| 554 |
self.assertEqual(count, 1) |
| 555 |
self.assertTupleEqual(dci2.recommended_data_shape(), (1,)) |
| 556 |
self.assertIsNone(dci2.recommended_chunk_shape()) |
| 557 |
|
| 558 |
############################################# |
| 559 |
# write_dataset tests: generic data chunk iterator |
| 560 |
############################################# |
| 561 |
def test_write_dataset_generic_data_chunk_iterator(self): |
| 562 |
array = np.arange(10) |
| 563 |
dci = NumpyArrayGenericDataChunkIterator(array=array) |
| 564 |
self.io.write_dataset(self.f, DatasetBuilder("test_dataset", dci, attributes={}, dtype=dci.dtype)) |
| 565 |
dset = self.f["test_dataset"] |
| 566 |
self.assertListEqual(dset[:].tolist(), list(array)) |
| 567 |
self.assertEqual(dset[:].dtype, dci.dtype) |
| 568 |
|
| 569 |
def test_write_dataset_generic_data_chunk_iterator_with_compression(self): |
| 570 |
array = np.arange(10) |
| 571 |
dci = NumpyArrayGenericDataChunkIterator(array=array) |
| 572 |
wrapped_dci = H5DataIO( |
| 573 |
data=dci, |
| 574 |
compression="gzip", |
| 575 |
compression_opts=5, |
| 576 |
shuffle=True, |
| 577 |
fletcher32=True, |
| 578 |
) |
| 579 |
self.io.write_dataset(self.f, DatasetBuilder("test_dataset", wrapped_dci, attributes={})) |
| 580 |
dset = self.f["test_dataset"] |
| 581 |
self.assertListEqual(dset[:].tolist(), list(array)) |
| 582 |
self.assertEqual(dset.compression, "gzip") |
| 583 |
self.assertEqual(dset.compression_opts, 5) |
| 584 |
self.assertEqual(dset.shuffle, True) |
| 585 |
self.assertEqual(dset.fletcher32, True) |
| 586 |
|
| 587 |
def test_chunk_shape_override_through_wrapper(self): |
| 588 |
array = np.arange(10) |
| 589 |
chunk_shape = (2,) |
| 590 |
dci = NumpyArrayGenericDataChunkIterator(array=array) |
| 591 |
wrapped_dci = H5DataIO(data=dci, chunks=chunk_shape) |
| 592 |
self.io.write_dataset(self.f, DatasetBuilder("test_dataset", wrapped_dci, attributes={})) |
| 593 |
dset = self.f["test_dataset"] |
| 594 |
self.assertListEqual(dset[:].tolist(), list(array)) |
| 595 |
self.assertEqual(dset.chunks, chunk_shape) |
| 596 |
|
| 597 |
def test_pass_through_of_chunk_shape_generic_data_chunk_iterator(self): |
| 598 |
maxshape = (5, 2, 3) |
| 599 |
chunk_shape = (5, 1, 1) |
| 600 |
array = np.arange(np.prod(maxshape)).reshape(maxshape) |
| 601 |
dci = NumpyArrayGenericDataChunkIterator(array=array, chunk_shape=chunk_shape) |
| 602 |
wrapped_dci = H5DataIO(data=dci) |
| 603 |
self.io.write_dataset(self.f, DatasetBuilder("test_dataset", wrapped_dci, attributes={})) |
| 604 |
dset = self.f["test_dataset"] |
| 605 |
self.assertEqual(dset.chunks, chunk_shape) |
| 606 |
|
| 607 |
############################################# |
| 608 |
# H5DataIO general |
| 609 |
############################################# |
| 610 |
def test_pass_through_of_maxshape_on_h5dataset(self): |
| 611 |
k = 10 |
| 612 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', np.arange(k), attributes={})) |
| 613 |
dset = H5DataIO(self.f['test_dataset']) |
| 614 |
self.assertEqual(dset.maxshape, (k,)) |
| 615 |
|
| 616 |
def test_warning_on_non_gzip_compression(self): |
| 617 |
# Make sure no warning is issued when using gzip |
| 618 |
with warnings.catch_warnings(record=True) as w: |
| 619 |
dset = H5DataIO(np.arange(30), |
| 620 |
compression='gzip') |
| 621 |
self.assertEqual(len(w), 0) |
| 622 |
self.assertEqual(dset.io_settings['compression'], 'gzip') |
| 623 |
# Make sure a warning is issued when using szip (even if installed) |
| 624 |
warn_msg = ("szip compression may not be available on all installations of HDF5. Use of gzip is " |
| 625 |
"recommended to ensure portability of the generated HDF5 files.") |
| 626 |
if "szip" in h5py_filters.encode: |
| 627 |
with self.assertWarnsWith(UserWarning, warn_msg): |
| 628 |
dset = H5DataIO(np.arange(30), |
| 629 |
compression='szip', |
| 630 |
compression_opts=('ec', 16)) |
| 631 |
self.assertEqual(dset.io_settings['compression'], 'szip') |
| 632 |
else: |
| 633 |
with self.assertRaises(ValueError): |
| 634 |
with self.assertWarnsWith(UserWarning, warn_msg): |
| 635 |
dset = H5DataIO(np.arange(30), |
| 636 |
compression='szip', |
| 637 |
compression_opts=('ec', 16)) |
| 638 |
self.assertEqual(dset.io_settings['compression'], 'szip') |
| 639 |
# Make sure a warning is issued when using lzf compression |
| 640 |
warn_msg = ("lzf compression may not be available on all installations of HDF5. Use of gzip is " |
| 641 |
"recommended to ensure portability of the generated HDF5 files.") |
| 642 |
with self.assertWarnsWith(UserWarning, warn_msg): |
| 643 |
dset = H5DataIO(np.arange(30), |
| 644 |
compression='lzf') |
| 645 |
self.assertEqual(dset.io_settings['compression'], 'lzf') |
| 646 |
|
| 647 |
def test_error_on_unsupported_compression_filter(self): |
| 648 |
# Make sure gzip does not raise an error |
| 649 |
try: |
| 650 |
H5DataIO(np.arange(30), compression='gzip', compression_opts=5) |
| 651 |
except ValueError: |
| 652 |
self.fail("Using gzip compression raised a ValueError when it should not") |
| 653 |
# Make sure szip raises an error if not installed (or does not raise an error if installed) |
| 654 |
warn_msg = ("szip compression may not be available on all installations of HDF5. Use of gzip is " |
| 655 |
"recommended to ensure portability of the generated HDF5 files.") |
| 656 |
if "szip" not in h5py_filters.encode: |
| 657 |
with self.assertRaises(ValueError): |
| 658 |
with self.assertWarnsWith(UserWarning, warn_msg): |
| 659 |
H5DataIO(np.arange(30), compression='szip', compression_opts=('ec', 16)) |
| 660 |
else: |
| 661 |
try: |
| 662 |
with self.assertWarnsWith(UserWarning, warn_msg): |
| 663 |
H5DataIO(np.arange(30), compression='szip', compression_opts=('ec', 16)) |
| 664 |
except ValueError: |
| 665 |
self.fail("SZIP is installed but H5DataIO still raises an error") |
| 666 |
# Test error on illegal (i.e., a made-up compressor) |
| 667 |
with self.assertRaises(ValueError): |
| 668 |
warn_msg = ("unknown compression may not be available on all installations of HDF5. Use of gzip is " |
| 669 |
"recommended to ensure portability of the generated HDF5 files.") |
| 670 |
with self.assertWarnsWith(UserWarning, warn_msg): |
| 671 |
H5DataIO(np.arange(30), compression="unknown") |
| 672 |
# Make sure passing int compression filter raise an error if not installed |
| 673 |
if not h5py_filters.h5z.filter_avail(h5py_filters.h5z.FILTER_MAX): |
| 674 |
with self.assertRaises(ValueError): |
| 675 |
warn_msg = ("%i compression may not be available on all installations of HDF5. Use of gzip is " |
| 676 |
"recommended to ensure portability of the generated HDF5 files." |
| 677 |
% h5py_filters.h5z.FILTER_MAX) |
| 678 |
with self.assertWarnsWith(UserWarning, warn_msg): |
| 679 |
H5DataIO(np.arange(30), compression=h5py_filters.h5z.FILTER_MAX, allow_plugin_filters=True) |
| 680 |
# Make sure available int compression filters raise an error without passing allow_plugin_filters=True |
| 681 |
with self.assertRaises(ValueError): |
| 682 |
H5DataIO(np.arange(30), compression=h5py_filters.h5z.FILTER_DEFLATE) |
| 683 |
|
| 684 |
def test_value_error_on_incompatible_compression_opts(self): |
| 685 |
# Make sure we warn when gzip with szip compression options is used |
| 686 |
with self.assertRaises(ValueError): |
| 687 |
H5DataIO(np.arange(30), compression='gzip', compression_opts=('ec', 16)) |
| 688 |
# Make sure we warn if gzip with a too high aggression is used |
| 689 |
with self.assertRaises(ValueError): |
| 690 |
H5DataIO(np.arange(30), compression='gzip', compression_opts=100) |
| 691 |
# Make sure we warn if lzf with gzip compression option is used |
| 692 |
with self.assertRaises(ValueError): |
| 693 |
H5DataIO(np.arange(30), compression='lzf', compression_opts=5) |
| 694 |
# Make sure we warn if lzf with szip compression option is used |
| 695 |
with self.assertRaises(ValueError): |
| 696 |
H5DataIO(np.arange(30), compression='lzf', compression_opts=('ec', 16)) |
| 697 |
# Make sure we warn if szip with gzip compression option is used |
| 698 |
with self.assertRaises(ValueError): |
| 699 |
H5DataIO(np.arange(30), compression='szip', compression_opts=4) |
| 700 |
# Make sure szip raises a ValueError if bad options are used (odd compression option) |
| 701 |
with self.assertRaises(ValueError): |
| 702 |
H5DataIO(np.arange(30), compression='szip', compression_opts=('ec', 3)) |
| 703 |
# Make sure szip raises a ValueError if bad options are used (bad methods) |
| 704 |
with self.assertRaises(ValueError): |
| 705 |
H5DataIO(np.arange(30), compression='szip', compression_opts=('bad_method', 16)) |
| 706 |
|
| 707 |
def test_warning_on_linking_of_regular_array(self): |
| 708 |
msg = "link_data parameter in H5DataIO will be ignored" |
| 709 |
with self.assertWarnsWith(UserWarning, msg): |
| 710 |
dset = H5DataIO(np.arange(30), |
| 711 |
link_data=True) |
| 712 |
self.assertEqual(dset.link_data, False) |
| 713 |
|
| 714 |
def test_warning_on_setting_io_options_on_h5dataset_input(self): |
| 715 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', np.arange(10), attributes={})) |
| 716 |
msg = "maxshape in H5DataIO will be ignored with H5DataIO.data being an HDF5 dataset" |
| 717 |
with self.assertWarnsWith(UserWarning, msg): |
| 718 |
H5DataIO(self.f['test_dataset'], |
| 719 |
compression='gzip', |
| 720 |
compression_opts=4, |
| 721 |
fletcher32=True, |
| 722 |
shuffle=True, |
| 723 |
maxshape=(10, 20), |
| 724 |
chunks=(10,), |
| 725 |
fillvalue=100) |
| 726 |
|
| 727 |
def test_h5dataio_array_conversion_numpy(self): |
| 728 |
# Test that H5DataIO.__array__ is working when wrapping an ndarray |
| 729 |
test_speed = np.array([10., 20.]) |
| 730 |
data = H5DataIO((test_speed)) |
| 731 |
self.assertTrue(np.all(np.isfinite(data))) # Force call of H5DataIO.__array__ |
| 732 |
|
| 733 |
def test_h5dataio_array_conversion_list(self): |
| 734 |
# Test that H5DataIO.__array__ is working when wrapping a python list |
| 735 |
test_speed = [10., 20.] |
| 736 |
data = H5DataIO(test_speed) |
| 737 |
self.assertTrue(np.all(np.isfinite(data))) # Force call of H5DataIO.__array__ |
| 738 |
|
| 739 |
def test_h5dataio_array_conversion_datachunkiterator(self): |
| 740 |
# Test that H5DataIO.__array__ is working when wrapping a python list |
| 741 |
test_speed = DataChunkIterator(data=[10., 20.]) |
| 742 |
data = H5DataIO(test_speed) |
| 743 |
with self.assertRaises(NotImplementedError): |
| 744 |
np.isfinite(data) # Force call of H5DataIO.__array__ |
| 745 |
|
| 746 |
############################################# |
| 747 |
# Copy/Link h5py.Dataset object |
| 748 |
############################################# |
| 749 |
def test_link_h5py_dataset_input(self): |
| 750 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', np.arange(10), attributes={})) |
| 751 |
self.io.write_dataset(self.f, DatasetBuilder('test_softlink', self.f['test_dataset'], attributes={})) |
| 752 |
self.assertTrue(isinstance(self.f.get('test_softlink', getlink=True), SoftLink)) |
| 753 |
|
| 754 |
def test_copy_h5py_dataset_input(self): |
| 755 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', np.arange(10), attributes={})) |
| 756 |
self.io.write_dataset(self.f, |
| 757 |
DatasetBuilder('test_copy', self.f['test_dataset'], attributes={}), |
| 758 |
link_data=False) |
| 759 |
self.assertTrue(isinstance(self.f.get('test_copy', getlink=True), HardLink)) |
| 760 |
self.assertListEqual(self.f['test_dataset'][:].tolist(), |
| 761 |
self.f['test_copy'][:].tolist()) |
| 762 |
|
| 763 |
def test_link_h5py_dataset_h5dataio_input(self): |
| 764 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', np.arange(10), attributes={})) |
| 765 |
self.io.write_dataset(self.f, DatasetBuilder('test_softlink', |
| 766 |
H5DataIO(data=self.f['test_dataset'], |
| 767 |
link_data=True), |
| 768 |
attributes={})) |
| 769 |
self.assertTrue(isinstance(self.f.get('test_softlink', getlink=True), SoftLink)) |
| 770 |
|
| 771 |
def test_copy_h5py_dataset_h5dataio_input(self): |
| 772 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', np.arange(10), attributes={})) |
| 773 |
self.io.write_dataset(self.f, |
| 774 |
DatasetBuilder('test_copy', |
| 775 |
H5DataIO(data=self.f['test_dataset'], |
| 776 |
link_data=False), # Force dataset copy |
| 777 |
attributes={})) # Make sure the default behavior is set to link the data |
| 778 |
self.assertTrue(isinstance(self.f.get('test_copy', getlink=True), HardLink)) |
| 779 |
self.assertListEqual(self.f['test_dataset'][:].tolist(), |
| 780 |
self.f['test_copy'][:].tolist()) |
| 781 |
|
| 782 |
def test_list_fill_empty(self): |
| 783 |
dset = self.io.__list_fill__(self.f, 'empty_dataset', [], options={'dtype': int, 'io_settings': {}}) |
| 784 |
self.assertTupleEqual(dset.shape, (0,)) |
| 785 |
|
| 786 |
def test_list_fill_empty_no_dtype(self): |
| 787 |
with self.assertRaisesRegex(Exception, r"cannot add \S+ to [/\S]+ - could not determine type"): |
| 788 |
self.io.__list_fill__(self.f, 'empty_dataset', []) |
| 789 |
|
| 790 |
def test_read_str(self): |
| 791 |
a = ['a', 'bb', 'ccc', 'dddd', 'e'] |
| 792 |
attr = 'foobar' |
| 793 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, attributes={'test_attr': attr}, dtype='text')) |
| 794 |
self.io.close() |
| 795 |
with HDF5IO(self.path, 'r') as io: |
| 796 |
bldr = io.read_builder() |
| 797 |
np.array_equal(bldr['test_dataset'].data[:], ['a', 'bb', 'ccc', 'dddd', 'e']) |
| 798 |
np.array_equal(bldr['test_dataset'].attributes['test_attr'], attr) |
| 799 |
if H5PY_3: |
| 800 |
self.assertEqual(str(bldr['test_dataset'].data), |
| 801 |
'<StrDataset for HDF5 dataset "test_dataset": shape (5,), type "|O">') |
| 802 |
else: |
| 803 |
self.assertEqual(str(bldr['test_dataset'].data), |
| 804 |
'<HDF5 dataset "test_dataset": shape (5,), type "|O">') |
| 805 |
|
| 806 |
def test_read_scalar_compound(self): |
| 807 |
cmpd_dtype = np.dtype([('x', np.int32), ('y', np.float64)]) |
| 808 |
a = np.array((1, 0.1), dtype=cmpd_dtype) |
| 809 |
self.io.write_dataset(self.f, DatasetBuilder('test_dataset', a, |
| 810 |
dtype=[DtypeSpec('x', doc='x', dtype='int32'), |
| 811 |
DtypeSpec('y', doc='y', dtype='float64')])) |
| 812 |
self.io.close() |
| 813 |
with HDF5IO(self.path, 'r') as io: |
| 814 |
bldr = io.read_builder() |
| 815 |
np.testing.assert_array_equal(bldr['test_dataset'].data[()], a) |
| 816 |
|
| 817 |
|
| 818 |
class TestRoundTrip(TestCase): |
| 819 |
|
| 820 |
def setUp(self): |
| 821 |
self.manager = get_foo_buildmanager() |
| 822 |
self.path = get_temp_filepath() |
| 823 |
|
| 824 |
def tearDown(self): |
| 825 |
if os.path.exists(self.path): |
| 826 |
os.remove(self.path) |
| 827 |
|
| 828 |
def test_roundtrip_basic(self): |
| 829 |
# Setup all the data we need |
| 830 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 831 |
foobucket = FooBucket('bucket1', [foo1]) |
| 832 |
foofile = FooFile(buckets=[foobucket]) |
| 833 |
|
| 834 |
with HDF5IO(self.path, manager=self.manager, mode='w') as io: |
| 835 |
io.write(foofile) |
| 836 |
|
| 837 |
with HDF5IO(self.path, manager=self.manager, mode='r') as io: |
| 838 |
read_foofile = io.read() |
| 839 |
self.assertListEqual(foofile.buckets['bucket1'].foos['foo1'].my_data, |
| 840 |
read_foofile.buckets['bucket1'].foos['foo1'].my_data[:].tolist()) |
| 841 |
|
| 842 |
def test_roundtrip_empty_dataset(self): |
| 843 |
foo1 = Foo('foo1', [], "I am foo1", 17, 3.14) |
| 844 |
foobucket = FooBucket('bucket1', [foo1]) |
| 845 |
foofile = FooFile(buckets=[foobucket]) |
| 846 |
|
| 847 |
with HDF5IO(self.path, manager=self.manager, mode='w') as io: |
| 848 |
io.write(foofile) |
| 849 |
|
| 850 |
with HDF5IO(self.path, manager=self.manager, mode='r') as io: |
| 851 |
read_foofile = io.read() |
| 852 |
self.assertListEqual([], read_foofile.buckets['bucket1'].foos['foo1'].my_data[:].tolist()) |
| 853 |
|
| 854 |
def test_roundtrip_empty_group(self): |
| 855 |
foobucket = FooBucket('bucket1', []) |
| 856 |
foofile = FooFile(buckets=[foobucket]) |
| 857 |
|
| 858 |
with HDF5IO(self.path, manager=self.manager, mode='w') as io: |
| 859 |
io.write(foofile) |
| 860 |
|
| 861 |
with HDF5IO(self.path, manager=self.manager, mode='r') as io: |
| 862 |
read_foofile = io.read() |
| 863 |
self.assertDictEqual({}, read_foofile.buckets['bucket1'].foos) |
| 864 |
|
| 865 |
def test_roundtrip_pathlib_path(self): |
| 866 |
pathlib_path = Path(self.path) |
| 867 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 868 |
foobucket = FooBucket('bucket1', [foo1]) |
| 869 |
foofile = FooFile([foobucket]) |
| 870 |
|
| 871 |
with HDF5IO(pathlib_path, manager=self.manager, mode='w') as io: |
| 872 |
io.write(foofile) |
| 873 |
|
| 874 |
with HDF5IO(pathlib_path, manager=self.manager, mode='r') as io: |
| 875 |
read_foofile = io.read() |
| 876 |
self.assertListEqual(foofile.buckets['bucket1'].foos['foo1'].my_data, |
| 877 |
read_foofile.buckets['bucket1'].foos['foo1'].my_data[:].tolist()) |
| 878 |
|
| 879 |
@unittest.skipIf(not LINKML_INSTALLED, "optional LinkML module is not installed") |
| 880 |
def test_roundtrip_TermSetWrapper_dataset(self): |
| 881 |
terms = TermSet(term_schema_path='tests/unit/example_test_term_set.yaml') |
| 882 |
foo = Foo(name="species", attr1='attr1', attr2=0, |
| 883 |
my_data=TermSetWrapper(value=['Homo sapiens', 'Mus musculus'], |
| 884 |
termset=terms)) |
| 885 |
|
| 886 |
foobucket = FooBucket('bucket1', [foo]) |
| 887 |
foofile = FooFile(buckets=[foobucket]) |
| 888 |
|
| 889 |
with HDF5IO(self.path, manager=get_foo_buildmanager("text"), mode='w', herd_path='./HERD.zip') as io: |
| 890 |
io.write(foofile) |
| 891 |
|
| 892 |
with HDF5IO(self.path, manager=get_foo_buildmanager("text"), mode='r') as io: |
| 893 |
read_foofile = io.read() |
| 894 |
self.assertListEqual(foofile.buckets['bucket1'].foos['species'].my_data.value, |
| 895 |
read_foofile.buckets['bucket1'].foos['species'].my_data[:].tolist()) |
| 896 |
remove_test_file('./HERD.zip') |
| 897 |
|
| 898 |
@unittest.skipIf(not LINKML_INSTALLED, "optional LinkML module is not installed") |
| 899 |
def test_roundtrip_TermSetWrapper_attribute(self): |
| 900 |
terms = TermSet(term_schema_path='tests/unit/example_test_term_set.yaml') |
| 901 |
foo = Foo(name="species", attr1=TermSetWrapper(value='Homo sapiens', termset=terms), |
| 902 |
attr2=0, my_data=[1,2,3]) |
| 903 |
foobucket = FooBucket('bucket1', [foo]) |
| 904 |
foofile = FooFile(buckets=[foobucket]) |
| 905 |
|
| 906 |
with HDF5IO(self.path, manager=self.manager, mode='w', herd_path='./HERD.zip') as io: |
| 907 |
io.write(foofile) |
| 908 |
|
| 909 |
with HDF5IO(self.path, manager=self.manager, mode='r') as io: |
| 910 |
read_foofile = io.read() |
| 911 |
self.assertEqual(foofile.buckets['bucket1'].foos['species'].attr1.value, |
| 912 |
read_foofile.buckets['bucket1'].foos['species'].attr1) |
| 913 |
remove_test_file('./HERD.zip') |
| 914 |
|
| 915 |
|
| 916 |
class TestHDF5IO(TestCase): |
| 917 |
|
| 918 |
def setUp(self): |
| 919 |
self.manager = get_foo_buildmanager() |
| 920 |
self.path = get_temp_filepath() |
| 921 |
|
| 922 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 923 |
foobucket = FooBucket('bucket1', [foo1]) |
| 924 |
self.foofile = FooFile(buckets=[foobucket]) |
| 925 |
|
| 926 |
self.file_obj = None |
| 927 |
|
| 928 |
def tearDown(self): |
| 929 |
if os.path.exists(self.path): |
| 930 |
os.remove(self.path) |
| 931 |
|
| 932 |
if self.file_obj is not None: |
| 933 |
fn = self.file_obj.filename |
| 934 |
self.file_obj.close() |
| 935 |
if os.path.exists(fn): |
| 936 |
os.remove(fn) |
| 937 |
|
| 938 |
def test_constructor(self): |
| 939 |
with HDF5IO(self.path, manager=self.manager, mode='w') as io: |
| 940 |
self.assertEqual(io.manager, self.manager) |
| 941 |
self.assertEqual(io.source, self.path) |
| 942 |
|
| 943 |
def test_delete_with_incomplete_construction_missing_file(self): |
| 944 |
""" |
| 945 |
Here we test what happens when `close` is called before `HDF5IO.__init__` has |
| 946 |
been completed. In this case, self.__file is missing. |
| 947 |
""" |
| 948 |
class MyHDF5IO(HDF5IO): |
| 949 |
def __init__(self): |
| 950 |
self.__open_links = [] |
| 951 |
raise ValueError("interrupt before HDF5IO.__file is initialized") |
| 952 |
|
| 953 |
with self.assertRaisesWith(exc_type=ValueError, exc_msg="interrupt before HDF5IO.__file is initialized"): |
| 954 |
with MyHDF5IO() as _: |
| 955 |
pass |
| 956 |
|
| 957 |
def test_delete_with_incomplete_construction_missing_open_files(self): |
| 958 |
""" |
| 959 |
Here we test what happens when `close` is called before `HDF5IO.__init__` has |
| 960 |
been completed. In this case, self.__open_files is missing. |
| 961 |
""" |
| 962 |
class MyHDF5IO(HDF5IO): |
| 963 |
def __init__(self): |
| 964 |
self.__file = None |
| 965 |
raise ValueError("interrupt before HDF5IO.__open_files is initialized") |
| 966 |
|
| 967 |
with self.assertRaisesWith(exc_type=ValueError, exc_msg="interrupt before HDF5IO.__open_files is initialized"): |
| 968 |
with MyHDF5IO() as _: |
| 969 |
pass |
| 970 |
|
| 971 |
def test_set_file_mismatch(self): |
| 972 |
self.file_obj = File(get_temp_filepath(), 'w') |
| 973 |
err_msg = ("You argued '%s' as this object's path, but supplied a file with filename: %s" |
| 974 |
% (self.path, self.file_obj.filename)) |
| 975 |
with self.assertRaisesWith(ValueError, err_msg): |
| 976 |
HDF5IO(self.path, manager=self.manager, mode='w', file=self.file_obj) |
| 977 |
|
| 978 |
def test_pathlib_path(self): |
| 979 |
pathlib_path = Path(self.path) |
| 980 |
with HDF5IO(pathlib_path, mode='w') as io: |
| 981 |
self.assertEqual(io.source, self.path) |
| 982 |
|
| 983 |
def test_path_or_file(self): |
| 984 |
with self.assertRaisesWith(ValueError, "Either the 'path' or 'file' argument must be supplied."): |
| 985 |
HDF5IO() |
| 986 |
|
| 987 |
|
| 988 |
class TestCacheSpec(TestCase): |
| 989 |
|
| 990 |
def setUp(self): |
| 991 |
self.manager = get_foo_buildmanager() |
| 992 |
self.path = get_temp_filepath() |
| 993 |
|
| 994 |
def tearDown(self): |
| 995 |
if os.path.exists(self.path): |
| 996 |
os.remove(self.path) |
| 997 |
|
| 998 |
def test_cache_spec(self): |
| 999 |
foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) |
| 1000 |
foo2 = Foo('foo2', [5, 6, 7, 8, 9], "I am foo2", 34, 6.28) |
| 1001 |
foobucket = FooBucket('bucket1', [foo1, foo2]) |
| 1002 |
foofile = FooFile(buckets=[foobucket]) |
| 1003 |
|
| 1004 |
with HDF5IO(self.path, manager=self.manager, mode='w') as io: |
| 1005 |
io.write(foofile) |
| 1006 |
|
| 1007 |
ns_catalog = NamespaceCatalog() |
| 1008 |
HDF5IO.load_namespaces(ns_catalog, self.path) |
| 1009 |
self.assertEqual(ns_catalog.namespaces, (CORE_NAMESPACE,)) |
| 1010 |
source_types = CacheSpecTestHelper.get_types(io.manager.namespace_catalog) |
| 1011 |
read_types = CacheSpecTestHelper.get_types(ns_catalog) |
| 1012 |
self.assertSetEqual(source_types, read_types) |
| 1013 |
|
| 1014 |
|
| 1015 |
class TestNoCacheSpec(TestCase): |
| 1016 |
|
| 1017 |
def setUp(self): |
| 1018 |
self.manager = get_foo_buildmanager() |
| 1019 |
self.path = get_temp_filepath() |
| 1020 |
|
| 1021 |
def tearDown(self): |
| 1022 |
if os.path.exists(self.path): |
| 1023 |
os.remove(self.path) |
| 1024 |
|
| 1025 |
def test_no_cache_spec(self): |
| 1026 |
# Setup all the data we need |
| 1027 |
foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) |
| 1028 |
foo2 = Foo('foo2', [5, 6, 7, 8, 9], "I am foo2", 34, 6.28) |
| 1029 |
foobucket = FooBucket('bucket1', [foo1, foo2]) |
| 1030 |
foofile = FooFile(buckets=[foobucket]) |
| 1031 |
|
| 1032 |
with HDF5IO(self.path, manager=self.manager, mode='w') as io: |
| 1033 |
io.write(foofile, cache_spec=False) |
| 1034 |
|
| 1035 |
with File(self.path, 'r') as f: |
| 1036 |
self.assertNotIn('specifications', f) |
| 1037 |
|
| 1038 |
|
| 1039 |
class TestHERDIO(TestCase): |
| 1040 |
|
| 1041 |
def setUp(self): |
| 1042 |
self.manager = get_foo_buildmanager() |
| 1043 |
self.path = get_temp_filepath() |
| 1044 |
|
| 1045 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 1046 |
foobucket = FooBucket('bucket1', [foo1]) |
| 1047 |
self.foofile = FooFile(buckets=[foobucket]) |
| 1048 |
|
| 1049 |
with HDF5IO(self.path, manager=self.manager, mode='w') as io: |
| 1050 |
io.write(self.foofile) |
| 1051 |
|
| 1052 |
def remove_er_files(self): |
| 1053 |
remove_test_file('./entities.tsv') |
| 1054 |
remove_test_file('./entity_keys.tsv') |
| 1055 |
remove_test_file('./objects.tsv') |
| 1056 |
remove_test_file('./object_keys.tsv') |
| 1057 |
remove_test_file('./keys.tsv') |
| 1058 |
remove_test_file('./files.tsv') |
| 1059 |
remove_test_file('./HERD.zip') |
| 1060 |
|
| 1061 |
def child_tsv(self, herd): |
| 1062 |
for child in herd.children: |
| 1063 |
df = child.to_dataframe() |
| 1064 |
df.to_csv('./'+child.name+'.tsv', sep='\t', index=False) |
| 1065 |
|
| 1066 |
def zip_child(self, zip_file): |
| 1067 |
files = glob('*.tsv') |
| 1068 |
with zipfile.ZipFile(zip_file, 'w') as zipF: |
| 1069 |
for file in files: |
| 1070 |
zipF.write(file) |
| 1071 |
|
| 1072 |
def test_io_read_herd(self): |
| 1073 |
er = HERD() |
| 1074 |
data = Data(name="species", data=['Homo sapiens', 'Mus musculus']) |
| 1075 |
er.add_ref(file=self.foofile, |
| 1076 |
container=data, |
| 1077 |
key='key1', |
| 1078 |
entity_id='entity_id1', |
| 1079 |
entity_uri='entity1') |
| 1080 |
er.to_zip(path='./HERD.zip') |
| 1081 |
with HDF5IO(self.path, manager=self.manager, mode='r', herd_path='./HERD.zip') as io: |
| 1082 |
container = io.read() |
| 1083 |
self.assertIsInstance(io.herd, HERD) |
| 1084 |
self.assertIsInstance(container.get_linked_resources(), HERD) |
| 1085 |
self.remove_er_files() |
| 1086 |
|
| 1087 |
def test_io_read_herd_file_warn(self): |
| 1088 |
er = HERD() |
| 1089 |
data = Data(name="species", data=['Homo sapiens', 'Mus musculus']) |
| 1090 |
er.add_ref(file=self.foofile, |
| 1091 |
container=data, |
| 1092 |
key='key1', |
| 1093 |
entity_id='entity_id1', |
| 1094 |
entity_uri='entity1') |
| 1095 |
er.to_zip(path='./HERD.zip') |
| 1096 |
|
| 1097 |
with HDF5IO(self.path, manager=self.manager, mode='r', herd_path='wrong_path') as io: |
| 1098 |
with self.assertWarns(Warning): |
| 1099 |
io.read() |
| 1100 |
|
| 1101 |
self.remove_er_files() |
| 1102 |
|
| 1103 |
def test_io_read_herd_value_warn(self): |
| 1104 |
er = HERD() |
| 1105 |
data = Data(name="species", data=['Homo sapiens', 'Mus musculus']) |
| 1106 |
er.add_ref(file=self.foofile, |
| 1107 |
container=data, |
| 1108 |
key='key1', |
| 1109 |
entity_id='entity_id1', |
| 1110 |
entity_uri='entity1') |
| 1111 |
er.to_zip(path='./HERD.zip') |
| 1112 |
|
| 1113 |
self.child_tsv(herd=er) |
| 1114 |
|
| 1115 |
df = er.entities.to_dataframe() |
| 1116 |
df.at[0, ('keys_idx')] = 10 # Change key_ix 0 to 10 |
| 1117 |
df.to_csv('./entities.tsv', sep='\t', index=False) |
| 1118 |
|
| 1119 |
self.zip_child(zip_file='HERD.zip') |
| 1120 |
with HDF5IO(self.path, manager=self.manager, mode='r', herd_path='./HERD.zip') as io: |
| 1121 |
with self.assertWarns(Warning): |
| 1122 |
io.read() |
| 1123 |
|
| 1124 |
self.remove_er_files() |
| 1125 |
|
| 1126 |
@unittest.skipIf(not LINKML_INSTALLED, "optional LinkML module is not installed") |
| 1127 |
def test_io_write_extend_herd(self): |
| 1128 |
""" |
| 1129 |
Test the optional write of HERD with extending an existing HERD instance. |
| 1130 |
""" |
| 1131 |
terms = TermSet(term_schema_path='tests/unit/example_test_term_set.yaml') |
| 1132 |
foo = Foo(name="species", attr1='attr1', attr2=0, |
| 1133 |
my_data=TermSetWrapper(value=['Homo sapiens'], |
| 1134 |
termset=terms)) |
| 1135 |
|
| 1136 |
foobucket = FooBucket('bucket1', [foo]) |
| 1137 |
foofile = FooFile(buckets=[foobucket]) |
| 1138 |
|
| 1139 |
er = HERD(type_map=self.manager.type_map) |
| 1140 |
er.add_ref(file=foofile, |
| 1141 |
container=foofile, |
| 1142 |
key='special', |
| 1143 |
entity_id="id11", |
| 1144 |
entity_uri='url11') |
| 1145 |
|
| 1146 |
with HDF5IO(self.path, manager=get_foo_buildmanager("text"), mode='w', herd_path='./HERD.zip') as io: |
| 1147 |
io.write(foofile, herd=er) |
| 1148 |
|
| 1149 |
with HDF5IO(self.path, manager=get_foo_buildmanager("text"), mode='r', herd_path='./HERD.zip') as io: |
| 1150 |
read_foofile = io.read() |
| 1151 |
read_herd = io.herd |
| 1152 |
|
| 1153 |
self.assertListEqual(foofile.buckets['bucket1'].foos['species'].my_data.value, |
| 1154 |
read_foofile.buckets['bucket1'].foos['species'].my_data[:].tolist()) |
| 1155 |
|
| 1156 |
self.assertEqual(read_herd.keys.data, [('special',), ('Homo sapiens',)]) |
| 1157 |
self.assertEqual(read_herd.entities.data[0], ('id11', 'url11')) |
| 1158 |
self.assertEqual(read_herd.entities.data[1], ('NCBI_TAXON:9606', |
| 1159 |
'https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=9606')) |
| 1160 |
self.assertEqual(read_herd.objects.data[0], |
| 1161 |
(0, read_foofile.object_id, 'FooFile', '', '')) |
| 1162 |
|
| 1163 |
self.remove_er_files() |
| 1164 |
|
| 1165 |
|
| 1166 |
class TestMultiWrite(TestCase): |
| 1167 |
|
| 1168 |
def setUp(self): |
| 1169 |
self.path = get_temp_filepath() |
| 1170 |
foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) |
| 1171 |
foo2 = Foo('foo2', [5, 6, 7, 8, 9], "I am foo2", 34, 6.28) |
| 1172 |
foobucket = FooBucket('bucket1', [foo1, foo2]) |
| 1173 |
self.foofile = FooFile(buckets=[foobucket]) |
| 1174 |
|
| 1175 |
def tearDown(self): |
| 1176 |
if os.path.exists(self.path): |
| 1177 |
os.remove(self.path) |
| 1178 |
|
| 1179 |
def test_double_write_new_manager(self): |
| 1180 |
"""Test writing to a container in write mode twice using a new manager without changing the container.""" |
| 1181 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='w') as io: |
| 1182 |
io.write(self.foofile) |
| 1183 |
|
| 1184 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='w') as io: |
| 1185 |
io.write(self.foofile) |
| 1186 |
|
| 1187 |
# check that new bucket was written |
| 1188 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='r') as io: |
| 1189 |
read_foofile = io.read() |
| 1190 |
self.assertContainerEqual(read_foofile, self.foofile) |
| 1191 |
|
| 1192 |
def test_double_write_same_manager(self): |
| 1193 |
"""Test writing to a container in write mode twice using the same manager without changing the container.""" |
| 1194 |
manager = get_foo_buildmanager() |
| 1195 |
with HDF5IO(self.path, manager=manager, mode='w') as io: |
| 1196 |
io.write(self.foofile) |
| 1197 |
|
| 1198 |
with HDF5IO(self.path, manager=manager, mode='w') as io: |
| 1199 |
io.write(self.foofile) |
| 1200 |
|
| 1201 |
# check that new bucket was written |
| 1202 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='r') as io: |
| 1203 |
read_foofile = io.read() |
| 1204 |
self.assertContainerEqual(read_foofile, self.foofile) |
| 1205 |
|
| 1206 |
@unittest.skip('Functionality not yet supported') |
| 1207 |
def test_double_append_new_manager(self): |
| 1208 |
"""Test writing to a container in append mode twice using a new manager without changing the container.""" |
| 1209 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='a') as io: |
| 1210 |
io.write(self.foofile) |
| 1211 |
|
| 1212 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='a') as io: |
| 1213 |
io.write(self.foofile) |
| 1214 |
|
| 1215 |
# check that new bucket was written |
| 1216 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='r') as io: |
| 1217 |
read_foofile = io.read() |
| 1218 |
self.assertContainerEqual(read_foofile, self.foofile) |
| 1219 |
|
| 1220 |
@unittest.skip('Functionality not yet supported') |
| 1221 |
def test_double_append_same_manager(self): |
| 1222 |
"""Test writing to a container in append mode twice using the same manager without changing the container.""" |
| 1223 |
manager = get_foo_buildmanager() |
| 1224 |
with HDF5IO(self.path, manager=manager, mode='a') as io: |
| 1225 |
io.write(self.foofile) |
| 1226 |
|
| 1227 |
with HDF5IO(self.path, manager=manager, mode='a') as io: |
| 1228 |
io.write(self.foofile) |
| 1229 |
|
| 1230 |
# check that new bucket was written |
| 1231 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='r') as io: |
| 1232 |
read_foofile = io.read() |
| 1233 |
self.assertContainerEqual(read_foofile, self.foofile) |
| 1234 |
|
| 1235 |
def test_write_add_write(self): |
| 1236 |
"""Test writing a container, adding to the in-memory container, then overwriting the same file.""" |
| 1237 |
manager = get_foo_buildmanager() |
| 1238 |
with HDF5IO(self.path, manager=manager, mode='w') as io: |
| 1239 |
io.write(self.foofile) |
| 1240 |
|
| 1241 |
# append new container to in-memory container |
| 1242 |
foo3 = Foo('foo3', [10, 20], "I am foo3", 2, 0.1) |
| 1243 |
new_bucket1 = FooBucket('new_bucket1', [foo3]) |
| 1244 |
self.foofile.add_bucket(new_bucket1) |
| 1245 |
|
| 1246 |
# write to same file with same manager, overwriting existing file |
| 1247 |
with HDF5IO(self.path, manager=manager, mode='w') as io: |
| 1248 |
io.write(self.foofile) |
| 1249 |
|
| 1250 |
# check that new bucket was written |
| 1251 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='r') as io: |
| 1252 |
read_foofile = io.read() |
| 1253 |
self.assertEqual(len(read_foofile.buckets), 2) |
| 1254 |
self.assertContainerEqual(read_foofile.buckets['new_bucket1'], new_bucket1) |
| 1255 |
|
| 1256 |
def test_write_add_append_bucket(self): |
| 1257 |
"""Test appending a container to a file.""" |
| 1258 |
manager = get_foo_buildmanager() |
| 1259 |
with HDF5IO(self.path, manager=manager, mode='w') as io: |
| 1260 |
io.write(self.foofile) |
| 1261 |
|
| 1262 |
foo3 = Foo('foo3', [10, 20], "I am foo3", 2, 0.1) |
| 1263 |
new_bucket1 = FooBucket('new_bucket1', [foo3]) |
| 1264 |
|
| 1265 |
# append to same file with same manager, overwriting existing file |
| 1266 |
with HDF5IO(self.path, manager=manager, mode='a') as io: |
| 1267 |
read_foofile = io.read() |
| 1268 |
# append to read container and call write |
| 1269 |
read_foofile.add_bucket(new_bucket1) |
| 1270 |
io.write(read_foofile) |
| 1271 |
|
| 1272 |
# check that new bucket was written |
| 1273 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='r') as io: |
| 1274 |
read_foofile = io.read() |
| 1275 |
self.assertEqual(len(read_foofile.buckets), 2) |
| 1276 |
self.assertContainerEqual(read_foofile.buckets['new_bucket1'], new_bucket1) |
| 1277 |
|
| 1278 |
def test_write_add_append_double_write(self): |
| 1279 |
"""Test using the same IO object to append a container to a file twice.""" |
| 1280 |
manager = get_foo_buildmanager() |
| 1281 |
with HDF5IO(self.path, manager=manager, mode='w') as io: |
| 1282 |
io.write(self.foofile) |
| 1283 |
|
| 1284 |
foo3 = Foo('foo3', [10, 20], "I am foo3", 2, 0.1) |
| 1285 |
new_bucket1 = FooBucket('new_bucket1', [foo3]) |
| 1286 |
foo4 = Foo('foo4', [10, 20], "I am foo4", 2, 0.1) |
| 1287 |
new_bucket2 = FooBucket('new_bucket2', [foo4]) |
| 1288 |
|
| 1289 |
# append to same file with same manager, overwriting existing file |
| 1290 |
with HDF5IO(self.path, manager=manager, mode='a') as io: |
| 1291 |
read_foofile = io.read() |
| 1292 |
# append to read container and call write |
| 1293 |
read_foofile.add_bucket(new_bucket1) |
| 1294 |
io.write(read_foofile) |
| 1295 |
|
| 1296 |
# append to read container again and call write again |
| 1297 |
read_foofile.add_bucket(new_bucket2) |
| 1298 |
io.write(read_foofile) |
| 1299 |
|
| 1300 |
# check that both new buckets were written |
| 1301 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='r') as io: |
| 1302 |
read_foofile = io.read() |
| 1303 |
self.assertEqual(len(read_foofile.buckets), 3) |
| 1304 |
self.assertContainerEqual(read_foofile.buckets['new_bucket1'], new_bucket1) |
| 1305 |
self.assertContainerEqual(read_foofile.buckets['new_bucket2'], new_bucket2) |
| 1306 |
|
| 1307 |
|
| 1308 |
class HDF5IOMultiFileTest(TestCase): |
| 1309 |
"""Tests for h5tools IO tools""" |
| 1310 |
|
| 1311 |
def setUp(self): |
| 1312 |
numfiles = 3 |
| 1313 |
self.paths = [get_temp_filepath() for i in range(numfiles)] |
| 1314 |
|
| 1315 |
# On Windows h5py cannot truncate an open file in write mode. |
| 1316 |
# The temp file will be closed before h5py truncates it |
| 1317 |
# and will be removed during the tearDown step. |
| 1318 |
self.io = [HDF5IO(i, mode='a', manager=get_foo_buildmanager()) for i in self.paths] |
| 1319 |
self.f = [i._file for i in self.io] |
| 1320 |
|
| 1321 |
def tearDown(self): |
| 1322 |
# Close all the files |
| 1323 |
for i in self.io: |
| 1324 |
i.close() |
| 1325 |
del i |
| 1326 |
self.io = None |
| 1327 |
self.f = None |
| 1328 |
# Make sure the files have been deleted |
| 1329 |
for tf in self.paths: |
| 1330 |
try: |
| 1331 |
os.remove(tf) |
| 1332 |
except OSError: |
| 1333 |
pass |
| 1334 |
|
| 1335 |
def test_copy_file_with_external_links(self): |
| 1336 |
# Create the first file |
| 1337 |
foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) |
| 1338 |
bucket1 = FooBucket('bucket1', [foo1]) |
| 1339 |
foofile1 = FooFile(buckets=[bucket1]) |
| 1340 |
|
| 1341 |
# Write the first file |
| 1342 |
self.io[0].write(foofile1) |
| 1343 |
|
| 1344 |
# Create the second file |
| 1345 |
read_foofile1 = self.io[0].read() |
| 1346 |
foo2 = Foo('foo2', read_foofile1.buckets['bucket1'].foos['foo1'].my_data, "I am foo2", 34, 6.28) |
| 1347 |
bucket2 = FooBucket('bucket2', [foo2]) |
| 1348 |
foofile2 = FooFile(buckets=[bucket2]) |
| 1349 |
# Write the second file |
| 1350 |
self.io[1].write(foofile2) |
| 1351 |
self.io[1].close() |
| 1352 |
self.io[0].close() # Don't forget to close the first file too |
| 1353 |
|
| 1354 |
# Copy the file |
| 1355 |
self.io[2].close() |
| 1356 |
|
| 1357 |
with self.assertWarns(DeprecationWarning): |
| 1358 |
HDF5IO.copy_file(source_filename=self.paths[1], |
| 1359 |
dest_filename=self.paths[2], |
| 1360 |
expand_external=True, |
| 1361 |
expand_soft=False, |
| 1362 |
expand_refs=False) |
| 1363 |
|
| 1364 |
# Test that everything is working as expected |
| 1365 |
# Confirm that our original data file is correct |
| 1366 |
f1 = File(self.paths[0], 'r') |
| 1367 |
self.assertIsInstance(f1.get('/buckets/bucket1/foo_holder/foo1/my_data', getlink=True), HardLink) |
| 1368 |
# Confirm that we successfully created and External Link in our second file |
| 1369 |
f2 = File(self.paths[1], 'r') |
| 1370 |
self.assertIsInstance(f2.get('/buckets/bucket2/foo_holder/foo2/my_data', getlink=True), ExternalLink) |
| 1371 |
# Confirm that we successfully resolved the External Link when we copied our second file |
| 1372 |
f3 = File(self.paths[2], 'r') |
| 1373 |
self.assertIsInstance(f3.get('/buckets/bucket2/foo_holder/foo2/my_data', getlink=True), HardLink) |
| 1374 |
|
| 1375 |
|
| 1376 |
class TestCloseLinks(TestCase): |
| 1377 |
|
| 1378 |
def setUp(self): |
| 1379 |
self.path1 = get_temp_filepath() |
| 1380 |
self.path2 = get_temp_filepath() |
| 1381 |
|
| 1382 |
def tearDown(self): |
| 1383 |
if self.path1 is not None and os.path.exists(self.path1): |
| 1384 |
os.remove(self.path1) # linked file may not be closed |
| 1385 |
if self.path2 is not None and os.path.exists(self.path2): |
| 1386 |
os.remove(self.path2) |
| 1387 |
|
| 1388 |
def test_close_linked_files_auto(self): |
| 1389 |
"""Test closing a file with close_links=True (default). |
| 1390 |
""" |
| 1391 |
# Create the first file |
| 1392 |
foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) |
| 1393 |
bucket1 = FooBucket('bucket1', [foo1]) |
| 1394 |
foofile1 = FooFile(buckets=[bucket1]) |
| 1395 |
|
| 1396 |
# Write the first file |
| 1397 |
with HDF5IO(self.path1, mode='w', manager=get_foo_buildmanager()) as io: |
| 1398 |
io.write(foofile1) |
| 1399 |
|
| 1400 |
# Create the second file |
| 1401 |
manager = get_foo_buildmanager() # use the same manager for read and write so that links work |
| 1402 |
with HDF5IO(self.path1, mode='r', manager=manager) as read_io: |
| 1403 |
read_foofile1 = read_io.read() |
| 1404 |
foofile2 = FooFile(foo_link=read_foofile1.buckets['bucket1'].foos['foo1']) # cross-file link |
| 1405 |
|
| 1406 |
# Write the second file |
| 1407 |
with HDF5IO(self.path2, mode='w', manager=manager) as write_io: |
| 1408 |
write_io.write(foofile2) |
| 1409 |
|
| 1410 |
with HDF5IO(self.path2, mode='a', manager=get_foo_buildmanager()) as new_io1: |
| 1411 |
read_foofile2 = new_io1.read() # keep reference to container in memory |
| 1412 |
|
| 1413 |
self.assertFalse(read_foofile2.foo_link.my_data) |
| 1414 |
|
| 1415 |
# should be able to reopen both files |
| 1416 |
with HDF5IO(self.path1, mode='a', manager=get_foo_buildmanager()) as new_io3: |
| 1417 |
new_io3.read() |
| 1418 |
|
| 1419 |
def test_close_linked_files_explicit(self): |
| 1420 |
"""Test closing a file with close_links=False and calling close_linked_files(). |
| 1421 |
""" |
| 1422 |
# Create the first file |
| 1423 |
foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) |
| 1424 |
bucket1 = FooBucket('bucket1', [foo1]) |
| 1425 |
foofile1 = FooFile(buckets=[bucket1]) |
| 1426 |
|
| 1427 |
# Write the first file |
| 1428 |
with HDF5IO(self.path1, mode='w', manager=get_foo_buildmanager()) as io: |
| 1429 |
io.write(foofile1) |
| 1430 |
|
| 1431 |
# Create the second file |
| 1432 |
manager = get_foo_buildmanager() # use the same manager for read and write so that links work |
| 1433 |
with HDF5IO(self.path1, mode='r', manager=manager) as read_io: |
| 1434 |
read_foofile1 = read_io.read() |
| 1435 |
foofile2 = FooFile(foo_link=read_foofile1.buckets['bucket1'].foos['foo1']) # cross-file link |
| 1436 |
|
| 1437 |
# Write the second file |
| 1438 |
with HDF5IO(self.path2, mode='w', manager=manager) as write_io: |
| 1439 |
write_io.write(foofile2) |
| 1440 |
|
| 1441 |
new_io1 = HDF5IO(self.path2, mode='a', manager=get_foo_buildmanager()) |
| 1442 |
read_foofile2 = new_io1.read() # keep reference to container in memory |
| 1443 |
new_io1.close(close_links=False) # do not close the links |
| 1444 |
|
| 1445 |
self.assertTrue(read_foofile2.foo_link.my_data) |
| 1446 |
new_io1.close_linked_files() |
| 1447 |
self.assertFalse(read_foofile2.foo_link.my_data) |
| 1448 |
|
| 1449 |
# should be able to reopen both files |
| 1450 |
with HDF5IO(self.path1, mode='a', manager=get_foo_buildmanager()) as new_io3: |
| 1451 |
new_io3.read() |
| 1452 |
|
| 1453 |
def test_close_links_manually_and_close(self): |
| 1454 |
"""Test closing a file with close_links=False, manually closing open links, and calling close_linked_files(). |
| 1455 |
""" |
| 1456 |
# Create the first file |
| 1457 |
foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) |
| 1458 |
bucket1 = FooBucket('bucket1', [foo1]) |
| 1459 |
foofile1 = FooFile(buckets=[bucket1]) |
| 1460 |
|
| 1461 |
# Write the first file |
| 1462 |
with HDF5IO(self.path1, mode='w', manager=get_foo_buildmanager()) as io: |
| 1463 |
io.write(foofile1) |
| 1464 |
|
| 1465 |
# Create the second file |
| 1466 |
manager = get_foo_buildmanager() # use the same manager for read and write so that links work |
| 1467 |
with HDF5IO(self.path1, mode='r', manager=manager) as read_io: |
| 1468 |
read_foofile1 = read_io.read() |
| 1469 |
foofile2 = FooFile(foo_link=read_foofile1.buckets['bucket1'].foos['foo1']) # cross-file link |
| 1470 |
|
| 1471 |
# Write the second file |
| 1472 |
with HDF5IO(self.path2, mode='w', manager=manager) as write_io: |
| 1473 |
write_io.write(foofile2) |
| 1474 |
|
| 1475 |
new_io1 = HDF5IO(self.path2, mode='a', manager=get_foo_buildmanager()) |
| 1476 |
read_foofile2 = new_io1.read() # keep reference to container in memory |
| 1477 |
new_io1.close(close_links=False) # do not close the links |
| 1478 |
|
| 1479 |
self.assertTrue(read_foofile2.foo_link.my_data) |
| 1480 |
read_foofile2.foo_link.my_data.file.close() # explicitly close the file from the h5dataset |
| 1481 |
self.assertFalse(read_foofile2.foo_link.my_data) |
| 1482 |
new_io1.close_linked_files() # make sure this does not fail because the linked-to file is already closed |
| 1483 |
|
| 1484 |
def test_close_linked_files_not_disruptive(self): |
| 1485 |
"""Test closing a file with close_links=True (default) does not interfere with other open file handles. |
| 1486 |
""" |
| 1487 |
# Create the first file |
| 1488 |
foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) |
| 1489 |
bucket1 = FooBucket('bucket1', [foo1]) |
| 1490 |
foofile1 = FooFile(buckets=[bucket1]) |
| 1491 |
|
| 1492 |
# Write the first file |
| 1493 |
with HDF5IO(self.path1, mode='w', manager=get_foo_buildmanager()) as io: |
| 1494 |
io.write(foofile1) |
| 1495 |
|
| 1496 |
# Create the second file |
| 1497 |
manager = get_foo_buildmanager() # use the same manager for read and write so that links work |
| 1498 |
with HDF5IO(self.path1, mode='r', manager=manager) as read_io: |
| 1499 |
read_foofile1 = read_io.read() |
| 1500 |
foofile2 = FooFile(foo_link=read_foofile1.buckets['bucket1'].foos['foo1']) # cross-file link |
| 1501 |
|
| 1502 |
# Write the second file |
| 1503 |
with HDF5IO(self.path2, mode='w', manager=manager) as write_io: |
| 1504 |
write_io.write(foofile2) |
| 1505 |
|
| 1506 |
read_io = HDF5IO(self.path1, mode='r', manager=manager) |
| 1507 |
read_foofile1 = read_io.read() |
| 1508 |
|
| 1509 |
with HDF5IO(self.path2, mode='r', manager=get_foo_buildmanager()) as new_io1: |
| 1510 |
new_io1.read() # keep reference to container in memory |
| 1511 |
|
| 1512 |
self.assertTrue(read_io) # make sure read_io is not closed |
| 1513 |
read_io.close() |
| 1514 |
|
| 1515 |
|
| 1516 |
class HDF5IOInitNoFileTest(TestCase): |
| 1517 |
""" Test if file does not exist, init with mode (r, r+) throws error, all others succeed """ |
| 1518 |
|
| 1519 |
def test_init_no_file_r(self): |
| 1520 |
self.path = "test_init_nofile_r.h5" |
| 1521 |
with self.assertRaisesWith(UnsupportedOperation, |
| 1522 |
"Unable to open file %s in 'r' mode. File does not exist." % self.path): |
| 1523 |
HDF5IO(self.path, mode='r') |
| 1524 |
|
| 1525 |
def test_init_no_file_rplus(self): |
| 1526 |
self.path = "test_init_nofile_rplus.h5" |
| 1527 |
with self.assertRaisesWith(UnsupportedOperation, |
| 1528 |
"Unable to open file %s in 'r+' mode. File does not exist." % self.path): |
| 1529 |
HDF5IO(self.path, mode='r+') |
| 1530 |
|
| 1531 |
def test_init_no_file_ok(self): |
| 1532 |
# test that no errors are thrown |
| 1533 |
modes = ('w', 'w-', 'x', 'a') |
| 1534 |
for m in modes: |
| 1535 |
self.path = "test_init_nofile.h5" |
| 1536 |
with HDF5IO(self.path, mode=m): |
| 1537 |
pass |
| 1538 |
if os.path.exists(self.path): |
| 1539 |
os.remove(self.path) |
| 1540 |
|
| 1541 |
|
| 1542 |
class HDF5IOInitFileExistsTest(TestCase): |
| 1543 |
""" Test if file exists, init with mode w-/x throws error, all others succeed """ |
| 1544 |
|
| 1545 |
def setUp(self): |
| 1546 |
self.path = get_temp_filepath() |
| 1547 |
temp_io = HDF5IO(self.path, mode='w') |
| 1548 |
temp_io.close() |
| 1549 |
self.io = None |
| 1550 |
|
| 1551 |
def tearDown(self): |
| 1552 |
if self.io is not None: |
| 1553 |
self.io.close() |
| 1554 |
del self.io |
| 1555 |
if os.path.exists(self.path): |
| 1556 |
os.remove(self.path) |
| 1557 |
|
| 1558 |
def test_init_wminus_file_exists(self): |
| 1559 |
with self.assertRaisesWith(UnsupportedOperation, |
| 1560 |
"Unable to open file %s in 'w-' mode. File already exists." % self.path): |
| 1561 |
self.io = HDF5IO(self.path, mode='w-') |
| 1562 |
|
| 1563 |
def test_init_x_file_exists(self): |
| 1564 |
with self.assertRaisesWith(UnsupportedOperation, |
| 1565 |
"Unable to open file %s in 'x' mode. File already exists." % self.path): |
| 1566 |
self.io = HDF5IO(self.path, mode='x') |
| 1567 |
|
| 1568 |
def test_init_file_exists_ok(self): |
| 1569 |
# test that no errors are thrown |
| 1570 |
modes = ('r', 'r+', 'w', 'a') |
| 1571 |
for m in modes: |
| 1572 |
with HDF5IO(self.path, mode=m): |
| 1573 |
pass |
| 1574 |
|
| 1575 |
|
| 1576 |
class HDF5IOReadNoDataTest(TestCase): |
| 1577 |
""" Test if file exists and there is no data, read with mode (r, r+, a) throws error """ |
| 1578 |
|
| 1579 |
def setUp(self): |
| 1580 |
self.path = get_temp_filepath() |
| 1581 |
temp_io = HDF5IO(self.path, mode='w') |
| 1582 |
temp_io.close() |
| 1583 |
self.io = None |
| 1584 |
|
| 1585 |
def tearDown(self): |
| 1586 |
if self.io is not None: |
| 1587 |
self.io.close() |
| 1588 |
del self.io |
| 1589 |
|
| 1590 |
if os.path.exists(self.path): |
| 1591 |
os.remove(self.path) |
| 1592 |
|
| 1593 |
def test_read_no_data_r(self): |
| 1594 |
self.io = HDF5IO(self.path, mode='r') |
| 1595 |
with self.assertRaisesWith(UnsupportedOperation, |
| 1596 |
"Cannot read data from file %s in mode 'r'. There are no values." % self.path): |
| 1597 |
self.io.read() |
| 1598 |
|
| 1599 |
def test_read_no_data_rplus(self): |
| 1600 |
self.io = HDF5IO(self.path, mode='r+') |
| 1601 |
with self.assertRaisesWith(UnsupportedOperation, |
| 1602 |
"Cannot read data from file %s in mode 'r+'. There are no values." % self.path): |
| 1603 |
self.io.read() |
| 1604 |
|
| 1605 |
def test_read_no_data_a(self): |
| 1606 |
self.io = HDF5IO(self.path, mode='a') |
| 1607 |
with self.assertRaisesWith(UnsupportedOperation, |
| 1608 |
"Cannot read data from file %s in mode 'a'. There are no values." % self.path): |
| 1609 |
self.io.read() |
| 1610 |
|
| 1611 |
|
| 1612 |
class HDF5IOReadData(TestCase): |
| 1613 |
""" Test if file exists and there is no data, read in mode (r, r+, a) is ok |
| 1614 |
and read in mode w throws error |
| 1615 |
""" |
| 1616 |
|
| 1617 |
def setUp(self): |
| 1618 |
self.path = get_temp_filepath() |
| 1619 |
foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) |
| 1620 |
bucket1 = FooBucket('bucket1', [foo1]) |
| 1621 |
self.foofile1 = FooFile(buckets=[bucket1]) |
| 1622 |
|
| 1623 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='w') as temp_io: |
| 1624 |
temp_io.write(self.foofile1) |
| 1625 |
self.io = None |
| 1626 |
|
| 1627 |
def tearDown(self): |
| 1628 |
if self.io is not None: |
| 1629 |
self.io.close() |
| 1630 |
del self.io |
| 1631 |
if os.path.exists(self.path): |
| 1632 |
os.remove(self.path) |
| 1633 |
|
| 1634 |
def test_read_file_ok(self): |
| 1635 |
modes = ('r', 'r+', 'a') |
| 1636 |
for m in modes: |
| 1637 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode=m) as io: |
| 1638 |
io.read() |
| 1639 |
|
| 1640 |
def test_read_file_w(self): |
| 1641 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='w') as io: |
| 1642 |
with self.assertRaisesWith(UnsupportedOperation, |
| 1643 |
"Cannot read from file %s in mode 'w'. Please use mode 'r', 'r+', or 'a'." |
| 1644 |
% self.path): |
| 1645 |
read_foofile1 = io.read() |
| 1646 |
self.assertListEqual(self.foofile1.buckets['bucket1'].foos['foo1'].my_data, |
| 1647 |
read_foofile1.buckets['bucket1'].foos['foo1'].my_data[:].tolist()) |
| 1648 |
|
| 1649 |
|
| 1650 |
class HDF5IOReadBuilderClosed(TestCase): |
| 1651 |
"""Test if file exists but is closed, then read_builder raises an error. """ |
| 1652 |
|
| 1653 |
def setUp(self): |
| 1654 |
self.path = get_temp_filepath() |
| 1655 |
temp_io = HDF5IO(self.path, mode='w') |
| 1656 |
temp_io.close() |
| 1657 |
self.io = None |
| 1658 |
|
| 1659 |
def tearDown(self): |
| 1660 |
if self.io is not None: |
| 1661 |
self.io.close() |
| 1662 |
del self.io |
| 1663 |
|
| 1664 |
if os.path.exists(self.path): |
| 1665 |
os.remove(self.path) |
| 1666 |
|
| 1667 |
def test_read_closed(self): |
| 1668 |
self.io = HDF5IO(self.path, mode='r') |
| 1669 |
self.io.close() |
| 1670 |
msg = "Cannot read data from closed HDF5 file '%s'" % self.path |
| 1671 |
with self.assertRaisesWith(UnsupportedOperation, msg): |
| 1672 |
self.io.read_builder() |
| 1673 |
|
| 1674 |
|
| 1675 |
class HDF5IOWriteNoFile(TestCase): |
| 1676 |
""" Test if file does not exist, write in mode (w, w-, x, a) is ok """ |
| 1677 |
|
| 1678 |
def setUp(self): |
| 1679 |
foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) |
| 1680 |
bucket1 = FooBucket('bucket1', [foo1]) |
| 1681 |
self.foofile1 = FooFile(buckets=[bucket1]) |
| 1682 |
self.path = 'test_write_nofile.h5' |
| 1683 |
|
| 1684 |
def tearDown(self): |
| 1685 |
if os.path.exists(self.path): |
| 1686 |
os.remove(self.path) |
| 1687 |
|
| 1688 |
def test_write_no_file_w_ok(self): |
| 1689 |
self.__write_file('w') |
| 1690 |
|
| 1691 |
def test_write_no_file_wminus_ok(self): |
| 1692 |
self.__write_file('w-') |
| 1693 |
|
| 1694 |
def test_write_no_file_x_ok(self): |
| 1695 |
self.__write_file('x') |
| 1696 |
|
| 1697 |
def test_write_no_file_a_ok(self): |
| 1698 |
self.__write_file('a') |
| 1699 |
|
| 1700 |
def __write_file(self, mode): |
| 1701 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode=mode) as io: |
| 1702 |
io.write(self.foofile1) |
| 1703 |
|
| 1704 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='r') as io: |
| 1705 |
read_foofile = io.read() |
| 1706 |
self.assertListEqual(self.foofile1.buckets['bucket1'].foos['foo1'].my_data, |
| 1707 |
read_foofile.buckets['bucket1'].foos['foo1'].my_data[:].tolist()) |
| 1708 |
|
| 1709 |
|
| 1710 |
class HDF5IOWriteFileExists(TestCase): |
| 1711 |
""" Test if file exists, write in mode (r+, w, a) is ok and write in mode r throws error """ |
| 1712 |
|
| 1713 |
def setUp(self): |
| 1714 |
self.path = get_temp_filepath() |
| 1715 |
|
| 1716 |
foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) |
| 1717 |
bucket1 = FooBucket('bucket1', [foo1]) |
| 1718 |
self.foofile1 = FooFile(buckets=[bucket1]) |
| 1719 |
|
| 1720 |
foo2 = Foo('foo2', [0, 1, 2, 3, 4], "I am foo2", 17, 3.14) |
| 1721 |
bucket2 = FooBucket('bucket2', [foo2]) |
| 1722 |
self.foofile2 = FooFile(buckets=[bucket2]) |
| 1723 |
|
| 1724 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='w') as io: |
| 1725 |
io.write(self.foofile1) |
| 1726 |
self.io = None |
| 1727 |
|
| 1728 |
def tearDown(self): |
| 1729 |
if self.io is not None: |
| 1730 |
self.io.close() |
| 1731 |
del self.io |
| 1732 |
if os.path.exists(self.path): |
| 1733 |
os.remove(self.path) |
| 1734 |
|
| 1735 |
def test_write_rplus(self): |
| 1736 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='r+') as io: |
| 1737 |
# even though foofile1 and foofile2 have different names, writing a |
| 1738 |
# root object into a file that already has a root object, in r+ mode |
| 1739 |
# should throw an error |
| 1740 |
with self.assertRaisesRegex(ValueError, ".*(name already exists)"): |
| 1741 |
io.write(self.foofile2) |
| 1742 |
|
| 1743 |
def test_write_a(self): |
| 1744 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='a') as io: |
| 1745 |
# even though foofile1 and foofile2 have different names, writing a |
| 1746 |
# root object into a file that already has a root object, in a mode |
| 1747 |
# should throw an error |
| 1748 |
with self.assertRaisesRegex(ValueError, ".*(name already exists)"): |
| 1749 |
io.write(self.foofile2) |
| 1750 |
|
| 1751 |
def test_write_w(self): |
| 1752 |
# mode 'w' should overwrite contents of file |
| 1753 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='w') as io: |
| 1754 |
io.write(self.foofile2) |
| 1755 |
|
| 1756 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='r') as io: |
| 1757 |
read_foofile = io.read() |
| 1758 |
self.assertListEqual(self.foofile2.buckets['bucket2'].foos['foo2'].my_data, |
| 1759 |
read_foofile.buckets['bucket2'].foos['foo2'].my_data[:].tolist()) |
| 1760 |
|
| 1761 |
def test_write_r(self): |
| 1762 |
with HDF5IO(self.path, manager=get_foo_buildmanager(), mode='r') as io: |
| 1763 |
with self.assertRaisesWith(UnsupportedOperation, |
| 1764 |
("Cannot write to file %s in mode 'r'. " |
| 1765 |
"Please use mode 'r+', 'w', 'w-', 'x', or 'a'") % self.path): |
| 1766 |
io.write(self.foofile2) |
| 1767 |
|
| 1768 |
|
| 1769 |
class TestWritten(TestCase): |
| 1770 |
|
| 1771 |
def setUp(self): |
| 1772 |
self.manager = get_foo_buildmanager() |
| 1773 |
self.path = get_temp_filepath() |
| 1774 |
foo1 = Foo('foo1', [0, 1, 2, 3, 4], "I am foo1", 17, 3.14) |
| 1775 |
foo2 = Foo('foo2', [5, 6, 7, 8, 9], "I am foo2", 34, 6.28) |
| 1776 |
foobucket = FooBucket('bucket1', [foo1, foo2]) |
| 1777 |
self.foofile = FooFile(buckets=[foobucket]) |
| 1778 |
|
| 1779 |
def tearDown(self): |
| 1780 |
if os.path.exists(self.path): |
| 1781 |
os.remove(self.path) |
| 1782 |
|
| 1783 |
def test_set_written_on_write(self): |
| 1784 |
"""Test that write_builder changes the written flag of the builder and its children from False to True.""" |
| 1785 |
with HDF5IO(self.path, manager=self.manager, mode='w') as io: |
| 1786 |
builder = self.manager.build(container=self.foofile, source=self.path) |
| 1787 |
self.assertFalse(io.get_written(builder)) |
| 1788 |
self._check_written_children(io, builder, False) |
| 1789 |
io.write_builder(builder) |
| 1790 |
self.assertTrue(io.get_written(builder)) |
| 1791 |
self._check_written_children(io, builder, True) |
| 1792 |
|
| 1793 |
def _check_written_children(self, io, builder, val): |
| 1794 |
"""Test whether the io object has the written flag of the child builders set to val.""" |
| 1795 |
for group_bldr in builder.groups.values(): |
| 1796 |
self.assertEqual(io.get_written(group_bldr), val) |
| 1797 |
self._check_written_children(io, group_bldr, val) |
| 1798 |
for dset_bldr in builder.datasets.values(): |
| 1799 |
self.assertEqual(io.get_written(dset_bldr), val) |
| 1800 |
for link_bldr in builder.links.values(): |
| 1801 |
self.assertEqual(io.get_written(link_bldr), val) |
| 1802 |
|
| 1803 |
|
| 1804 |
class H5DataIOValid(TestCase): |
| 1805 |
|
| 1806 |
def setUp(self): |
| 1807 |
self.paths = [get_temp_filepath(), ] |
| 1808 |
|
| 1809 |
self.foo1 = Foo('foo1', H5DataIO([1, 2, 3, 4, 5]), "I am foo1", 17, 3.14) |
| 1810 |
bucket1 = FooBucket('bucket1', [self.foo1]) |
| 1811 |
foofile1 = FooFile(buckets=[bucket1]) |
| 1812 |
|
| 1813 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as io: |
| 1814 |
io.write(foofile1) |
| 1815 |
|
| 1816 |
def tearDown(self): |
| 1817 |
for path in self.paths: |
| 1818 |
if os.path.exists(path): |
| 1819 |
os.remove(path) |
| 1820 |
|
| 1821 |
def test_valid(self): |
| 1822 |
self.assertTrue(self.foo1.my_data.valid) |
| 1823 |
|
| 1824 |
def test_read_valid(self): |
| 1825 |
"""Test that h5py.H5Dataset.id.valid works as expected""" |
| 1826 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as io: |
| 1827 |
read_foofile1 = io.read() |
| 1828 |
self.assertTrue(read_foofile1.buckets['bucket1'].foos['foo1'].my_data.id.valid) |
| 1829 |
|
| 1830 |
self.assertFalse(read_foofile1.buckets['bucket1'].foos['foo1'].my_data.id.valid) |
| 1831 |
|
| 1832 |
def test_link(self): |
| 1833 |
"""Test that wrapping of linked data within H5DataIO """ |
| 1834 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as io: |
| 1835 |
read_foofile1 = io.read() |
| 1836 |
|
| 1837 |
self.foo2 = Foo('foo2', H5DataIO(data=read_foofile1.buckets['bucket1'].foos['foo1'].my_data), |
| 1838 |
"I am foo2", 17, 3.14) |
| 1839 |
bucket2 = FooBucket('bucket2', [self.foo2]) |
| 1840 |
foofile2 = FooFile(buckets=[bucket2]) |
| 1841 |
|
| 1842 |
self.paths.append(get_temp_filepath()) |
| 1843 |
|
| 1844 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='w') as io: |
| 1845 |
io.write(foofile2) |
| 1846 |
|
| 1847 |
self.assertTrue(self.foo2.my_data.valid) # test valid |
| 1848 |
self.assertEqual(len(self.foo2.my_data), 5) # test len |
| 1849 |
self.assertEqual(self.foo2.my_data.shape, (5,)) # test getattr with shape |
| 1850 |
self.assertTrue(np.array_equal(np.array(self.foo2.my_data), [1, 2, 3, 4, 5])) # test array conversion |
| 1851 |
|
| 1852 |
# test loop through iterable |
| 1853 |
match = [1, 2, 3, 4, 5] |
| 1854 |
for (i, j) in zip(self.foo2.my_data, match): |
| 1855 |
self.assertEqual(i, j) |
| 1856 |
|
| 1857 |
# test iterator |
| 1858 |
my_iter = iter(self.foo2.my_data) |
| 1859 |
self.assertEqual(next(my_iter), 1) |
| 1860 |
|
| 1861 |
# foo2.my_data dataset is now closed |
| 1862 |
self.assertFalse(self.foo2.my_data.valid) |
| 1863 |
|
| 1864 |
with self.assertRaisesWith(InvalidDataIOError, "Cannot get length of data. Data is not valid."): |
| 1865 |
len(self.foo2.my_data) |
| 1866 |
|
| 1867 |
with self.assertRaisesWith(InvalidDataIOError, "Cannot get attribute 'shape' of data. Data is not valid."): |
| 1868 |
self.foo2.my_data.shape |
| 1869 |
|
| 1870 |
with self.assertRaisesWith(InvalidDataIOError, "Cannot convert data to array. Data is not valid."): |
| 1871 |
np.array(self.foo2.my_data) |
| 1872 |
|
| 1873 |
with self.assertRaisesWith(InvalidDataIOError, "Cannot iterate on data. Data is not valid."): |
| 1874 |
for i in self.foo2.my_data: |
| 1875 |
pass |
| 1876 |
|
| 1877 |
with self.assertRaisesWith(InvalidDataIOError, "Cannot iterate on data. Data is not valid."): |
| 1878 |
iter(self.foo2.my_data) |
| 1879 |
|
| 1880 |
# re-open the file with the data linking to other file (still closed) |
| 1881 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as io: |
| 1882 |
read_foofile2 = io.read() |
| 1883 |
read_foo2 = read_foofile2.buckets['bucket2'].foos['foo2'] |
| 1884 |
|
| 1885 |
# note that read_foo2 dataset does not have an attribute 'valid' |
| 1886 |
self.assertEqual(len(read_foo2.my_data), 5) # test len |
| 1887 |
self.assertEqual(read_foo2.my_data.shape, (5,)) # test getattr with shape |
| 1888 |
self.assertTrue(np.array_equal(np.array(read_foo2.my_data), [1, 2, 3, 4, 5])) # test array conversion |
| 1889 |
|
| 1890 |
# test loop through iterable |
| 1891 |
match = [1, 2, 3, 4, 5] |
| 1892 |
for (i, j) in zip(read_foo2.my_data, match): |
| 1893 |
self.assertEqual(i, j) |
| 1894 |
|
| 1895 |
# test iterator |
| 1896 |
my_iter = iter(read_foo2.my_data) |
| 1897 |
self.assertEqual(next(my_iter), 1) |
| 1898 |
|
| 1899 |
|
| 1900 |
class TestReadLink(TestCase): |
| 1901 |
|
| 1902 |
def setUp(self): |
| 1903 |
self.target_path = get_temp_filepath() |
| 1904 |
self.link_path = get_temp_filepath() |
| 1905 |
root1 = GroupBuilder(name='root') |
| 1906 |
subgroup = GroupBuilder(name='test_group') |
| 1907 |
root1.set_group(subgroup) |
| 1908 |
dataset = DatasetBuilder('test_dataset', data=[1, 2, 3, 4]) |
| 1909 |
subgroup.set_dataset(dataset) |
| 1910 |
|
| 1911 |
root2 = GroupBuilder(name='root') |
| 1912 |
link_group = LinkBuilder(subgroup, 'link_to_test_group') |
| 1913 |
root2.set_link(link_group) |
| 1914 |
link_dataset = LinkBuilder(dataset, 'link_to_test_dataset') |
| 1915 |
root2.set_link(link_dataset) |
| 1916 |
|
| 1917 |
with HDF5IO(self.target_path, manager=get_foo_buildmanager(), mode='w') as io: |
| 1918 |
io.write_builder(root1) |
| 1919 |
root1.source = self.target_path |
| 1920 |
|
| 1921 |
with HDF5IO(self.link_path, manager=get_foo_buildmanager(), mode='w') as io: |
| 1922 |
io.write_builder(root2) |
| 1923 |
root2.source = self.link_path |
| 1924 |
self.ios = [] |
| 1925 |
|
| 1926 |
def tearDown(self): |
| 1927 |
if os.path.exists(self.target_path): |
| 1928 |
os.remove(self.target_path) |
| 1929 |
if os.path.exists(self.link_path): |
| 1930 |
os.remove(self.link_path) |
| 1931 |
|
| 1932 |
def test_set_link_loc(self): |
| 1933 |
""" |
| 1934 |
Test that Builder location is set when it is read as a link |
| 1935 |
""" |
| 1936 |
read_io = HDF5IO(self.link_path, manager=get_foo_buildmanager(), mode='r') |
| 1937 |
self.ios.append(read_io) # store IO object for closing in tearDown |
| 1938 |
bldr = read_io.read_builder() |
| 1939 |
self.assertEqual(bldr['link_to_test_group'].builder.location, '/') |
| 1940 |
self.assertEqual(bldr['link_to_test_dataset'].builder.location, '/test_group') |
| 1941 |
read_io.close() |
| 1942 |
|
| 1943 |
def test_link_to_link(self): |
| 1944 |
""" |
| 1945 |
Test that link to link gets written and read properly |
| 1946 |
""" |
| 1947 |
link_to_link_path = get_temp_filepath() |
| 1948 |
read_io1 = HDF5IO(self.link_path, manager=get_foo_buildmanager(), mode='r') |
| 1949 |
self.ios.append(read_io1) # store IO object for closing in tearDown |
| 1950 |
bldr1 = read_io1.read_builder() |
| 1951 |
root3 = GroupBuilder(name='root') |
| 1952 |
|
| 1953 |
link = LinkBuilder(bldr1['link_to_test_group'].builder, 'link_to_link') |
| 1954 |
root3.set_link(link) |
| 1955 |
root3.set_link(LinkBuilder(bldr1['link_to_test_group'].builder, 'link_to_link')) |
| 1956 |
with HDF5IO(link_to_link_path, manager=get_foo_buildmanager(), mode='w') as io: |
| 1957 |
io.write_builder(root3) |
| 1958 |
read_io1.close() |
| 1959 |
|
| 1960 |
read_io2 = HDF5IO(link_to_link_path, manager=get_foo_buildmanager(), mode='r') |
| 1961 |
self.ios.append(read_io2) |
| 1962 |
bldr2 = read_io2.read_builder() |
| 1963 |
self.assertEqual(bldr2['link_to_link'].builder.source, self.target_path) |
| 1964 |
read_io2.close() |
| 1965 |
|
| 1966 |
def test_broken_link(self): |
| 1967 |
"""Test that opening a file with a broken link raises a warning but is still readable.""" |
| 1968 |
os.remove(self.target_path) |
| 1969 |
with self.assertWarnsWith(BrokenLinkWarning, 'Path to Group altered/broken at /link_to_test_group'): |
| 1970 |
with HDF5IO(self.link_path, manager=get_foo_buildmanager(), mode='r') as read_io: |
| 1971 |
bldr = read_io.read_builder() |
| 1972 |
self.assertDictEqual(bldr.links, {}) |
| 1973 |
|
| 1974 |
def test_broken_linked_data(self): |
| 1975 |
"""Test that opening a file with a broken link raises a warning but is still readable.""" |
| 1976 |
manager = get_foo_buildmanager() |
| 1977 |
|
| 1978 |
with HDF5IO(self.target_path, manager=manager, mode='r') as read_io: |
| 1979 |
read_root = read_io.read_builder() |
| 1980 |
read_dataset_data = read_root.groups['test_group'].datasets['test_dataset'].data |
| 1981 |
|
| 1982 |
with HDF5IO(self.link_path, manager=manager, mode='w') as write_io: |
| 1983 |
root2 = GroupBuilder(name='root') |
| 1984 |
dataset = DatasetBuilder(name='link_to_test_dataset', data=read_dataset_data) |
| 1985 |
root2.set_dataset(dataset) |
| 1986 |
write_io.write_builder(root2, link_data=True) |
| 1987 |
|
| 1988 |
os.remove(self.target_path) |
| 1989 |
with self.assertWarnsWith(BrokenLinkWarning, 'Path to Group altered/broken at /link_to_test_dataset'): |
| 1990 |
with HDF5IO(self.link_path, manager=get_foo_buildmanager(), mode='r') as read_io: |
| 1991 |
bldr = read_io.read_builder() |
| 1992 |
self.assertDictEqual(bldr.links, {}) |
| 1993 |
|
| 1994 |
|
| 1995 |
class TestBuildWriteLinkToLink(TestCase): |
| 1996 |
|
| 1997 |
def setUp(self): |
| 1998 |
self.paths = [ |
| 1999 |
get_temp_filepath(), |
| 2000 |
get_temp_filepath(), |
| 2001 |
get_temp_filepath() |
| 2002 |
] |
| 2003 |
self.ios = [] |
| 2004 |
|
| 2005 |
def tearDown(self): |
| 2006 |
for p in self.paths: |
| 2007 |
if os.path.exists(p): |
| 2008 |
os.remove(p) |
| 2009 |
|
| 2010 |
def test_external_link_to_external_link(self): |
| 2011 |
"""Test writing a file with external links to external links.""" |
| 2012 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2013 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2014 |
foofile = FooFile(buckets=[foobucket]) |
| 2015 |
|
| 2016 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2017 |
write_io.write(foofile) |
| 2018 |
|
| 2019 |
manager = get_foo_buildmanager() |
| 2020 |
with HDF5IO(self.paths[0], manager=manager, mode='r') as read_io: |
| 2021 |
read_foofile = read_io.read() |
| 2022 |
# make external link to existing group |
| 2023 |
foofile2 = FooFile(foo_link=read_foofile.buckets['bucket1'].foos['foo1']) |
| 2024 |
|
| 2025 |
with HDF5IO(self.paths[1], manager=manager, mode='w') as write_io: |
| 2026 |
write_io.write(foofile2) |
| 2027 |
|
| 2028 |
manager = get_foo_buildmanager() |
| 2029 |
with HDF5IO(self.paths[1], manager=manager, mode='r') as read_io: |
| 2030 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2031 |
read_foofile2 = read_io.read() |
| 2032 |
foofile3 = FooFile(foo_link=read_foofile2.foo_link) # make external link to external link |
| 2033 |
|
| 2034 |
with HDF5IO(self.paths[2], manager=manager, mode='w') as write_io: |
| 2035 |
write_io.write(foofile3) |
| 2036 |
|
| 2037 |
with HDF5IO(self.paths[2], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2038 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2039 |
read_foofile3 = read_io.read() |
| 2040 |
|
| 2041 |
self.assertEqual(read_foofile3.foo_link.container_source, self.paths[0]) |
| 2042 |
|
| 2043 |
def test_external_link_to_soft_link(self): |
| 2044 |
"""Test writing a file with external links to external links.""" |
| 2045 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2046 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2047 |
foofile = FooFile(buckets=[foobucket], foo_link=foo1) # create soft link |
| 2048 |
|
| 2049 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2050 |
write_io.write(foofile) |
| 2051 |
|
| 2052 |
manager = get_foo_buildmanager() |
| 2053 |
with HDF5IO(self.paths[0], manager=manager, mode='r') as read_io: |
| 2054 |
read_foofile = read_io.read() |
| 2055 |
foofile2 = FooFile(foo_link=read_foofile.foo_link) # make external link to existing soft link |
| 2056 |
|
| 2057 |
with HDF5IO(self.paths[1], manager=manager, mode='w') as write_io: |
| 2058 |
write_io.write(foofile2) |
| 2059 |
|
| 2060 |
manager = get_foo_buildmanager() |
| 2061 |
with HDF5IO(self.paths[1], manager=manager, mode='r') as read_io: |
| 2062 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2063 |
read_foofile2 = read_io.read() |
| 2064 |
foofile3 = FooFile(foo_link=read_foofile2.foo_link) # make external link to external link |
| 2065 |
|
| 2066 |
with HDF5IO(self.paths[2], manager=manager, mode='w') as write_io: |
| 2067 |
write_io.write(foofile3) |
| 2068 |
|
| 2069 |
with HDF5IO(self.paths[2], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2070 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2071 |
read_foofile3 = read_io.read() |
| 2072 |
|
| 2073 |
self.assertEqual(read_foofile3.foo_link.container_source, self.paths[0]) |
| 2074 |
|
| 2075 |
|
| 2076 |
class TestLinkData(TestCase): |
| 2077 |
|
| 2078 |
def setUp(self): |
| 2079 |
self.target_path = get_temp_filepath() |
| 2080 |
self.link_path = get_temp_filepath() |
| 2081 |
root1 = GroupBuilder(name='root') |
| 2082 |
subgroup = GroupBuilder(name='test_group') |
| 2083 |
root1.set_group(subgroup) |
| 2084 |
dataset = DatasetBuilder('test_dataset', data=[1, 2, 3, 4]) |
| 2085 |
subgroup.set_dataset(dataset) |
| 2086 |
|
| 2087 |
with HDF5IO(self.target_path, manager=get_foo_buildmanager(), mode='w') as io: |
| 2088 |
io.write_builder(root1) |
| 2089 |
|
| 2090 |
def tearDown(self): |
| 2091 |
if os.path.exists(self.target_path): |
| 2092 |
os.remove(self.target_path) |
| 2093 |
if os.path.exists(self.link_path): |
| 2094 |
os.remove(self.link_path) |
| 2095 |
|
| 2096 |
def test_link_data_true(self): |
| 2097 |
"""Test that the argument link_data=True for write_builder creates an external link.""" |
| 2098 |
manager = get_foo_buildmanager() |
| 2099 |
with HDF5IO(self.target_path, manager=manager, mode='r') as read_io: |
| 2100 |
read_root = read_io.read_builder() |
| 2101 |
read_dataset_data = read_root.groups['test_group'].datasets['test_dataset'].data |
| 2102 |
|
| 2103 |
with HDF5IO(self.link_path, manager=manager, mode='w') as write_io: |
| 2104 |
root2 = GroupBuilder(name='root') |
| 2105 |
dataset = DatasetBuilder(name='link_to_test_dataset', data=read_dataset_data) |
| 2106 |
root2.set_dataset(dataset) |
| 2107 |
write_io.write_builder(root2, link_data=True) |
| 2108 |
|
| 2109 |
with File(self.link_path, mode='r') as f: |
| 2110 |
self.assertIsInstance(f.get('link_to_test_dataset', getlink=True), ExternalLink) |
| 2111 |
|
| 2112 |
def test_link_data_false(self): |
| 2113 |
"""Test that the argument link_data=False for write_builder copies the data.""" |
| 2114 |
manager = get_foo_buildmanager() |
| 2115 |
with HDF5IO(self.target_path, manager=manager, mode='r') as read_io: |
| 2116 |
read_root = read_io.read_builder() |
| 2117 |
read_dataset_data = read_root.groups['test_group'].datasets['test_dataset'].data |
| 2118 |
|
| 2119 |
with HDF5IO(self.link_path, manager=manager, mode='w') as write_io: |
| 2120 |
root2 = GroupBuilder(name='root') |
| 2121 |
dataset = DatasetBuilder(name='link_to_test_dataset', data=read_dataset_data) |
| 2122 |
root2.set_dataset(dataset) |
| 2123 |
write_io.write_builder(root2, link_data=False) |
| 2124 |
|
| 2125 |
with File(self.link_path, mode='r') as f: |
| 2126 |
self.assertFalse(isinstance(f.get('link_to_test_dataset', getlink=True), ExternalLink)) |
| 2127 |
self.assertListEqual(f.get('link_to_test_dataset')[:].tolist(), [1, 2, 3, 4]) |
| 2128 |
|
| 2129 |
|
| 2130 |
class TestLoadNamespaces(TestCase): |
| 2131 |
|
| 2132 |
def setUp(self): |
| 2133 |
self.manager = get_foo_buildmanager() |
| 2134 |
self.path = get_temp_filepath() |
| 2135 |
container = FooFile() |
| 2136 |
with HDF5IO(self.path, manager=self.manager, mode='w') as io: |
| 2137 |
io.write(container) |
| 2138 |
|
| 2139 |
def tearDown(self): |
| 2140 |
if os.path.exists(self.path): |
| 2141 |
os.remove(self.path) |
| 2142 |
|
| 2143 |
def test_load_namespaces_none_version(self): |
| 2144 |
"""Test that reading a file with a cached namespace and None version works but raises a warning.""" |
| 2145 |
# make the file have group name "None" instead of "0.1.0" (namespace version is used as group name) |
| 2146 |
# and set the version key to "None" |
| 2147 |
with h5py.File(self.path, mode='r+') as f: |
| 2148 |
# rename the group |
| 2149 |
f.move('/specifications/test_core/0.1.0', '/specifications/test_core/None') |
| 2150 |
|
| 2151 |
# replace the namespace dataset with a serialized dict with the version key set to 'None' |
| 2152 |
new_ns = ('{"namespaces":[{"doc":"a test namespace","schema":[{"source":"test"}],"name":"test_core",' |
| 2153 |
'"version":"None"}]}') |
| 2154 |
f['/specifications/test_core/None/namespace'][()] = new_ns |
| 2155 |
|
| 2156 |
# load the namespace from file |
| 2157 |
ns_catalog = NamespaceCatalog() |
| 2158 |
msg = "Loaded namespace '%s' is unversioned. Please notify the extension author." % CORE_NAMESPACE |
| 2159 |
with self.assertWarnsWith(UserWarning, msg): |
| 2160 |
HDF5IO.load_namespaces(ns_catalog, self.path) |
| 2161 |
|
| 2162 |
def test_load_namespaces_unversioned(self): |
| 2163 |
"""Test that reading a file with a cached, unversioned version works but raises a warning.""" |
| 2164 |
# make the file have group name "unversioned" instead of "0.1.0" (namespace version is used as group name) |
| 2165 |
# and remove the version key |
| 2166 |
with h5py.File(self.path, mode='r+') as f: |
| 2167 |
# rename the group |
| 2168 |
f.move('/specifications/test_core/0.1.0', '/specifications/test_core/unversioned') |
| 2169 |
|
| 2170 |
# replace the namespace dataset with a serialized dict without the version key |
| 2171 |
new_ns = ('{"namespaces":[{"doc":"a test namespace","schema":[{"source":"test"}],"name":"test_core"}]}') |
| 2172 |
f['/specifications/test_core/unversioned/namespace'][()] = new_ns |
| 2173 |
|
| 2174 |
# load the namespace from file |
| 2175 |
ns_catalog = NamespaceCatalog() |
| 2176 |
msg = ("Loaded namespace '%s' is missing the required key 'version'. Version will be set to " |
| 2177 |
"'%s'. Please notify the extension author." % (CORE_NAMESPACE, SpecNamespace.UNVERSIONED)) |
| 2178 |
with self.assertWarnsWith(UserWarning, msg): |
| 2179 |
HDF5IO.load_namespaces(ns_catalog, self.path) |
| 2180 |
|
| 2181 |
def test_load_namespaces_path(self): |
| 2182 |
"""Test that loading namespaces given a path is OK and returns the correct dictionary.""" |
| 2183 |
ns_catalog = NamespaceCatalog() |
| 2184 |
d = HDF5IO.load_namespaces(ns_catalog, self.path) |
| 2185 |
self.assertEqual(d, {'test_core': {}}) # test_core has no dependencies |
| 2186 |
|
| 2187 |
def test_load_namespaces_no_path_no_file(self): |
| 2188 |
"""Test that loading namespaces without a path or file raises an error.""" |
| 2189 |
ns_catalog = NamespaceCatalog() |
| 2190 |
|
| 2191 |
msg = "Either the 'path' or 'file' argument must be supplied." |
| 2192 |
with self.assertRaisesWith(ValueError, msg): |
| 2193 |
HDF5IO.load_namespaces(ns_catalog) |
| 2194 |
|
| 2195 |
def test_load_namespaces_file_no_path(self): |
| 2196 |
""" |
| 2197 |
Test that loading namespaces from an h5py.File not backed by a file on disk is OK and does not close the file. |
| 2198 |
""" |
| 2199 |
with open(self.path, 'rb') as raw_file: |
| 2200 |
buffer = BytesIO(raw_file.read()) |
| 2201 |
file_obj = h5py.File(buffer, 'r') |
| 2202 |
|
| 2203 |
ns_catalog = NamespaceCatalog() |
| 2204 |
d = HDF5IO.load_namespaces(ns_catalog, file=file_obj) |
| 2205 |
|
| 2206 |
self.assertTrue(file_obj.__bool__()) # check file object is still open |
| 2207 |
self.assertEqual(d, {'test_core': {}}) |
| 2208 |
|
| 2209 |
file_obj.close() |
| 2210 |
|
| 2211 |
def test_load_namespaces_file_path_matched(self): |
| 2212 |
"""Test that loading namespaces given an h5py.File and path is OK and does not close the file.""" |
| 2213 |
with h5py.File(self.path, 'r') as file_obj: |
| 2214 |
ns_catalog = NamespaceCatalog() |
| 2215 |
d = HDF5IO.load_namespaces(ns_catalog, path=self.path, file=file_obj) |
| 2216 |
self.assertTrue(file_obj.__bool__()) # check file object is still open |
| 2217 |
self.assertEqual(d, {'test_core': {}}) |
| 2218 |
|
| 2219 |
def test_load_namespaces_file_path_mismatched(self): |
| 2220 |
"""Test that loading namespaces given an h5py.File and path that are mismatched raises an error.""" |
| 2221 |
with h5py.File(self.path, 'r') as file_obj: |
| 2222 |
ns_catalog = NamespaceCatalog() |
| 2223 |
|
| 2224 |
msg = "You argued 'different_path' as this object's path, but supplied a file with filename: %s" % self.path |
| 2225 |
with self.assertRaisesWith(ValueError, msg): |
| 2226 |
HDF5IO.load_namespaces(ns_catalog, path='different_path', file=file_obj) |
| 2227 |
|
| 2228 |
def test_load_namespaces_with_pathlib_path(self): |
| 2229 |
"""Test that loading a namespace using a valid pathlib Path is OK and returns the correct dictionary.""" |
| 2230 |
pathlib_path = Path(self.path) |
| 2231 |
ns_catalog = NamespaceCatalog() |
| 2232 |
d = HDF5IO.load_namespaces(ns_catalog, pathlib_path) |
| 2233 |
self.assertEqual(d, {'test_core': {}}) # test_core has no dependencies |
| 2234 |
|
| 2235 |
def test_load_namespaces_with_dependencies(self): |
| 2236 |
"""Test loading namespaces where one includes another.""" |
| 2237 |
class MyFoo(Container): |
| 2238 |
pass |
| 2239 |
|
| 2240 |
myfoo_spec = GroupSpec(doc="A MyFoo", data_type_def='MyFoo', data_type_inc='Foo') |
| 2241 |
spec_catalog = SpecCatalog() |
| 2242 |
name = 'test_core2' |
| 2243 |
namespace = SpecNamespace( |
| 2244 |
doc='a test namespace', |
| 2245 |
name=name, |
| 2246 |
schema=[{'source': 'test2.yaml', 'namespace': 'test_core'}], # depends on test_core |
| 2247 |
version='0.1.0', |
| 2248 |
catalog=spec_catalog |
| 2249 |
) |
| 2250 |
spec_catalog.register_spec(myfoo_spec, 'test2.yaml') |
| 2251 |
namespace_catalog = NamespaceCatalog() |
| 2252 |
namespace_catalog.add_namespace(name, namespace) |
| 2253 |
type_map = TypeMap(namespace_catalog) |
| 2254 |
type_map.register_container_type(name, 'MyFoo', MyFoo) |
| 2255 |
type_map.merge(self.manager.type_map, ns_catalog=True) |
| 2256 |
manager = BuildManager(type_map) |
| 2257 |
container = MyFoo(name='myfoo') |
| 2258 |
with HDF5IO(self.path, manager=manager, mode='a') as io: # append to file |
| 2259 |
io.write(container) |
| 2260 |
|
| 2261 |
ns_catalog = NamespaceCatalog() |
| 2262 |
d = HDF5IO.load_namespaces(ns_catalog, self.path) |
| 2263 |
self.assertEqual(d, {'test_core': {}, 'test_core2': {'test_core': ('Foo', 'FooBucket', 'FooFile')}}) |
| 2264 |
|
| 2265 |
def test_load_namespaces_no_specloc(self): |
| 2266 |
"""Test loading namespaces where the file does not contain a SPEC_LOC_ATTR.""" |
| 2267 |
# delete the spec location attribute from the file |
| 2268 |
with h5py.File(self.path, mode='r+') as f: |
| 2269 |
del f.attrs[SPEC_LOC_ATTR] |
| 2270 |
|
| 2271 |
# load the namespace from file |
| 2272 |
ns_catalog = NamespaceCatalog() |
| 2273 |
ret = HDF5IO.load_namespaces(ns_catalog, self.path) |
| 2274 |
self.assertDictEqual(ret, {}) |
| 2275 |
|
| 2276 |
def test_load_namespaces_resolve_custom_deps(self): |
| 2277 |
"""Test that reading a file with a cached namespace and different def/inc keys works.""" |
| 2278 |
# Setup all the data we need |
| 2279 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2280 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2281 |
foofile = FooFile(buckets=[foobucket]) |
| 2282 |
|
| 2283 |
with HDF5IO(self.path, manager=self.manager, mode='w') as io: |
| 2284 |
io.write(foofile) |
| 2285 |
|
| 2286 |
with h5py.File(self.path, mode='r+') as f: |
| 2287 |
# add two types where one extends the other and overrides an attribute |
| 2288 |
# check that the inherited attribute resolves correctly despite having a different def/inc key than those |
| 2289 |
# used in the namespace catalog |
| 2290 |
added_types = (',{"data_type_def":"BigFoo","data_type_inc":"Foo","doc":"doc","attributes":[' |
| 2291 |
'{"name":"my_attr","dtype":"text","doc":"an attr"}]},' |
| 2292 |
'{"data_type_def":"BiggerFoo","data_type_inc":"BigFoo","doc":"doc"}]}') |
| 2293 |
old_test_source = f['/specifications/test_core/0.1.0/test'] |
| 2294 |
# strip the ]} from end, then add to groups |
| 2295 |
if H5PY_3: # string datasets are returned as bytes |
| 2296 |
old_test_source[()] = old_test_source[()][0:-2].decode('utf-8') + added_types |
| 2297 |
else: |
| 2298 |
old_test_source[()] = old_test_source[()][0:-2] + added_types |
| 2299 |
new_ns = ('{"namespaces":[{"doc":"a test namespace","schema":[' |
| 2300 |
'{"namespace":"test_core","my_data_types":["Foo"]},' |
| 2301 |
'{"source":"test-ext.extensions"}' |
| 2302 |
'],"name":"test-ext","version":"0.1.0"}]}') |
| 2303 |
f.create_dataset('/specifications/test-ext/0.1.0/namespace', data=new_ns) |
| 2304 |
new_ext = '{"groups":[{"my_data_type_def":"FooExt","my_data_type_inc":"Foo","doc":"doc"}]}' |
| 2305 |
f.create_dataset('/specifications/test-ext/0.1.0/test-ext.extensions', data=new_ext) |
| 2306 |
|
| 2307 |
# load the namespace from file |
| 2308 |
ns_catalog = NamespaceCatalog(CustomGroupSpec, CustomDatasetSpec, CustomSpecNamespace) |
| 2309 |
namespace_deps = HDF5IO.load_namespaces(ns_catalog, self.path) |
| 2310 |
|
| 2311 |
# test that the dependencies are correct |
| 2312 |
expected = ('Foo',) |
| 2313 |
self.assertTupleEqual((namespace_deps['test-ext']['test_core']), expected) |
| 2314 |
|
| 2315 |
# test that the types are loaded |
| 2316 |
types = ns_catalog.get_types('test-ext.extensions') |
| 2317 |
expected = ('FooExt',) |
| 2318 |
self.assertTupleEqual(types, expected) |
| 2319 |
|
| 2320 |
# test that the def_key is updated for test-ext ns |
| 2321 |
foo_ext_spec = ns_catalog.get_spec('test-ext', 'FooExt') |
| 2322 |
self.assertTrue('my_data_type_def' in foo_ext_spec) |
| 2323 |
self.assertTrue('my_data_type_inc' in foo_ext_spec) |
| 2324 |
|
| 2325 |
# test that the data_type_def is replaced with my_data_type_def for test_core ns |
| 2326 |
bigger_foo_spec = ns_catalog.get_spec('test_core', 'BiggerFoo') |
| 2327 |
self.assertTrue('my_data_type_def' in bigger_foo_spec) |
| 2328 |
self.assertTrue('my_data_type_inc' in bigger_foo_spec) |
| 2329 |
|
| 2330 |
# test that my_attr is properly inherited in BiggerFoo from BigFoo and attr1, attr3 are inherited from Foo |
| 2331 |
self.assertTrue(len(bigger_foo_spec.attributes) == 3) |
| 2332 |
|
| 2333 |
|
| 2334 |
class TestGetNamespaces(TestCase): |
| 2335 |
|
| 2336 |
def create_test_namespace(self, name, version): |
| 2337 |
file_spec = GroupSpec(doc="A FooFile", data_type_def='FooFile') |
| 2338 |
spec_catalog = SpecCatalog() |
| 2339 |
namespace = SpecNamespace( |
| 2340 |
doc='a test namespace', |
| 2341 |
name=name, |
| 2342 |
schema=[{'source': 'test.yaml'}], |
| 2343 |
version=version, |
| 2344 |
catalog=spec_catalog |
| 2345 |
) |
| 2346 |
spec_catalog.register_spec(file_spec, 'test.yaml') |
| 2347 |
return namespace |
| 2348 |
|
| 2349 |
def write_test_file(self, name, version, mode): |
| 2350 |
namespace = self.create_test_namespace(name, version) |
| 2351 |
namespace_catalog = NamespaceCatalog() |
| 2352 |
namespace_catalog.add_namespace(name, namespace) |
| 2353 |
type_map = TypeMap(namespace_catalog) |
| 2354 |
type_map.register_container_type(name, 'FooFile', FooFile) |
| 2355 |
manager = BuildManager(type_map) |
| 2356 |
with HDF5IO(self.path, manager=manager, mode=mode) as io: |
| 2357 |
io.write(self.container) |
| 2358 |
|
| 2359 |
def setUp(self): |
| 2360 |
self.path = get_temp_filepath() |
| 2361 |
self.container = FooFile() |
| 2362 |
|
| 2363 |
def tearDown(self): |
| 2364 |
if os.path.exists(self.path): |
| 2365 |
os.remove(self.path) |
| 2366 |
|
| 2367 |
# see other tests for path & file match/mismatch testing in TestLoadNamespaces |
| 2368 |
|
| 2369 |
def test_get_namespaces_with_path(self): |
| 2370 |
"""Test getting namespaces given a path.""" |
| 2371 |
self.write_test_file('test_core', '0.1.0', 'w') |
| 2372 |
|
| 2373 |
ret = HDF5IO.get_namespaces(path=self.path) |
| 2374 |
self.assertEqual(ret, {'test_core': '0.1.0'}) |
| 2375 |
|
| 2376 |
def test_get_namespaces_with_file(self): |
| 2377 |
"""Test getting namespaces given a file object.""" |
| 2378 |
self.write_test_file('test_core', '0.1.0', 'w') |
| 2379 |
|
| 2380 |
with File(self.path, 'r') as f: |
| 2381 |
ret = HDF5IO.get_namespaces(file=f) |
| 2382 |
self.assertEqual(ret, {'test_core': '0.1.0'}) |
| 2383 |
self.assertTrue(f.__bool__()) # check file object is still open |
| 2384 |
|
| 2385 |
def test_get_namespaces_different_versions(self): |
| 2386 |
"""Test getting namespaces with multiple versions given a path.""" |
| 2387 |
# write file with spec with smaller version string |
| 2388 |
self.write_test_file('test_core', '0.0.10', 'w') |
| 2389 |
|
| 2390 |
# append to file with spec with larger version string |
| 2391 |
self.write_test_file('test_core', '0.1.0', 'a') |
| 2392 |
|
| 2393 |
ret = HDF5IO.get_namespaces(path=self.path) |
| 2394 |
self.assertEqual(ret, {'test_core': '0.1.0'}) |
| 2395 |
|
| 2396 |
def test_get_namespaces_multiple_namespaces(self): |
| 2397 |
"""Test getting multiple namespaces given a path.""" |
| 2398 |
self.write_test_file('test_core1', '0.0.10', 'w') |
| 2399 |
self.write_test_file('test_core2', '0.1.0', 'a') |
| 2400 |
|
| 2401 |
ret = HDF5IO.get_namespaces(path=self.path) |
| 2402 |
self.assertEqual(ret, {'test_core1': '0.0.10', 'test_core2': '0.1.0'}) |
| 2403 |
|
| 2404 |
def test_get_namespaces_none_version(self): |
| 2405 |
"""Test getting namespaces where file has one None-versioned namespace.""" |
| 2406 |
self.write_test_file('test_core', '0.1.0', 'w') |
| 2407 |
|
| 2408 |
# make the file have group name "None" instead of "0.1.0" (namespace version is used as group name) |
| 2409 |
# and set the version key to "None" |
| 2410 |
with h5py.File(self.path, mode='r+') as f: |
| 2411 |
# rename the group |
| 2412 |
f.move('/specifications/test_core/0.1.0', '/specifications/test_core/None') |
| 2413 |
|
| 2414 |
# replace the namespace dataset with a serialized dict with the version key set to 'None' |
| 2415 |
new_ns = ('{"namespaces":[{"doc":"a test namespace","schema":[{"source":"test"}],"name":"test_core",' |
| 2416 |
'"version":"None"}]}') |
| 2417 |
f['/specifications/test_core/None/namespace'][()] = new_ns |
| 2418 |
|
| 2419 |
ret = HDF5IO.get_namespaces(path=self.path) |
| 2420 |
self.assertEqual(ret, {'test_core': 'None'}) |
| 2421 |
|
| 2422 |
def test_get_namespaces_none_and_other_version(self): |
| 2423 |
"""Test getting namespaces file has a namespace with a normal version and an 'None" version.""" |
| 2424 |
self.write_test_file('test_core', '0.1.0', 'w') |
| 2425 |
|
| 2426 |
# make the file have group name "None" instead of "0.1.0" (namespace version is used as group name) |
| 2427 |
# and set the version key to "None" |
| 2428 |
with h5py.File(self.path, mode='r+') as f: |
| 2429 |
# rename the group |
| 2430 |
f.move('/specifications/test_core/0.1.0', '/specifications/test_core/None') |
| 2431 |
|
| 2432 |
# replace the namespace dataset with a serialized dict with the version key set to 'None' |
| 2433 |
new_ns = ('{"namespaces":[{"doc":"a test namespace","schema":[{"source":"test"}],"name":"test_core",' |
| 2434 |
'"version":"None"}]}') |
| 2435 |
f['/specifications/test_core/None/namespace'][()] = new_ns |
| 2436 |
|
| 2437 |
# append to file with spec with a larger version string |
| 2438 |
self.write_test_file('test_core', '0.2.0', 'a') |
| 2439 |
|
| 2440 |
ret = HDF5IO.get_namespaces(path=self.path) |
| 2441 |
self.assertEqual(ret, {'test_core': '0.2.0'}) |
| 2442 |
|
| 2443 |
def test_get_namespaces_unversioned(self): |
| 2444 |
"""Test getting namespaces where file has one unversioned namespace.""" |
| 2445 |
self.write_test_file('test_core', '0.1.0', 'w') |
| 2446 |
|
| 2447 |
# make the file have group name "unversioned" instead of "0.1.0" (namespace version is used as group name) |
| 2448 |
with h5py.File(self.path, mode='r+') as f: |
| 2449 |
# rename the group |
| 2450 |
f.move('/specifications/test_core/0.1.0', '/specifications/test_core/unversioned') |
| 2451 |
|
| 2452 |
# replace the namespace dataset with a serialized dict without the version key |
| 2453 |
new_ns = ('{"namespaces":[{"doc":"a test namespace","schema":[{"source":"test"}],"name":"test_core"}]}') |
| 2454 |
f['/specifications/test_core/unversioned/namespace'][()] = new_ns |
| 2455 |
|
| 2456 |
ret = HDF5IO.get_namespaces(path=self.path) |
| 2457 |
self.assertEqual(ret, {'test_core': 'unversioned'}) |
| 2458 |
|
| 2459 |
def test_get_namespaces_unversioned_and_other(self): |
| 2460 |
"""Test getting namespaces file has a namespace with a normal version and an 'unversioned" version.""" |
| 2461 |
self.write_test_file('test_core', '0.1.0', 'w') |
| 2462 |
|
| 2463 |
# make the file have group name "unversioned" instead of "0.1.0" (namespace version is used as group name) |
| 2464 |
with h5py.File(self.path, mode='r+') as f: |
| 2465 |
# rename the group |
| 2466 |
f.move('/specifications/test_core/0.1.0', '/specifications/test_core/unversioned') |
| 2467 |
|
| 2468 |
# replace the namespace dataset with a serialized dict without the version key |
| 2469 |
new_ns = ('{"namespaces":[{"doc":"a test namespace","schema":[{"source":"test"}],"name":"test_core"}]}') |
| 2470 |
f['/specifications/test_core/unversioned/namespace'][()] = new_ns |
| 2471 |
|
| 2472 |
# append to file with spec with a larger version string |
| 2473 |
self.write_test_file('test_core', '0.2.0', 'a') |
| 2474 |
|
| 2475 |
ret = HDF5IO.get_namespaces(path=self.path) |
| 2476 |
self.assertEqual(ret, {'test_core': '0.2.0'}) |
| 2477 |
|
| 2478 |
def test_get_namespaces_no_specloc(self): |
| 2479 |
"""Test getting namespaces where the file does not contain a SPEC_LOC_ATTR.""" |
| 2480 |
self.write_test_file('test_core', '0.1.0', 'w') |
| 2481 |
|
| 2482 |
# delete the spec location attribute from the file |
| 2483 |
with h5py.File(self.path, mode='r+') as f: |
| 2484 |
del f.attrs[SPEC_LOC_ATTR] |
| 2485 |
|
| 2486 |
# load the namespace from file |
| 2487 |
ret = HDF5IO.get_namespaces(path=self.path) |
| 2488 |
self.assertDictEqual(ret, {}) |
| 2489 |
|
| 2490 |
|
| 2491 |
class TestExport(TestCase): |
| 2492 |
"""Test exporting HDF5 to HDF5 using HDF5IO.export_container_to_hdf5.""" |
| 2493 |
|
| 2494 |
def setUp(self): |
| 2495 |
self.paths = [ |
| 2496 |
get_temp_filepath(), |
| 2497 |
get_temp_filepath(), |
| 2498 |
get_temp_filepath(), |
| 2499 |
get_temp_filepath(), |
| 2500 |
] |
| 2501 |
self.ios = [] |
| 2502 |
|
| 2503 |
def tearDown(self): |
| 2504 |
for p in self.paths: |
| 2505 |
if os.path.exists(p): |
| 2506 |
os.remove(p) |
| 2507 |
|
| 2508 |
def test_basic(self): |
| 2509 |
"""Test that exporting a written container works.""" |
| 2510 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2511 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2512 |
foofile = FooFile(buckets=[foobucket]) |
| 2513 |
|
| 2514 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2515 |
write_io.write(foofile) |
| 2516 |
|
| 2517 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2518 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 2519 |
export_io.export(src_io=read_io) |
| 2520 |
|
| 2521 |
self.assertTrue(os.path.exists(self.paths[1])) |
| 2522 |
self.assertEqual(foofile.container_source, self.paths[0]) |
| 2523 |
|
| 2524 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2525 |
read_foofile = read_io.read() |
| 2526 |
self.assertEqual(read_foofile.container_source, self.paths[1]) |
| 2527 |
self.assertContainerEqual(foofile, read_foofile, ignore_hdmf_attrs=True) |
| 2528 |
self.assertEqual(os.path.abspath(read_foofile.buckets['bucket1'].foos['foo1'].my_data.file.filename), |
| 2529 |
self.paths[1]) |
| 2530 |
|
| 2531 |
def test_basic_container(self): |
| 2532 |
"""Test that exporting a written container, passing in the container arg, works.""" |
| 2533 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2534 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2535 |
foofile = FooFile(buckets=[foobucket]) |
| 2536 |
|
| 2537 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2538 |
write_io.write(foofile) |
| 2539 |
|
| 2540 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2541 |
read_foofile = read_io.read() |
| 2542 |
|
| 2543 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 2544 |
export_io.export(src_io=read_io, container=read_foofile) |
| 2545 |
|
| 2546 |
self.assertTrue(os.path.exists(self.paths[1])) |
| 2547 |
self.assertEqual(foofile.container_source, self.paths[0]) |
| 2548 |
|
| 2549 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2550 |
read_foofile = read_io.read() |
| 2551 |
self.assertEqual(read_foofile.container_source, self.paths[1]) |
| 2552 |
self.assertContainerEqual(foofile, read_foofile, ignore_hdmf_attrs=True) |
| 2553 |
|
| 2554 |
def test_container_part(self): |
| 2555 |
"""Test that exporting a part of a written container raises an error.""" |
| 2556 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2557 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2558 |
foofile = FooFile(buckets=[foobucket]) |
| 2559 |
|
| 2560 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2561 |
write_io.write(foofile) |
| 2562 |
|
| 2563 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2564 |
read_foofile = read_io.read() |
| 2565 |
|
| 2566 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 2567 |
msg = ("The provided container must be the root of the hierarchy of the source used to read the " |
| 2568 |
"container.") |
| 2569 |
with self.assertRaisesWith(ValueError, msg): |
| 2570 |
export_io.export(src_io=read_io, container=read_foofile.buckets['bucket1']) |
| 2571 |
|
| 2572 |
def test_container_unknown(self): |
| 2573 |
"""Test that exporting a container that did not come from the src_io object raises an error.""" |
| 2574 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2575 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2576 |
foofile = FooFile(buckets=[foobucket]) |
| 2577 |
|
| 2578 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2579 |
write_io.write(foofile) |
| 2580 |
|
| 2581 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2582 |
|
| 2583 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 2584 |
dummy_file = FooFile(buckets=[]) |
| 2585 |
msg = "The provided container must have been read by the provided src_io." |
| 2586 |
with self.assertRaisesWith(ValueError, msg): |
| 2587 |
export_io.export(src_io=read_io, container=dummy_file) |
| 2588 |
|
| 2589 |
def test_cache_spec_true(self): |
| 2590 |
"""Test that exporting with cache_spec works.""" |
| 2591 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2592 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2593 |
foofile = FooFile(buckets=[foobucket]) |
| 2594 |
|
| 2595 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2596 |
write_io.write(foofile) |
| 2597 |
|
| 2598 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2599 |
read_foofile = read_io.read() |
| 2600 |
|
| 2601 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 2602 |
export_io.export( |
| 2603 |
src_io=read_io, |
| 2604 |
container=read_foofile, |
| 2605 |
) |
| 2606 |
|
| 2607 |
with File(self.paths[1], 'r') as f: |
| 2608 |
self.assertIn("test_core", f["specifications"]) |
| 2609 |
|
| 2610 |
def test_cache_spec_false(self): |
| 2611 |
"""Test that exporting with cache_spec works.""" |
| 2612 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2613 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2614 |
foofile = FooFile(buckets=[foobucket]) |
| 2615 |
|
| 2616 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2617 |
write_io.write(foofile) |
| 2618 |
|
| 2619 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2620 |
read_foofile = read_io.read() |
| 2621 |
|
| 2622 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 2623 |
export_io.export( |
| 2624 |
src_io=read_io, |
| 2625 |
container=read_foofile, |
| 2626 |
cache_spec=False, |
| 2627 |
) |
| 2628 |
|
| 2629 |
with File(self.paths[1], 'r') as f: |
| 2630 |
self.assertNotIn('specifications', f) |
| 2631 |
|
| 2632 |
def test_soft_link_group(self): |
| 2633 |
"""Test that exporting a written file with soft linked groups keeps links within the file.""" |
| 2634 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2635 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2636 |
foofile = FooFile(buckets=[foobucket], foo_link=foo1) |
| 2637 |
|
| 2638 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2639 |
write_io.write(foofile) |
| 2640 |
|
| 2641 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2642 |
|
| 2643 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 2644 |
export_io.export(src_io=read_io) |
| 2645 |
|
| 2646 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2647 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2648 |
read_foofile2 = read_io.read() |
| 2649 |
|
| 2650 |
# make sure the linked group is within the same file |
| 2651 |
self.assertEqual(read_foofile2.foo_link.container_source, self.paths[1]) |
| 2652 |
|
| 2653 |
def test_soft_link_dataset(self): |
| 2654 |
"""Test that exporting a written file with soft linked datasets keeps links within the file.""" |
| 2655 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2656 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2657 |
foofile = FooFile(buckets=[foobucket], foofile_data=foo1.my_data) |
| 2658 |
|
| 2659 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2660 |
write_io.write(foofile) |
| 2661 |
|
| 2662 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2663 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2664 |
|
| 2665 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 2666 |
export_io.export(src_io=read_io) |
| 2667 |
|
| 2668 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2669 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2670 |
read_foofile2 = read_io.read() |
| 2671 |
|
| 2672 |
# make sure the linked dataset is within the same file |
| 2673 |
self.assertEqual(read_foofile2.foofile_data.file.filename, self.paths[1]) |
| 2674 |
|
| 2675 |
def test_soft_link_group_modified(self): |
| 2676 |
"""Test that exporting a written file with soft linked groups keeps links within the file.""" |
| 2677 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2678 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2679 |
foofile = FooFile(buckets=[foobucket], foo_link=foo1) |
| 2680 |
|
| 2681 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2682 |
write_io.write(foofile) |
| 2683 |
|
| 2684 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2685 |
read_foofile2 = read_io.read() |
| 2686 |
read_foofile2.foo_link.set_modified() # trigger a rebuild of foo_link and its parents |
| 2687 |
|
| 2688 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 2689 |
export_io.export(src_io=read_io, container=read_foofile2) |
| 2690 |
|
| 2691 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2692 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2693 |
read_foofile2 = read_io.read() |
| 2694 |
|
| 2695 |
# make sure the linked group is within the same file |
| 2696 |
self.assertEqual(read_foofile2.foo_link.container_source, self.paths[1]) |
| 2697 |
|
| 2698 |
# make sure the linked group is a soft link |
| 2699 |
with File(self.paths[1], 'r') as f: |
| 2700 |
self.assertEqual(f['links/foo_link'].file.filename, self.paths[1]) |
| 2701 |
self.assertIsInstance(f.get('links/foo_link', getlink=True), h5py.SoftLink) |
| 2702 |
|
| 2703 |
def test_soft_link_group_modified_rel_path(self): |
| 2704 |
"""Test that exporting a written file with soft linked groups keeps links within the file.""" |
| 2705 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2706 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2707 |
foofile = FooFile(buckets=[foobucket], foo_link=foo1) |
| 2708 |
# make temp files in relative path location |
| 2709 |
self.paths[0] = os.path.basename(self.paths[0]) |
| 2710 |
self.paths[1] = os.path.basename(self.paths[1]) |
| 2711 |
|
| 2712 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2713 |
write_io.write(foofile) |
| 2714 |
|
| 2715 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2716 |
read_foofile2 = read_io.read() |
| 2717 |
read_foofile2.foo_link.set_modified() # trigger a rebuild of foo_link and its parents |
| 2718 |
|
| 2719 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 2720 |
export_io.export(src_io=read_io, container=read_foofile2) |
| 2721 |
|
| 2722 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2723 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2724 |
read_foofile2 = read_io.read() |
| 2725 |
|
| 2726 |
# make sure the linked group is within the same file |
| 2727 |
self.assertEqual(read_foofile2.foo_link.container_source, os.path.abspath(self.paths[1])) |
| 2728 |
|
| 2729 |
# make sure the linked group is a soft link |
| 2730 |
with File(self.paths[1], 'r') as f: |
| 2731 |
self.assertEqual(f['links/foo_link'].file.filename, self.paths[1]) |
| 2732 |
self.assertIsInstance(f.get('links/foo_link', getlink=True), h5py.SoftLink) |
| 2733 |
|
| 2734 |
def test_external_link_group(self): |
| 2735 |
"""Test that exporting a written file with external linked groups maintains the links.""" |
| 2736 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2737 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2738 |
foofile = FooFile(buckets=[foobucket]) |
| 2739 |
|
| 2740 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as read_io: |
| 2741 |
read_io.write(foofile) |
| 2742 |
|
| 2743 |
manager = get_foo_buildmanager() |
| 2744 |
with HDF5IO(self.paths[0], manager=manager, mode='r') as read_io: |
| 2745 |
read_foofile = read_io.read() |
| 2746 |
# make external link to existing group |
| 2747 |
foofile2 = FooFile(foo_link=read_foofile.buckets['bucket1'].foos['foo1']) |
| 2748 |
|
| 2749 |
with HDF5IO(self.paths[1], manager=manager, mode='w') as write_io: |
| 2750 |
write_io.write(foofile2) |
| 2751 |
|
| 2752 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2753 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2754 |
|
| 2755 |
with HDF5IO(self.paths[2], mode='w') as export_io: |
| 2756 |
export_io.export(src_io=read_io) |
| 2757 |
|
| 2758 |
with HDF5IO(self.paths[2], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2759 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2760 |
read_foofile2 = read_io.read() |
| 2761 |
|
| 2762 |
# make sure the linked group is read from the first file |
| 2763 |
self.assertEqual(read_foofile2.foo_link.container_source, self.paths[0]) |
| 2764 |
|
| 2765 |
def test_external_link_group_rel_path(self): |
| 2766 |
"""Test that exporting a written file from a relative filepath works.""" |
| 2767 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2768 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2769 |
foofile = FooFile(buckets=[foobucket]) |
| 2770 |
# make temp files in relative path location |
| 2771 |
self.paths[0] = os.path.basename(self.paths[0]) |
| 2772 |
self.paths[1] = os.path.basename(self.paths[1]) |
| 2773 |
self.paths[2] = os.path.basename(self.paths[2]) |
| 2774 |
|
| 2775 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as read_io: |
| 2776 |
read_io.write(foofile) |
| 2777 |
|
| 2778 |
manager = get_foo_buildmanager() |
| 2779 |
with HDF5IO(self.paths[0], manager=manager, mode='r') as read_io: |
| 2780 |
read_foofile = read_io.read() |
| 2781 |
# make external link to existing group |
| 2782 |
foofile2 = FooFile(foo_link=read_foofile.buckets['bucket1'].foos['foo1']) |
| 2783 |
|
| 2784 |
with HDF5IO(self.paths[1], manager=manager, mode='w') as write_io: |
| 2785 |
write_io.write(foofile2) |
| 2786 |
|
| 2787 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2788 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2789 |
|
| 2790 |
with HDF5IO(self.paths[2], mode='w') as export_io: |
| 2791 |
export_io.export(src_io=read_io) |
| 2792 |
|
| 2793 |
with HDF5IO(self.paths[2], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2794 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2795 |
read_foofile2 = read_io.read() |
| 2796 |
|
| 2797 |
# make sure the linked group is read from the first file |
| 2798 |
self.assertEqual(read_foofile2.foo_link.container_source, os.path.abspath(self.paths[0])) |
| 2799 |
|
| 2800 |
def test_external_link_dataset(self): |
| 2801 |
"""Test that exporting a written file with external linked datasets maintains the links.""" |
| 2802 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2803 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2804 |
foofile = FooFile(buckets=[foobucket], foofile_data=[1, 2, 3]) |
| 2805 |
|
| 2806 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2807 |
write_io.write(foofile) |
| 2808 |
|
| 2809 |
manager = get_foo_buildmanager() |
| 2810 |
with HDF5IO(self.paths[0], manager=manager, mode='r') as read_io: |
| 2811 |
read_foofile = read_io.read() |
| 2812 |
foofile2 = FooFile(foofile_data=read_foofile.foofile_data) # make external link to existing dataset |
| 2813 |
|
| 2814 |
with HDF5IO(self.paths[1], manager=manager, mode='w') as write_io: |
| 2815 |
write_io.write(foofile2) |
| 2816 |
|
| 2817 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2818 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2819 |
|
| 2820 |
with HDF5IO(self.paths[2], mode='w') as export_io: |
| 2821 |
export_io.export(src_io=read_io) |
| 2822 |
|
| 2823 |
with HDF5IO(self.paths[2], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2824 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2825 |
read_foofile2 = read_io.read() |
| 2826 |
|
| 2827 |
# make sure the linked dataset is read from the first file |
| 2828 |
self.assertEqual(read_foofile2.foofile_data.file.filename, self.paths[0]) |
| 2829 |
|
| 2830 |
def test_external_link_link(self): |
| 2831 |
"""Test that exporting a written file with external links to external links maintains the links.""" |
| 2832 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2833 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2834 |
foofile = FooFile(buckets=[foobucket]) |
| 2835 |
|
| 2836 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2837 |
write_io.write(foofile) |
| 2838 |
|
| 2839 |
manager = get_foo_buildmanager() |
| 2840 |
with HDF5IO(self.paths[0], manager=manager, mode='r') as read_io: |
| 2841 |
read_foofile = read_io.read() |
| 2842 |
# make external link to existing group |
| 2843 |
foofile2 = FooFile(foo_link=read_foofile.buckets['bucket1'].foos['foo1']) |
| 2844 |
|
| 2845 |
with HDF5IO(self.paths[1], manager=manager, mode='w') as write_io: |
| 2846 |
write_io.write(foofile2) |
| 2847 |
|
| 2848 |
manager = get_foo_buildmanager() |
| 2849 |
with HDF5IO(self.paths[1], manager=manager, mode='r') as read_io: |
| 2850 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2851 |
read_foofile2 = read_io.read() |
| 2852 |
foofile3 = FooFile(foo_link=read_foofile2.foo_link) # make external link to external link |
| 2853 |
|
| 2854 |
with HDF5IO(self.paths[2], manager=manager, mode='w') as write_io: |
| 2855 |
write_io.write(foofile3) |
| 2856 |
|
| 2857 |
with HDF5IO(self.paths[2], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2858 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2859 |
|
| 2860 |
with HDF5IO(self.paths[3], mode='w') as export_io: |
| 2861 |
export_io.export(src_io=read_io) |
| 2862 |
|
| 2863 |
with HDF5IO(self.paths[3], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2864 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2865 |
read_foofile3 = read_io.read() |
| 2866 |
|
| 2867 |
# make sure the linked group is read from the first file |
| 2868 |
self.assertEqual(read_foofile3.foo_link.container_source, self.paths[0]) |
| 2869 |
|
| 2870 |
def test_new_soft_link(self): |
| 2871 |
"""Test that exporting a file with a newly created soft link makes the link internally.""" |
| 2872 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2873 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2874 |
foofile = FooFile(buckets=[foobucket]) |
| 2875 |
|
| 2876 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2877 |
write_io.write(foofile) |
| 2878 |
|
| 2879 |
manager = get_foo_buildmanager() |
| 2880 |
with HDF5IO(self.paths[0], manager=manager, mode='r') as read_io: |
| 2881 |
read_foofile = read_io.read() |
| 2882 |
# make external link to existing group |
| 2883 |
read_foofile.foo_link = read_foofile.buckets['bucket1'].foos['foo1'] |
| 2884 |
|
| 2885 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 2886 |
export_io.export(src_io=read_io, container=read_foofile) |
| 2887 |
|
| 2888 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2889 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2890 |
read_foofile2 = read_io.read() |
| 2891 |
|
| 2892 |
# make sure the linked group is read from the exported file |
| 2893 |
self.assertEqual(read_foofile2.foo_link.container_source, self.paths[1]) |
| 2894 |
|
| 2895 |
def test_attr_reference(self): |
| 2896 |
"""Test that exporting a written file with attribute references maintains the references.""" |
| 2897 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2898 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2899 |
foofile = FooFile(buckets=[foobucket], foo_ref_attr=foo1) |
| 2900 |
|
| 2901 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as read_io: |
| 2902 |
read_io.write(foofile) |
| 2903 |
|
| 2904 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2905 |
|
| 2906 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 2907 |
export_io.export(src_io=read_io) |
| 2908 |
|
| 2909 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2910 |
read_foofile2 = read_io.read() |
| 2911 |
|
| 2912 |
# make sure the attribute reference resolves to the container within the same file |
| 2913 |
self.assertIs(read_foofile2.foo_ref_attr, read_foofile2.buckets['bucket1'].foos['foo1']) |
| 2914 |
|
| 2915 |
with File(self.paths[1], 'r') as f: |
| 2916 |
self.assertIsInstance(f.attrs['foo_ref_attr'], h5py.Reference) |
| 2917 |
|
| 2918 |
def test_pop_data(self): |
| 2919 |
"""Test that exporting a written container after removing an element from it works.""" |
| 2920 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2921 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2922 |
foofile = FooFile(buckets=[foobucket]) |
| 2923 |
|
| 2924 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2925 |
write_io.write(foofile) |
| 2926 |
|
| 2927 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2928 |
read_foofile = read_io.read() |
| 2929 |
read_foofile.remove_bucket('bucket1') # remove child group |
| 2930 |
|
| 2931 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 2932 |
export_io.export(src_io=read_io, container=read_foofile) |
| 2933 |
|
| 2934 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2935 |
read_foofile2 = read_io.read() |
| 2936 |
|
| 2937 |
# make sure the read foofile has no buckets |
| 2938 |
self.assertDictEqual(read_foofile2.buckets, {}) |
| 2939 |
|
| 2940 |
# check that file size of file 2 is smaller |
| 2941 |
self.assertTrue(os.path.getsize(self.paths[0]) > os.path.getsize(self.paths[1])) |
| 2942 |
|
| 2943 |
def test_pop_linked_group(self): |
| 2944 |
"""Test that exporting a written container after removing a linked element from it works.""" |
| 2945 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2946 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2947 |
foofile = FooFile(buckets=[foobucket], foo_link=foo1) |
| 2948 |
|
| 2949 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2950 |
write_io.write(foofile) |
| 2951 |
|
| 2952 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2953 |
read_foofile = read_io.read() |
| 2954 |
read_foofile.buckets['bucket1'].remove_foo('foo1') # remove child group |
| 2955 |
|
| 2956 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 2957 |
msg = ("links (links): Linked Foo 'foo1' has no parent. Remove the link or ensure the linked " |
| 2958 |
"container is added properly.") |
| 2959 |
with self.assertRaisesWith(OrphanContainerBuildError, msg): |
| 2960 |
export_io.export(src_io=read_io, container=read_foofile) |
| 2961 |
|
| 2962 |
def test_append_data(self): |
| 2963 |
"""Test that exporting a written container after adding groups, links, and references to it works.""" |
| 2964 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 2965 |
foobucket = FooBucket('bucket1', [foo1]) |
| 2966 |
foofile = FooFile(buckets=[foobucket]) |
| 2967 |
|
| 2968 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 2969 |
write_io.write(foofile) |
| 2970 |
|
| 2971 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2972 |
read_foofile = read_io.read() |
| 2973 |
|
| 2974 |
# create a foo with link to existing dataset my_data, add the foo to new foobucket |
| 2975 |
# this should make a soft link within the exported file |
| 2976 |
foo2 = Foo('foo2', read_foofile.buckets['bucket1'].foos['foo1'].my_data, "I am foo2", 17, 3.14) |
| 2977 |
foobucket2 = FooBucket('bucket2', [foo2]) |
| 2978 |
read_foofile.add_bucket(foobucket2) |
| 2979 |
|
| 2980 |
# also add link from foofile to new foo2 container |
| 2981 |
read_foofile.foo_link = foo2 |
| 2982 |
|
| 2983 |
# also add link from foofile to new foo2.my_data dataset which is a link to foo1.my_data dataset |
| 2984 |
read_foofile.foofile_data = foo2.my_data |
| 2985 |
|
| 2986 |
# also add reference from foofile to new foo2 |
| 2987 |
read_foofile.foo_ref_attr = foo2 |
| 2988 |
|
| 2989 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 2990 |
export_io.export(src_io=read_io, container=read_foofile) |
| 2991 |
|
| 2992 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 2993 |
self.ios.append(read_io) # track IO objects for tearDown |
| 2994 |
read_foofile2 = read_io.read() |
| 2995 |
|
| 2996 |
# test new soft link to dataset in file |
| 2997 |
self.assertIs(read_foofile2.buckets['bucket1'].foos['foo1'].my_data, |
| 2998 |
read_foofile2.buckets['bucket2'].foos['foo2'].my_data) |
| 2999 |
|
| 3000 |
# test new soft link to group in file |
| 3001 |
self.assertIs(read_foofile2.foo_link, read_foofile2.buckets['bucket2'].foos['foo2']) |
| 3002 |
|
| 3003 |
# test new soft link to new soft link to dataset in file |
| 3004 |
self.assertIs(read_foofile2.buckets['bucket1'].foos['foo1'].my_data, read_foofile2.foofile_data) |
| 3005 |
|
| 3006 |
# test new attribute reference to new group in file |
| 3007 |
self.assertIs(read_foofile2.foo_ref_attr, read_foofile2.buckets['bucket2'].foos['foo2']) |
| 3008 |
|
| 3009 |
with File(self.paths[1], 'r') as f: |
| 3010 |
self.assertEqual(f['foofile_data'].file.filename, self.paths[1]) |
| 3011 |
self.assertIsInstance(f.attrs['foo_ref_attr'], h5py.Reference) |
| 3012 |
|
| 3013 |
def test_append_dataset_of_references(self): |
| 3014 |
"""Test that exporting a written container with a dataset of references works.""" |
| 3015 |
bazs = [] |
| 3016 |
num_bazs = 1 |
| 3017 |
for i in range(num_bazs): |
| 3018 |
bazs.append(Baz(name='baz%d' % i)) |
| 3019 |
array_bazs=np.array(bazs) |
| 3020 |
wrapped_bazs = H5DataIO(array_bazs, maxshape=(None,)) |
| 3021 |
baz_data = BazData(name='baz_data1', data=wrapped_bazs) |
| 3022 |
bucket = BazBucket(name='bucket1', bazs=bazs.copy(), baz_data=baz_data) |
| 3023 |
|
| 3024 |
with HDF5IO(self.paths[0], manager=get_baz_buildmanager(), mode='w') as write_io: |
| 3025 |
write_io.write(bucket) |
| 3026 |
|
| 3027 |
with HDF5IO(self.paths[0], manager=get_baz_buildmanager(), mode='a') as append_io: |
| 3028 |
read_bucket1 = append_io.read() |
| 3029 |
new_baz = Baz(name='new') |
| 3030 |
read_bucket1.add_baz(new_baz) |
| 3031 |
append_io.write(read_bucket1) |
| 3032 |
|
| 3033 |
with HDF5IO(self.paths[0], manager=get_baz_buildmanager(), mode='a') as ref_io: |
| 3034 |
read_bucket1 = ref_io.read() |
| 3035 |
DoR = read_bucket1.baz_data.data |
| 3036 |
DoR.append(read_bucket1.bazs['new']) |
| 3037 |
|
| 3038 |
with HDF5IO(self.paths[0], manager=get_baz_buildmanager(), mode='r') as read_io: |
| 3039 |
read_bucket1 = read_io.read() |
| 3040 |
self.assertEqual(len(read_bucket1.baz_data.data), 2) |
| 3041 |
self.assertIs(read_bucket1.baz_data.data[1], read_bucket1.bazs["new"]) |
| 3042 |
|
| 3043 |
def test_append_dataset_of_references_orphaned_target(self): |
| 3044 |
bazs = [] |
| 3045 |
num_bazs = 1 |
| 3046 |
for i in range(num_bazs): |
| 3047 |
bazs.append(Baz(name='baz%d' % i)) |
| 3048 |
array_bazs=np.array(bazs) |
| 3049 |
wrapped_bazs = H5DataIO(array_bazs, maxshape=(None,)) |
| 3050 |
baz_data = BazData(name='baz_data1', data=wrapped_bazs) |
| 3051 |
bucket = BazBucket(name='bucket1', bazs=bazs.copy(), baz_data=baz_data) |
| 3052 |
|
| 3053 |
with HDF5IO(self.paths[0], manager=get_baz_buildmanager(), mode='w') as write_io: |
| 3054 |
write_io.write(bucket) |
| 3055 |
|
| 3056 |
with HDF5IO(self.paths[0], manager=get_baz_buildmanager(), mode='a') as ref_io: |
| 3057 |
read_bucket1 = ref_io.read() |
| 3058 |
new_baz = Baz(name='new') |
| 3059 |
read_bucket1.add_baz(new_baz) |
| 3060 |
DoR = read_bucket1.baz_data.data |
| 3061 |
with self.assertRaises(ValueError): |
| 3062 |
DoR.append(read_bucket1.bazs['new']) |
| 3063 |
|
| 3064 |
def test_append_external_link_data(self): |
| 3065 |
"""Test that exporting a written container after adding a link with link_data=True creates external links.""" |
| 3066 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 3067 |
foobucket = FooBucket('bucket1', [foo1]) |
| 3068 |
foofile = FooFile(buckets=[foobucket]) |
| 3069 |
|
| 3070 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 3071 |
write_io.write(foofile) |
| 3072 |
|
| 3073 |
foofile2 = FooFile(buckets=[]) |
| 3074 |
|
| 3075 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 3076 |
write_io.write(foofile2) |
| 3077 |
|
| 3078 |
manager = get_foo_buildmanager() |
| 3079 |
with HDF5IO(self.paths[0], manager=manager, mode='r') as read_io1: |
| 3080 |
self.ios.append(read_io1) # track IO objects for tearDown |
| 3081 |
read_foofile1 = read_io1.read() |
| 3082 |
|
| 3083 |
with HDF5IO(self.paths[1], manager=manager, mode='r') as read_io2: |
| 3084 |
self.ios.append(read_io2) |
| 3085 |
read_foofile2 = read_io2.read() |
| 3086 |
|
| 3087 |
# create a foo with link to existing dataset my_data (not in same file), add the foo to new foobucket |
| 3088 |
# this should make an external link within the exported file |
| 3089 |
foo2 = Foo('foo2', read_foofile1.buckets['bucket1'].foos['foo1'].my_data, "I am foo2", 17, 3.14) |
| 3090 |
foobucket2 = FooBucket('bucket2', [foo2]) |
| 3091 |
read_foofile2.add_bucket(foobucket2) |
| 3092 |
|
| 3093 |
# also add link from foofile to new foo2.my_data dataset which is a link to foo1.my_data dataset |
| 3094 |
# this should make an external link within the exported file |
| 3095 |
read_foofile2.foofile_data = foo2.my_data |
| 3096 |
|
| 3097 |
with HDF5IO(self.paths[2], mode='w') as export_io: |
| 3098 |
export_io.export(src_io=read_io2, container=read_foofile2) |
| 3099 |
|
| 3100 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io1: |
| 3101 |
self.ios.append(read_io1) # track IO objects for tearDown |
| 3102 |
read_foofile3 = read_io1.read() |
| 3103 |
|
| 3104 |
with HDF5IO(self.paths[2], manager=get_foo_buildmanager(), mode='r') as read_io2: |
| 3105 |
self.ios.append(read_io2) # track IO objects for tearDown |
| 3106 |
read_foofile4 = read_io2.read() |
| 3107 |
|
| 3108 |
self.assertEqual(read_foofile4.buckets['bucket2'].foos['foo2'].my_data, |
| 3109 |
read_foofile3.buckets['bucket1'].foos['foo1'].my_data) |
| 3110 |
self.assertEqual(read_foofile4.foofile_data, read_foofile3.buckets['bucket1'].foos['foo1'].my_data) |
| 3111 |
|
| 3112 |
with File(self.paths[2], 'r') as f: |
| 3113 |
self.assertEqual(f['buckets/bucket2/foo_holder/foo2/my_data'].file.filename, self.paths[0]) |
| 3114 |
self.assertEqual(f['foofile_data'].file.filename, self.paths[0]) |
| 3115 |
self.assertIsInstance(f.get('buckets/bucket2/foo_holder/foo2/my_data', getlink=True), |
| 3116 |
h5py.ExternalLink) |
| 3117 |
self.assertIsInstance(f.get('foofile_data', getlink=True), h5py.ExternalLink) |
| 3118 |
|
| 3119 |
def test_append_external_link_copy_data(self): |
| 3120 |
"""Test that exporting a written container after adding a link with link_data=False copies the data.""" |
| 3121 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 3122 |
foobucket = FooBucket('bucket1', [foo1]) |
| 3123 |
foofile = FooFile(buckets=[foobucket]) |
| 3124 |
|
| 3125 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 3126 |
write_io.write(foofile) |
| 3127 |
|
| 3128 |
foofile2 = FooFile(buckets=[]) |
| 3129 |
|
| 3130 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 3131 |
write_io.write(foofile2) |
| 3132 |
|
| 3133 |
manager = get_foo_buildmanager() |
| 3134 |
with HDF5IO(self.paths[0], manager=manager, mode='r') as read_io1: |
| 3135 |
self.ios.append(read_io1) # track IO objects for tearDown |
| 3136 |
read_foofile1 = read_io1.read() |
| 3137 |
|
| 3138 |
with HDF5IO(self.paths[1], manager=manager, mode='r') as read_io2: |
| 3139 |
self.ios.append(read_io2) |
| 3140 |
read_foofile2 = read_io2.read() |
| 3141 |
|
| 3142 |
# create a foo with link to existing dataset my_data (not in same file), add the foo to new foobucket |
| 3143 |
# this would normally make an external link but because link_data=False, data will be copied |
| 3144 |
foo2 = Foo('foo2', read_foofile1.buckets['bucket1'].foos['foo1'].my_data, "I am foo2", 17, 3.14) |
| 3145 |
foobucket2 = FooBucket('bucket2', [foo2]) |
| 3146 |
read_foofile2.add_bucket(foobucket2) |
| 3147 |
|
| 3148 |
# also add link from foofile to new foo2.my_data dataset which is a link to foo1.my_data dataset |
| 3149 |
# this would normally make an external link but because link_data=False, data will be copied |
| 3150 |
read_foofile2.foofile_data = foo2.my_data |
| 3151 |
|
| 3152 |
with HDF5IO(self.paths[2], mode='w') as export_io: |
| 3153 |
export_io.export(src_io=read_io2, container=read_foofile2, write_args={'link_data': False}) |
| 3154 |
|
| 3155 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io1: |
| 3156 |
self.ios.append(read_io1) # track IO objects for tearDown |
| 3157 |
read_foofile3 = read_io1.read() |
| 3158 |
|
| 3159 |
with HDF5IO(self.paths[2], manager=get_foo_buildmanager(), mode='r') as read_io2: |
| 3160 |
self.ios.append(read_io2) # track IO objects for tearDown |
| 3161 |
read_foofile4 = read_io2.read() |
| 3162 |
|
| 3163 |
# check that file can be read |
| 3164 |
self.assertNotEqual(read_foofile4.buckets['bucket2'].foos['foo2'].my_data, |
| 3165 |
read_foofile3.buckets['bucket1'].foos['foo1'].my_data) |
| 3166 |
self.assertNotEqual(read_foofile4.foofile_data, read_foofile3.buckets['bucket1'].foos['foo1'].my_data) |
| 3167 |
self.assertNotEqual(read_foofile4.foofile_data, read_foofile4.buckets['bucket2'].foos['foo2'].my_data) |
| 3168 |
|
| 3169 |
with File(self.paths[2], 'r') as f: |
| 3170 |
self.assertEqual(f['buckets/bucket2/foo_holder/foo2/my_data'].file.filename, self.paths[2]) |
| 3171 |
self.assertEqual(f['foofile_data'].file.filename, self.paths[2]) |
| 3172 |
|
| 3173 |
def test_export_simple_link_data(self): |
| 3174 |
"""Test simple exporting of data with a link with link_data=True links the data.""" |
| 3175 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 3176 |
foobucket = FooBucket('bucket1', [foo1]) |
| 3177 |
foofile = FooFile([foobucket]) |
| 3178 |
|
| 3179 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 3180 |
write_io.write(foofile) |
| 3181 |
|
| 3182 |
# create new foofile with link from foo2.data to read foo1.data |
| 3183 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 3184 |
read_foofile1 = read_io.read() |
| 3185 |
foo2 = Foo('foo2', read_foofile1.buckets['bucket1'].foos['foo1'].my_data, "I am foo2", 17, 3.14) |
| 3186 |
foobucket2 = FooBucket('bucket2', [foo2]) |
| 3187 |
foofile2 = FooFile([foobucket2]) |
| 3188 |
|
| 3189 |
# also add link from foofile to new foo2.my_data dataset which is a link to foo1.my_data dataset |
| 3190 |
# this should make an external link within the exported file |
| 3191 |
foofile2.foofile_data = foo2.my_data |
| 3192 |
|
| 3193 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 3194 |
write_io.write(foofile2) |
| 3195 |
|
| 3196 |
# read the data with the linked dataset, do not modify it, and export it |
| 3197 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 3198 |
with HDF5IO(self.paths[2], mode='w') as export_io: |
| 3199 |
export_io.export(src_io=read_io) |
| 3200 |
|
| 3201 |
# read the exported file and confirm that the dataset is linked to the correct foofile1 |
| 3202 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io1: |
| 3203 |
self.ios.append(read_io1) # track IO objects for tearDown |
| 3204 |
read_foofile3 = read_io1.read() |
| 3205 |
|
| 3206 |
with HDF5IO(self.paths[2], manager=get_foo_buildmanager(), mode='r') as read_io2: |
| 3207 |
self.ios.append(read_io2) # track IO objects for tearDown |
| 3208 |
read_foofile4 = read_io2.read() |
| 3209 |
|
| 3210 |
self.assertEqual(read_foofile4.buckets['bucket2'].foos['foo2'].my_data, |
| 3211 |
read_foofile3.buckets['bucket1'].foos['foo1'].my_data) |
| 3212 |
self.assertEqual(read_foofile4.foofile_data, read_foofile3.buckets['bucket1'].foos['foo1'].my_data) |
| 3213 |
|
| 3214 |
with File(self.paths[2], 'r') as f: |
| 3215 |
self.assertEqual(f['buckets/bucket2/foo_holder/foo2/my_data'].file.filename, self.paths[0]) |
| 3216 |
self.assertEqual(f['foofile_data'].file.filename, self.paths[0]) |
| 3217 |
self.assertIsInstance(f.get('buckets/bucket2/foo_holder/foo2/my_data', getlink=True), |
| 3218 |
h5py.ExternalLink) |
| 3219 |
self.assertIsInstance(f.get('foofile_data', getlink=True), h5py.ExternalLink) |
| 3220 |
|
| 3221 |
def test_export_simple_link_data_false(self): |
| 3222 |
"""Test simple exporting of data with a link with link_data=False copies the data.""" |
| 3223 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 3224 |
foobucket = FooBucket('bucket1', [foo1]) |
| 3225 |
foofile = FooFile([foobucket]) |
| 3226 |
|
| 3227 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 3228 |
write_io.write(foofile) |
| 3229 |
|
| 3230 |
# create new foofile with link from foo2.data to read foo1.data |
| 3231 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 3232 |
read_foofile1 = read_io.read() |
| 3233 |
foo2 = Foo('foo2', read_foofile1.buckets['bucket1'].foos['foo1'].my_data, "I am foo2", 17, 3.14) |
| 3234 |
foobucket2 = FooBucket('bucket2', [foo2]) |
| 3235 |
foofile2 = FooFile([foobucket2]) |
| 3236 |
|
| 3237 |
# also add link from foofile to new foo2.my_data dataset which is a link to foo1.my_data dataset |
| 3238 |
# this should make an external link within the exported file |
| 3239 |
foofile2.foofile_data = foo2.my_data |
| 3240 |
|
| 3241 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 3242 |
write_io.write(foofile2) |
| 3243 |
|
| 3244 |
# read the data with the linked dataset, do not modify it, and export it |
| 3245 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 3246 |
with HDF5IO(self.paths[2], mode='w') as export_io: |
| 3247 |
export_io.export(src_io=read_io, write_args={'link_data': False}) |
| 3248 |
|
| 3249 |
# read the exported file and confirm that the dataset is copied |
| 3250 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io1: |
| 3251 |
self.ios.append(read_io1) # track IO objects for tearDown |
| 3252 |
read_foofile3 = read_io1.read() |
| 3253 |
|
| 3254 |
with HDF5IO(self.paths[2], manager=get_foo_buildmanager(), mode='r') as read_io2: |
| 3255 |
self.ios.append(read_io2) # track IO objects for tearDown |
| 3256 |
read_foofile4 = read_io2.read() |
| 3257 |
|
| 3258 |
# check that file can be read |
| 3259 |
self.assertNotEqual(read_foofile4.buckets['bucket2'].foos['foo2'].my_data, |
| 3260 |
read_foofile3.buckets['bucket1'].foos['foo1'].my_data) |
| 3261 |
self.assertNotEqual(read_foofile4.foofile_data, read_foofile3.buckets['bucket1'].foos['foo1'].my_data) |
| 3262 |
self.assertNotEqual(read_foofile4.foofile_data, read_foofile4.buckets['bucket2'].foos['foo2'].my_data) |
| 3263 |
|
| 3264 |
with File(self.paths[2], 'r') as f: |
| 3265 |
self.assertEqual(f['buckets/bucket2/foo_holder/foo2/my_data'].file.filename, self.paths[2]) |
| 3266 |
self.assertEqual(f['foofile_data'].file.filename, self.paths[2]) |
| 3267 |
|
| 3268 |
def test_export_simple_with_container_link_data_false(self): |
| 3269 |
"""Test simple exporting of data with a link with link_data=False copies the data.""" |
| 3270 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 3271 |
foobucket = FooBucket('bucket1', [foo1]) |
| 3272 |
foofile = FooFile([foobucket]) |
| 3273 |
|
| 3274 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 3275 |
write_io.write(foofile) |
| 3276 |
|
| 3277 |
# create new foofile with link from foo2.data to read foo1.data |
| 3278 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 3279 |
read_foofile1 = read_io.read() |
| 3280 |
foo2 = Foo('foo2', read_foofile1.buckets['bucket1'].foos['foo1'].my_data, "I am foo2", 17, 3.14) |
| 3281 |
foobucket2 = FooBucket('bucket2', [foo2]) |
| 3282 |
foofile2 = FooFile([foobucket2]) |
| 3283 |
|
| 3284 |
# also add link from foofile to new foo2.my_data dataset which is a link to foo1.my_data dataset |
| 3285 |
# this should make an external link within the exported file |
| 3286 |
foofile2.foofile_data = foo2.my_data |
| 3287 |
|
| 3288 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 3289 |
write_io.write(foofile2) |
| 3290 |
|
| 3291 |
# read the data with the linked dataset, do not modify it, and export it |
| 3292 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 3293 |
read_foofile2 = read_io.read() |
| 3294 |
with HDF5IO(self.paths[2], mode='w') as export_io: |
| 3295 |
export_io.export(src_io=read_io, container=read_foofile2, write_args={'link_data': False}) |
| 3296 |
|
| 3297 |
# read the exported file and confirm that the dataset is copied |
| 3298 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io1: |
| 3299 |
self.ios.append(read_io1) # track IO objects for tearDown |
| 3300 |
read_foofile3 = read_io1.read() |
| 3301 |
|
| 3302 |
with HDF5IO(self.paths[2], manager=get_foo_buildmanager(), mode='r') as read_io2: |
| 3303 |
self.ios.append(read_io2) # track IO objects for tearDown |
| 3304 |
read_foofile4 = read_io2.read() |
| 3305 |
|
| 3306 |
# check that file can be read |
| 3307 |
self.assertNotEqual(read_foofile4.buckets['bucket2'].foos['foo2'].my_data, |
| 3308 |
read_foofile3.buckets['bucket1'].foos['foo1'].my_data) |
| 3309 |
self.assertNotEqual(read_foofile4.foofile_data, read_foofile3.buckets['bucket1'].foos['foo1'].my_data) |
| 3310 |
self.assertNotEqual(read_foofile4.foofile_data, read_foofile4.buckets['bucket2'].foos['foo2'].my_data) |
| 3311 |
|
| 3312 |
with File(self.paths[2], 'r') as f: |
| 3313 |
self.assertEqual(f['buckets/bucket2/foo_holder/foo2/my_data'].file.filename, self.paths[2]) |
| 3314 |
self.assertEqual(f['foofile_data'].file.filename, self.paths[2]) |
| 3315 |
|
| 3316 |
def test_export_io(self): |
| 3317 |
"""Test that exporting a written container using HDF5IO.export_io works.""" |
| 3318 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 3319 |
foobucket = FooBucket('bucket1', [foo1]) |
| 3320 |
foofile = FooFile(buckets=[foobucket]) |
| 3321 |
|
| 3322 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 3323 |
write_io.write(foofile) |
| 3324 |
|
| 3325 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 3326 |
HDF5IO.export_io(src_io=read_io, path=self.paths[1]) |
| 3327 |
|
| 3328 |
self.assertTrue(os.path.exists(self.paths[1])) |
| 3329 |
self.assertEqual(foofile.container_source, self.paths[0]) |
| 3330 |
|
| 3331 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 3332 |
read_foofile = read_io.read() |
| 3333 |
self.assertEqual(read_foofile.container_source, self.paths[1]) |
| 3334 |
self.assertContainerEqual(foofile, read_foofile, ignore_hdmf_attrs=True) |
| 3335 |
|
| 3336 |
def test_export_dset_refs(self): |
| 3337 |
"""Test that exporting a written container with a dataset of references works.""" |
| 3338 |
bazs = [] |
| 3339 |
num_bazs = 10 |
| 3340 |
for i in range(num_bazs): |
| 3341 |
bazs.append(Baz(name='baz%d' % i)) |
| 3342 |
baz_data = BazData(name='baz_data1', data=bazs) |
| 3343 |
bucket = BazBucket(name='bucket1', bazs=bazs.copy(), baz_data=baz_data) |
| 3344 |
|
| 3345 |
with HDF5IO(self.paths[0], manager=get_baz_buildmanager(), mode='w') as write_io: |
| 3346 |
write_io.write(bucket) |
| 3347 |
|
| 3348 |
with HDF5IO(self.paths[0], manager=get_baz_buildmanager(), mode='r') as read_io: |
| 3349 |
read_bucket1 = read_io.read() |
| 3350 |
|
| 3351 |
# NOTE: reference IDs might be the same between two identical files |
| 3352 |
# adding a Baz with a smaller name should change the reference IDs on export |
| 3353 |
new_baz = Baz(name='baz000') |
| 3354 |
read_bucket1.add_baz(new_baz) |
| 3355 |
|
| 3356 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 3357 |
export_io.export(src_io=read_io, container=read_bucket1) |
| 3358 |
|
| 3359 |
with HDF5IO(self.paths[1], manager=get_baz_buildmanager(), mode='r') as read_io: |
| 3360 |
read_bucket2 = read_io.read() |
| 3361 |
|
| 3362 |
# remove and check the appended child, then compare the read container with the original |
| 3363 |
read_new_baz = read_bucket2.remove_baz('baz000') |
| 3364 |
self.assertContainerEqual(new_baz, read_new_baz, ignore_hdmf_attrs=True) |
| 3365 |
|
| 3366 |
self.assertContainerEqual(bucket, read_bucket2, ignore_name=True, ignore_hdmf_attrs=True) |
| 3367 |
for i in range(num_bazs): |
| 3368 |
baz_name = 'baz%d' % i |
| 3369 |
self.assertIs(read_bucket2.baz_data.data[i], read_bucket2.bazs[baz_name]) |
| 3370 |
|
| 3371 |
def test_export_cpd_dset_refs(self): |
| 3372 |
"""Test that exporting a written container with a compound dataset with references works.""" |
| 3373 |
bazs = [] |
| 3374 |
baz_pairs = [] |
| 3375 |
num_bazs = 10 |
| 3376 |
for i in range(num_bazs): |
| 3377 |
b = Baz(name='baz%d' % i) |
| 3378 |
bazs.append(b) |
| 3379 |
baz_pairs.append((i, b)) |
| 3380 |
baz_cpd_data = BazCpdData(name='baz_cpd_data1', data=baz_pairs) |
| 3381 |
bucket = BazBucket(name='bucket1', bazs=bazs.copy(), baz_cpd_data=baz_cpd_data) |
| 3382 |
|
| 3383 |
with HDF5IO(self.paths[0], manager=get_baz_buildmanager(), mode='w') as write_io: |
| 3384 |
write_io.write(bucket) |
| 3385 |
|
| 3386 |
with HDF5IO(self.paths[0], manager=get_baz_buildmanager(), mode='r') as read_io: |
| 3387 |
read_bucket1 = read_io.read() |
| 3388 |
|
| 3389 |
# NOTE: reference IDs might be the same between two identical files |
| 3390 |
# adding a Baz with a smaller name should change the reference IDs on export |
| 3391 |
new_baz = Baz(name='baz000') |
| 3392 |
read_bucket1.add_baz(new_baz) |
| 3393 |
|
| 3394 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 3395 |
export_io.export(src_io=read_io, container=read_bucket1) |
| 3396 |
|
| 3397 |
with HDF5IO(self.paths[1], manager=get_baz_buildmanager(), mode='r') as read_io: |
| 3398 |
read_bucket2 = read_io.read() |
| 3399 |
|
| 3400 |
# remove and check the appended child, then compare the read container with the original |
| 3401 |
read_new_baz = read_bucket2.remove_baz(new_baz.name) |
| 3402 |
self.assertContainerEqual(new_baz, read_new_baz, ignore_hdmf_attrs=True) |
| 3403 |
|
| 3404 |
self.assertContainerEqual(bucket, read_bucket2, ignore_name=True, ignore_hdmf_attrs=True) |
| 3405 |
for i in range(num_bazs): |
| 3406 |
baz_name = 'baz%d' % i |
| 3407 |
self.assertEqual(read_bucket2.baz_cpd_data.data[i][0], i) |
| 3408 |
self.assertIs(read_bucket2.baz_cpd_data.data[i][1], read_bucket2.bazs[baz_name]) |
| 3409 |
|
| 3410 |
def test_non_manager_container(self): |
| 3411 |
"""Test that exporting with a src_io without a manager raises an error.""" |
| 3412 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 3413 |
foobucket = FooBucket('bucket1', [foo1]) |
| 3414 |
foofile = FooFile(buckets=[foobucket]) |
| 3415 |
|
| 3416 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 3417 |
write_io.write(foofile) |
| 3418 |
|
| 3419 |
class OtherIO(HDMFIO): |
| 3420 |
|
| 3421 |
@staticmethod |
| 3422 |
def can_read(path): |
| 3423 |
pass |
| 3424 |
|
| 3425 |
def read_builder(self): |
| 3426 |
pass |
| 3427 |
|
| 3428 |
def write_builder(self, **kwargs): |
| 3429 |
pass |
| 3430 |
|
| 3431 |
def open(self): |
| 3432 |
pass |
| 3433 |
|
| 3434 |
def close(self): |
| 3435 |
pass |
| 3436 |
|
| 3437 |
with OtherIO() as read_io: |
| 3438 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 3439 |
msg = 'When a container is provided, src_io must have a non-None manager (BuildManager) property.' |
| 3440 |
with self.assertRaisesWith(ValueError, msg): |
| 3441 |
export_io.export(src_io=read_io, container=foofile, write_args={'link_data': False}) |
| 3442 |
|
| 3443 |
def test_non_HDF5_src_link_data_true(self): |
| 3444 |
"""Test that exporting with a src_io without a manager raises an error.""" |
| 3445 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 3446 |
foobucket = FooBucket('bucket1', [foo1]) |
| 3447 |
foofile = FooFile(buckets=[foobucket]) |
| 3448 |
|
| 3449 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 3450 |
write_io.write(foofile) |
| 3451 |
|
| 3452 |
class OtherIO(HDMFIO): |
| 3453 |
|
| 3454 |
@staticmethod |
| 3455 |
def can_read(path): |
| 3456 |
pass |
| 3457 |
|
| 3458 |
def __init__(self, manager): |
| 3459 |
super().__init__(manager=manager) |
| 3460 |
|
| 3461 |
def read_builder(self): |
| 3462 |
pass |
| 3463 |
|
| 3464 |
def write_builder(self, **kwargs): |
| 3465 |
pass |
| 3466 |
|
| 3467 |
def open(self): |
| 3468 |
pass |
| 3469 |
|
| 3470 |
def close(self): |
| 3471 |
pass |
| 3472 |
|
| 3473 |
with OtherIO(manager=get_foo_buildmanager()) as read_io: |
| 3474 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 3475 |
msg = "Cannot export from non-HDF5 backend OtherIO to HDF5 with write argument link_data=True." |
| 3476 |
with self.assertRaisesWith(UnsupportedOperation, msg): |
| 3477 |
export_io.export(src_io=read_io, container=foofile) |
| 3478 |
|
| 3479 |
def test_wrong_mode(self): |
| 3480 |
"""Test that exporting with a src_io without a manager raises an error.""" |
| 3481 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 3482 |
foobucket = FooBucket('bucket1', [foo1]) |
| 3483 |
foofile = FooFile(buckets=[foobucket]) |
| 3484 |
|
| 3485 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 3486 |
write_io.write(foofile) |
| 3487 |
|
| 3488 |
with HDF5IO(self.paths[0], mode='r') as read_io: |
| 3489 |
with HDF5IO(self.paths[1], mode='a') as export_io: |
| 3490 |
msg = "Cannot export to file %s in mode 'a'. Please use mode 'w'." % self.paths[1] |
| 3491 |
with self.assertRaisesWith(UnsupportedOperation, msg): |
| 3492 |
export_io.export(src_io=read_io) |
| 3493 |
|
| 3494 |
def test_with_new_id(self): |
| 3495 |
"""Test that exporting with a src_io without a manager raises an error.""" |
| 3496 |
foo1 = Foo('foo1', [1, 2, 3, 4, 5], "I am foo1", 17, 3.14) |
| 3497 |
foobucket = FooBucket('bucket1', [foo1]) |
| 3498 |
foofile = FooFile([foobucket]) |
| 3499 |
|
| 3500 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='w') as write_io: |
| 3501 |
write_io.write(foofile) |
| 3502 |
|
| 3503 |
with HDF5IO(self.paths[0], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 3504 |
data = read_io.read() |
| 3505 |
original_id = data.object_id |
| 3506 |
data.generate_new_id() |
| 3507 |
with HDF5IO(self.paths[1], mode='w') as export_io: |
| 3508 |
export_io.export(src_io=read_io, container=data) |
| 3509 |
|
| 3510 |
with HDF5IO(self.paths[1], manager=get_foo_buildmanager(), mode='r') as read_io: |
| 3511 |
data = read_io.read() |
| 3512 |
self.assertTrue(original_id != data.object_id) |
| 3513 |
|
| 3514 |
|
| 3515 |
class TestDatasetRefs(TestCase): |
| 3516 |
|
| 3517 |
def test_roundtrip(self): |
| 3518 |
self.path = get_temp_filepath() |
| 3519 |
bazs = [] |
| 3520 |
num_bazs = 10 |
| 3521 |
for i in range(num_bazs): |
| 3522 |
bazs.append(Baz(name='baz%d' % i)) |
| 3523 |
baz_data = BazData(name='baz_data1', data=bazs) |
| 3524 |
bucket = BazBucket(name='bucket1', bazs=bazs.copy(), baz_data=baz_data) |
| 3525 |
|
| 3526 |
with HDF5IO(self.path, manager=get_baz_buildmanager(), mode='w') as write_io: |
| 3527 |
write_io.write(bucket) |
| 3528 |
|
| 3529 |
with HDF5IO(self.path, manager=get_baz_buildmanager(), mode='r') as read_io: |
| 3530 |
read_bucket = read_io.read() |
| 3531 |
|
| 3532 |
self.assertContainerEqual(bucket, read_bucket, ignore_name=True) |
| 3533 |
for i in range(num_bazs): |
| 3534 |
baz_name = 'baz%d' % i |
| 3535 |
self.assertIs(read_bucket.baz_data.data[i], read_bucket.bazs[baz_name]) |
| 3536 |
|
| 3537 |
|
| 3538 |
class TestCpdDatasetRefs(TestCase): |
| 3539 |
|
| 3540 |
def test_roundtrip(self): |
| 3541 |
self.path = get_temp_filepath() |
| 3542 |
bazs = [] |
| 3543 |
baz_pairs = [] |
| 3544 |
num_bazs = 10 |
| 3545 |
for i in range(num_bazs): |
| 3546 |
b = Baz(name='baz%d' % i) |
| 3547 |
bazs.append(b) |
| 3548 |
baz_pairs.append((i, b)) |
| 3549 |
baz_cpd_data = BazCpdData(name='baz_cpd_data1', data=baz_pairs) |
| 3550 |
bucket = BazBucket(name='bucket1', bazs=bazs.copy(), baz_cpd_data=baz_cpd_data) |
| 3551 |
|
| 3552 |
with HDF5IO(self.path, manager=get_baz_buildmanager(), mode='w') as write_io: |
| 3553 |
write_io.write(bucket) |
| 3554 |
|
| 3555 |
with HDF5IO(self.path, manager=get_baz_buildmanager(), mode='r') as read_io: |
| 3556 |
read_bucket = read_io.read() |
| 3557 |
|
| 3558 |
self.assertContainerEqual(bucket, read_bucket, ignore_name=True) |
| 3559 |
for i in range(num_bazs): |
| 3560 |
baz_name = 'baz%d' % i |
| 3561 |
self.assertEqual(read_bucket.baz_cpd_data.data[i][0], i) |
| 3562 |
self.assertIs(read_bucket.baz_cpd_data.data[i][1], read_bucket.bazs[baz_name]) |
| 3563 |
|
| 3564 |
|
| 3565 |
@unittest.skipIf(SKIP_ZARR_TESTS, "Skipping TestRoundTripHDF5withZarrInput because Zarr is not installed") |
| 3566 |
class TestWriteHDF5withZarrInput(TestCase): |
| 3567 |
""" |
| 3568 |
Test saving data to HDF5 with a zarr.Array as the data |
| 3569 |
""" |
| 3570 |
def setUp(self): |
| 3571 |
self.manager = get_foo_buildmanager() |
| 3572 |
self.path = get_temp_filepath() |
| 3573 |
self.path = get_temp_filepath() |
| 3574 |
self.zarr_path = tempfile.mkdtemp() |
| 3575 |
|
| 3576 |
def tearDown(self): |
| 3577 |
if os.path.exists(self.path): |
| 3578 |
os.remove(self.path) |
| 3579 |
if os.path.exists(self.zarr_path): |
| 3580 |
shutil.rmtree(self.zarr_path) |
| 3581 |
|
| 3582 |
def test_roundtrip_basic(self): |
| 3583 |
# Setup all the data we need |
| 3584 |
zarr.save(self.zarr_path, np.arange(50).reshape(5, 10)) |
| 3585 |
zarr_data = zarr.open(self.zarr_path, 'r') |
| 3586 |
foo1 = Foo(name='foo1', |
| 3587 |
my_data=zarr_data, |
| 3588 |
attr1="I am foo1", |
| 3589 |
attr2=17, |
| 3590 |
attr3=3.14) |
| 3591 |
foobucket = FooBucket('bucket1', [foo1]) |
| 3592 |
foofile = FooFile(buckets=[foobucket]) |
| 3593 |
|
| 3594 |
with HDF5IO(self.path, manager=self.manager, mode='w') as io: |
| 3595 |
io.write(foofile) |
| 3596 |
|
| 3597 |
with HDF5IO(self.path, manager=self.manager, mode='r') as io: |
| 3598 |
read_foofile = io.read() |
| 3599 |
self.assertListEqual(foofile.buckets['bucket1'].foos['foo1'].my_data[:].tolist(), |
| 3600 |
read_foofile.buckets['bucket1'].foos['foo1'].my_data[:].tolist()) |
| 3601 |
|
| 3602 |
def test_roundtrip_empty_dataset(self): |
| 3603 |
zarr.save(self.zarr_path, np.asarray([]).astype('int64')) |
| 3604 |
zarr_data = zarr.open(self.zarr_path, 'r') |
| 3605 |
foo1 = Foo('foo1', zarr_data, "I am foo1", 17, 3.14) |
| 3606 |
foobucket = FooBucket('bucket1', [foo1]) |
| 3607 |
foofile = FooFile(buckets=[foobucket]) |
| 3608 |
|
| 3609 |
with HDF5IO(self.path, manager=self.manager, mode='w') as io: |
| 3610 |
io.write(foofile) |
| 3611 |
|
| 3612 |
with HDF5IO(self.path, manager=self.manager, mode='r') as io: |
| 3613 |
read_foofile = io.read() |
| 3614 |
self.assertListEqual([], read_foofile.buckets['bucket1'].foos['foo1'].my_data[:].tolist()) |
| 3615 |
|
| 3616 |
def test_write_zarr_int32_dataset(self): |
| 3617 |
base_data = np.arange(50).reshape(5, 10).astype('int32') |
| 3618 |
zarr.save(self.zarr_path, base_data) |
| 3619 |
zarr_data = zarr.open(self.zarr_path, 'r') |
| 3620 |
io = HDF5IO(self.path, mode='a') |
| 3621 |
f = io._file |
| 3622 |
io.write_dataset(f, DatasetBuilder(name='test_dataset', data=zarr_data, attributes={})) |
| 3623 |
dset = f['test_dataset'] |
| 3624 |
self.assertTupleEqual(dset.shape, base_data.shape) |
| 3625 |
self.assertEqual(dset.dtype, base_data.dtype) |
| 3626 |
self.assertEqual(base_data.dtype, dset.dtype) |
| 3627 |
self.assertListEqual(dset[:].tolist(), |
| 3628 |
base_data.tolist()) |
| 3629 |
|
| 3630 |
def test_write_zarr_float32_dataset(self): |
| 3631 |
base_data = np.arange(50).reshape(5, 10).astype('float32') |
| 3632 |
zarr.save(self.zarr_path, base_data) |
| 3633 |
zarr_data = zarr.open(self.zarr_path, 'r') |
| 3634 |
io = HDF5IO(self.path, mode='a') |
| 3635 |
f = io._file |
| 3636 |
io.write_dataset(f, DatasetBuilder(name='test_dataset', data=zarr_data, attributes={})) |
| 3637 |
dset = f['test_dataset'] |
| 3638 |
self.assertTupleEqual(dset.shape, base_data.shape) |
| 3639 |
self.assertEqual(dset.dtype, base_data.dtype) |
| 3640 |
self.assertEqual(base_data.dtype, dset.dtype) |
| 3641 |
self.assertListEqual(dset[:].tolist(), |
| 3642 |
base_data.tolist()) |
| 3643 |
|
| 3644 |
def test_write_zarr_string_dataset(self): |
| 3645 |
base_data = np.array(['string1', 'string2'], dtype=str) |
| 3646 |
zarr.save(self.zarr_path, base_data) |
| 3647 |
zarr_data = zarr.open(self.zarr_path, 'r') |
| 3648 |
io = HDF5IO(self.path, mode='a') |
| 3649 |
f = io._file |
| 3650 |
io.write_dataset(f, DatasetBuilder('test_dataset', zarr_data, attributes={})) |
| 3651 |
dset = f['test_dataset'] |
| 3652 |
self.assertTupleEqual(dset.shape, (2,)) |
| 3653 |
self.assertListEqual(dset[:].astype(bytes).tolist(), base_data.astype(bytes).tolist()) |
| 3654 |
|
| 3655 |
def test_write_zarr_dataset_compress_gzip(self): |
| 3656 |
base_data = np.arange(50).reshape(5, 10).astype('float32') |
| 3657 |
zarr.save(self.zarr_path, base_data) |
| 3658 |
zarr_data = zarr.open(self.zarr_path, 'r') |
| 3659 |
a = H5DataIO(zarr_data, |
| 3660 |
compression='gzip', |
| 3661 |
compression_opts=5, |
| 3662 |
shuffle=True, |
| 3663 |
fletcher32=True) |
| 3664 |
io = HDF5IO(self.path, mode='a') |
| 3665 |
f = io._file |
| 3666 |
io.write_dataset(f, DatasetBuilder('test_dataset', a, attributes={})) |
| 3667 |
dset = f['test_dataset'] |
| 3668 |
self.assertTrue(np.all(dset[:] == a.data)) |
| 3669 |
self.assertEqual(dset.compression, 'gzip') |
| 3670 |
self.assertEqual(dset.compression_opts, 5) |
| 3671 |
self.assertEqual(dset.shuffle, True) |
| 3672 |
self.assertEqual(dset.fletcher32, True) |
| 3673 |
|
| 3674 |
|
| 3675 |
class HDF5IOEmptyDataset(TestCase): |
| 3676 |
""" Test if file does not exist, write in mode (w, w-, x, a) is ok """ |
| 3677 |
|
| 3678 |
def setUp(self): |
| 3679 |
self.manager = get_foo_buildmanager() |
| 3680 |
self.path = get_temp_filepath() |
| 3681 |
self.path2 = get_temp_filepath() |
| 3682 |
|
| 3683 |
def tearDown(self): |
| 3684 |
if os.path.exists(self.path): |
| 3685 |
os.remove(self.path) |
| 3686 |
if os.path.exists(self.path2): |
| 3687 |
os.remove(self.path2) |
| 3688 |
|
| 3689 |
def test_write_empty_dataset(self): |
| 3690 |
dataio = H5DataIO(shape=(5,), dtype=int) |
| 3691 |
foo = Foo('foo1', dataio, "I am foo1", 17, 3.14) |
| 3692 |
bucket = FooBucket('bucket1', [foo]) |
| 3693 |
foofile = FooFile(buckets=[bucket]) |
| 3694 |
|
| 3695 |
with HDF5IO(self.path, manager=self.manager, mode='w') as io: |
| 3696 |
io.write(foofile) |
| 3697 |
|
| 3698 |
self.assertIs(foo.my_data, dataio) |
| 3699 |
self.assertIsNotNone(foo.my_data.dataset) |
| 3700 |
self.assertIsInstance(foo.my_data.dataset, h5py.Dataset) |
| 3701 |
np.testing.assert_array_equal(foo.my_data.dataset, np.zeros(5, dtype=int)) |
| 3702 |
|
| 3703 |
def test_overwrite_dataset(self): |
| 3704 |
dataio = H5DataIO(shape=(5,), dtype=int) |
| 3705 |
foo = Foo('foo1', dataio, "I am foo1", 17, 3.14) |
| 3706 |
bucket = FooBucket('bucket1', [foo]) |
| 3707 |
foofile = FooFile(buckets=[bucket]) |
| 3708 |
|
| 3709 |
with HDF5IO(self.path, manager=self.manager, mode='w') as io: |
| 3710 |
io.write(foofile) |
| 3711 |
|
| 3712 |
with self.assertRaisesRegex(ValueError, 'Cannot overwrite H5DataIO.dataset'): |
| 3713 |
with HDF5IO(self.path2, manager=self.manager, mode='w') as io: |
| 3714 |
io.write(foofile) |
| 3715 |
|
| 3716 |
|
| 3717 |
class HDF5IOClassmethodTests(TestCase): |
| 3718 |
|
| 3719 |
def setUp(self): |
| 3720 |
self.path = get_temp_filepath() |
| 3721 |
self.f = h5py.File(self.path, 'w') |
| 3722 |
|
| 3723 |
def tearDown(self): |
| 3724 |
self.f.close() |
| 3725 |
if os.path.exists(self.path): |
| 3726 |
os.remove(self.path) |
| 3727 |
|
| 3728 |
def test_setup_empty_dset(self): |
| 3729 |
dset = HDF5IO.__setup_empty_dset__(self.f, 'foo', {'shape': (3, 3), 'dtype': 'float'}) |
| 3730 |
self.assertEqual(dset.name, '/foo') |
| 3731 |
self.assertTupleEqual(dset.shape, (3, 3)) |
| 3732 |
self.assertIs(dset.dtype.type, np.float32) |
| 3733 |
|
| 3734 |
def test_setup_empty_dset_req_args(self): |
| 3735 |
with self.assertRaisesRegex(ValueError, 'Cannot setup empty dataset /foo without dtype'): |
| 3736 |
HDF5IO.__setup_empty_dset__(self.f, 'foo', {'shape': (3, 3)}) |
| 3737 |
|
| 3738 |
with self.assertRaisesRegex(ValueError, 'Cannot setup empty dataset /foo without shape'): |
| 3739 |
HDF5IO.__setup_empty_dset__(self.f, 'foo', {'dtype': np.float32}) |
| 3740 |
|
| 3741 |
def test_setup_empty_dset_create_exception(self): |
| 3742 |
HDF5IO.__setup_empty_dset__(self.f, 'foo', {'shape': (3, 3), 'dtype': 'float'}) |
| 3743 |
with self.assertRaisesRegex(Exception, "Could not create dataset foo in /"): |
| 3744 |
HDF5IO.__setup_empty_dset__(self.f, 'foo', {'shape': (3, 3), 'dtype': 'float'}) |
| 3745 |
|
| 3746 |
|
| 3747 |
class H5DataIOTests(TestCase): |
| 3748 |
|
| 3749 |
def _bad_arg_cm(self): |
| 3750 |
return self.assertRaisesRegex(ValueError, "Must specify 'dtype' and 'shape' " |
| 3751 |
"if not specifying 'data'") |
| 3752 |
|
| 3753 |
def test_dataio_bad_args(self): |
| 3754 |
with self._bad_arg_cm(): |
| 3755 |
H5DataIO(shape=(10, 10)) |
| 3756 |
with self._bad_arg_cm(): |
| 3757 |
H5DataIO(dtype=int) |
| 3758 |
with self.assertWarnsRegex(UserWarning, "Argument 'dtype' is ignored when 'data' is specified"): |
| 3759 |
H5DataIO(data=np.zeros((10, 10)), dtype=int) |
| 3760 |
with self.assertWarnsRegex(UserWarning, "Argument 'shape' is ignored when 'data' is specified"): |
| 3761 |
H5DataIO(data=np.zeros((10, 10)), shape=(10, 10)) |
| 3762 |
|
| 3763 |
def test_dataio_len(self): |
| 3764 |
dataio = H5DataIO(shape=(10, 10), dtype=int) |
| 3765 |
self.assertEqual(len(dataio), 10) |
| 3766 |
|
| 3767 |
def test_dataio_shape_then_data(self): |
| 3768 |
dataio = H5DataIO(shape=(10, 10), dtype=int) |
| 3769 |
with self.assertRaisesRegex(ValueError, "Setting data when dtype and shape are not None is not supported"): |
| 3770 |
dataio.data = list() |
| 3771 |
|
| 3772 |
def test_dataio_maxshape(self): |
| 3773 |
dataio = H5DataIO(data=np.arange(10), maxshape=(None,)) |
| 3774 |
self.assertEqual(dataio.maxshape, (None,)) |
| 3775 |
|
| 3776 |
def test_dataio_maxshape_from_data(self): |
| 3777 |
dataio = H5DataIO(data=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) |
| 3778 |
self.assertEqual(dataio.maxshape, (10,)) |
| 3779 |
|
| 3780 |
|
| 3781 |
def test_hdf5io_can_read(): |
| 3782 |
assert not HDF5IO.can_read("not_a_file") |
| 3783 |
assert HDF5IO.can_read("tests/unit/back_compat_tests/1.0.5.h5") |
| 3784 |
assert not HDF5IO.can_read(__file__) # this file is not an HDF5 file |
| 3785 |
|
| 3786 |
|
| 3787 |
class TestContainerSetDataIO(TestCase): |
| 3788 |
|
| 3789 |
def setUp(self) -> None: |
| 3790 |
class ContainerWithData(Container): |
| 3791 |
__fields__ = ('data1', 'data2') |
| 3792 |
|
| 3793 |
@docval( |
| 3794 |
{"name": "name", "doc": "name", "type": str}, |
| 3795 |
{'name': 'data1', 'doc': 'field1 doc', 'type': list}, |
| 3796 |
{'name': 'data2', 'doc': 'field2 doc', 'type': list, 'default': None} |
| 3797 |
) |
| 3798 |
def __init__(self, **kwargs): |
| 3799 |
super().__init__(name=kwargs["name"]) |
| 3800 |
self.data1 = kwargs["data1"] |
| 3801 |
self.data2 = kwargs["data2"] |
| 3802 |
|
| 3803 |
self.obj = ContainerWithData("name", [1, 2, 3, 4, 5], None) |
| 3804 |
self.file_path = get_temp_filepath() |
| 3805 |
|
| 3806 |
def tearDown(self): |
| 3807 |
if os.path.exists(self.file_path): |
| 3808 |
os.remove(self.file_path) |
| 3809 |
|
| 3810 |
def test_set_data_io(self): |
| 3811 |
self.obj.set_data_io("data1", H5DataIO, data_io_kwargs=dict(chunks=True)) |
| 3812 |
assert isinstance(self.obj.data1, H5DataIO) |
| 3813 |
assert self.obj.data1.io_settings["chunks"] |
| 3814 |
|
| 3815 |
def test_fail_set_data_io(self): |
| 3816 |
"""Attempt to set a DataIO for a dataset that is missing.""" |
| 3817 |
with self.assertRaisesWith(ValueError, "data2 is None and cannot be wrapped in a DataIO class"): |
| 3818 |
self.obj.set_data_io("data2", H5DataIO, data_io_kwargs=dict(chunks=True)) |
| 3819 |
|
| 3820 |
def test_set_data_io_old_api(self): |
| 3821 |
"""Test that using the kwargs still works but throws a warning.""" |
| 3822 |
msg = ( |
| 3823 |
"Use of **kwargs in Container.set_data_io() is deprecated. Please pass the DataIO kwargs as a dictionary to" |
| 3824 |
" the `data_io_kwargs` parameter instead." |
| 3825 |
) |
| 3826 |
with self.assertWarnsWith(DeprecationWarning, msg): |
| 3827 |
self.obj.set_data_io("data1", H5DataIO, chunks=True) |
| 3828 |
self.assertIsInstance(self.obj.data1, H5DataIO) |
| 3829 |
self.assertTrue(self.obj.data1.io_settings["chunks"]) |
| 3830 |
|
| 3831 |
def test_set_data_io_h5py_dataset(self): |
| 3832 |
file = File(self.file_path, 'w') |
| 3833 |
data = file.create_dataset('data', data=[1, 2, 3, 4, 5], chunks=(3,)) |
| 3834 |
class ContainerWithData(Container): |
| 3835 |
__fields__ = ('data',) |
| 3836 |
|
| 3837 |
@docval( |
| 3838 |
{"name": "name", "doc": "name", "type": str}, |
| 3839 |
{'name': 'data', 'doc': 'field1 doc', 'type': h5py.Dataset}, |
| 3840 |
) |
| 3841 |
def __init__(self, **kwargs): |
| 3842 |
super().__init__(name=kwargs["name"]) |
| 3843 |
self.data = kwargs["data"] |
| 3844 |
|
| 3845 |
container = ContainerWithData("name", data) |
| 3846 |
container.set_data_io( |
| 3847 |
"data", |
| 3848 |
H5DataIO, |
| 3849 |
data_io_kwargs=dict(chunks=(2,)), |
| 3850 |
data_chunk_iterator_class=DataChunkIterator, |
| 3851 |
) |
| 3852 |
|
| 3853 |
self.assertIsInstance(container.data, H5DataIO) |
| 3854 |
self.assertEqual(container.data.io_settings["chunks"], (2,)) |
| 3855 |
file.close() |
| 3856 |
|
| 3857 |
class TestDataSetDataIO(TestCase): |
| 3858 |
|
| 3859 |
def setUp(self): |
| 3860 |
class MyData(Data): |
| 3861 |
pass |
| 3862 |
|
| 3863 |
self.data = MyData("my_data", [1, 2, 3]) |
| 3864 |
self.file_path = get_temp_filepath() |
| 3865 |
|
| 3866 |
def tearDown(self): |
| 3867 |
if os.path.exists(self.file_path): |
| 3868 |
os.remove(self.file_path) |
| 3869 |
|
| 3870 |
def test_set_data_io(self): |
| 3871 |
self.data.set_data_io(H5DataIO, dict(chunks=True)) |
| 3872 |
assert isinstance(self.data.data, H5DataIO) |
| 3873 |
assert self.data.data.io_settings["chunks"] |
| 3874 |
|
| 3875 |
def test_set_data_io_h5py_dataset(self): |
| 3876 |
file = File(self.file_path, 'w') |
| 3877 |
data = file.create_dataset('data', data=[1, 2, 3, 4, 5], chunks=(3,)) |
| 3878 |
class MyData(Data): |
| 3879 |
pass |
| 3880 |
|
| 3881 |
my_data = MyData("my_data", data) |
| 3882 |
my_data.set_data_io( |
| 3883 |
H5DataIO, |
| 3884 |
data_io_kwargs=dict(chunks=(2,)), |
| 3885 |
data_chunk_iterator_class=DataChunkIterator, |
| 3886 |
) |
| 3887 |
|
| 3888 |
self.assertIsInstance(my_data.data, H5DataIO) |
| 3889 |
self.assertEqual(my_data.data.io_settings["chunks"], (2,)) |
| 3890 |
file.close() |