|
| 1 | +from pathlib import Path |
| 2 | + |
| 3 | +import pytest |
| 4 | + |
| 5 | +import mrcfile |
| 6 | +import tifffile |
| 7 | +import zarr |
| 8 | +import numpy as np |
| 9 | +import os |
| 10 | + |
| 11 | +from zarrify.utils.dask_utils import initialize_dask_client |
| 12 | +from zarrify import to_zarr |
| 13 | + |
| 14 | +@pytest.fixture |
| 15 | +def create_test_file(tmp_path): |
| 16 | + """Factory fixture to create test files with specified format and dimensions""" |
| 17 | + def _create_file(ext: str, shape: tuple): |
| 18 | + data = np.random.rand(*shape).astype(np.uint8) |
| 19 | + file_path = tmp_path / f"test_image_{len(shape)}d.{ext}" |
| 20 | + |
| 21 | + if ext in ["tiff", "tif"]: |
| 22 | + tifffile.imwrite(file_path, data) |
| 23 | + elif ext == "mrc": |
| 24 | + with mrcfile.new(file_path, overwrite=True) as mrc: |
| 25 | + mrc.set_data(data.astype(data.dtype)) |
| 26 | + else: |
| 27 | + raise ValueError("Unsupported file format") |
| 28 | + |
| 29 | + return file_path, data |
| 30 | + return _create_file |
| 31 | + |
| 32 | +import itertools |
| 33 | + |
| 34 | +# Test parameters |
| 35 | +FORMATS = ['tif', 'tiff', 'mrc'] |
| 36 | +SHAPES = [(40, 50), (1, 30, 50)] # 2D and 3D |
| 37 | + |
| 38 | +@pytest.mark.parametrize("ext,shape", list(itertools.product(FORMATS, SHAPES))) |
| 39 | +def test_to_zarr(create_test_file, ext, shape): |
| 40 | + |
| 41 | + src_path, expected_data = create_test_file(ext, shape) |
| 42 | + dest_path = Path(f"{src_path.with_suffix('')}.zarr") |
| 43 | + |
| 44 | + dask_client = initialize_dask_client('local') |
| 45 | + |
| 46 | + # convert to zarr |
| 47 | + to_zarr(src_path, dest_path, dask_client) |
| 48 | + |
| 49 | + if src_path.suffix.lstrip('.') in ['tif', 'tiff']: |
| 50 | + src_data = tifffile.imread(src_path) |
| 51 | + elif src_path.suffix.lstrip('.') == 'mrc': |
| 52 | + with mrcfile.open(src_path, permissive=True) as mrc: |
| 53 | + src_data = mrc.data |
| 54 | + |
| 55 | + # store array in s0 by convention |
| 56 | + dest_data = zarr.open(f'{dest_path}/s0', mode='r') |
| 57 | + assert np.array_equal(dest_data[:], src_data) |
| 58 | + assert np.array_equal(dest_data[:], expected_data) |
| 59 | + |
0 commit comments