File: test_migrate_v3.py

package info (click to toggle)
zarr 3.1.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,068 kB
  • sloc: python: 31,589; makefile: 10
file content (666 lines) | stat: -rw-r--r-- 23,188 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
import lzma
from pathlib import Path
from typing import Literal, cast

import numcodecs
import numcodecs.abc
import numpy as np
import pytest

import zarr
from tests.test_cli.conftest import create_nested_zarr
from zarr.abc.codec import Codec
from zarr.codecs.blosc import BloscCodec
from zarr.codecs.bytes import BytesCodec
from zarr.codecs.gzip import GzipCodec
from zarr.codecs.numcodecs import LZMA, Delta
from zarr.codecs.transpose import TransposeCodec
from zarr.codecs.zstd import ZstdCodec
from zarr.core.chunk_grids import RegularChunkGrid
from zarr.core.chunk_key_encodings import V2ChunkKeyEncoding
from zarr.core.common import JSON, ZarrFormat
from zarr.core.dtype.npy.int import UInt8, UInt16
from zarr.core.group import Group, GroupMetadata
from zarr.core.metadata.v3 import ArrayV3Metadata
from zarr.storage._local import LocalStore
from zarr.types import AnyArray

typer_testing = pytest.importorskip(
    "typer.testing", reason="optional cli dependencies aren't installed"
)
cli = pytest.importorskip("zarr._cli.cli", reason="optional cli dependencies aren't installed")

runner = typer_testing.CliRunner()

NUMCODECS_USER_WARNING = "Numcodecs codecs are not in the Zarr version 3 specification and may not be supported by other zarr implementations."


def test_migrate_array(local_store: LocalStore) -> None:
    shape = (10, 10)
    chunks = (10, 10)
    dtype = "uint16"
    compressors = numcodecs.Blosc(cname="zstd", clevel=3, shuffle=1)
    fill_value = 2
    attributes = cast(dict[str, JSON], {"baz": 42, "qux": [1, 4, 7, 12]})

    zarr.create_array(
        store=local_store,
        shape=shape,
        chunks=chunks,
        dtype=dtype,
        compressors=compressors,
        zarr_format=2,
        fill_value=fill_value,
        attributes=attributes,
    )

    result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)])
    assert result.exit_code == 0
    assert (local_store.root / "zarr.json").exists()

    zarr_array = zarr.open(local_store.root, zarr_format=3)

    expected_metadata = ArrayV3Metadata(
        shape=shape,
        data_type=UInt16(endianness="little"),
        chunk_grid=RegularChunkGrid(chunk_shape=chunks),
        chunk_key_encoding=V2ChunkKeyEncoding(separator="."),
        fill_value=fill_value,
        codecs=(
            BytesCodec(endian="little"),
            BloscCodec(typesize=2, cname="zstd", clevel=3, shuffle="shuffle", blocksize=0),
        ),
        attributes=attributes,
        dimension_names=None,
        storage_transformers=None,
    )
    assert zarr_array.metadata == expected_metadata


def test_migrate_group(local_store: LocalStore) -> None:
    attributes = {"baz": 42, "qux": [1, 4, 7, 12]}
    zarr.create_group(store=local_store, zarr_format=2, attributes=attributes)

    result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)])
    assert result.exit_code == 0
    assert (local_store.root / "zarr.json").exists()

    zarr_array = zarr.open(local_store.root, zarr_format=3)
    expected_metadata = GroupMetadata(
        attributes=attributes, zarr_format=3, consolidated_metadata=None
    )
    assert zarr_array.metadata == expected_metadata


@pytest.mark.parametrize("separator", [".", "/"])
def test_migrate_nested_groups_and_arrays_in_place(
    local_store: LocalStore, separator: str, expected_v3_metadata: list[Path]
) -> None:
    """Test that zarr.json are made at the correct points in a hierarchy of groups and arrays
    (including when there are additional dirs due to using a / separator)"""

    attributes = {"baz": 42, "qux": [1, 4, 7, 12]}
    paths = create_nested_zarr(local_store, attributes=attributes, separator=separator)

    result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)])
    assert result.exit_code == 0

    zarr_json_paths = sorted(local_store.root.rglob("zarr.json"))
    expected_zarr_json_paths = [local_store.root / p for p in expected_v3_metadata]
    assert zarr_json_paths == expected_zarr_json_paths

    # Check converted zarr can be opened + metadata accessed at all levels
    zarr_array = zarr.open(local_store.root, zarr_format=3)
    for path in paths:
        zarr_v3 = cast(AnyArray | Group, zarr_array[path])
        metadata = zarr_v3.metadata
        assert metadata.zarr_format == 3
        assert metadata.attributes == attributes


@pytest.mark.parametrize("separator", [".", "/"])
async def test_migrate_nested_groups_and_arrays_separate_location(
    tmp_path: Path,
    separator: str,
    expected_v2_metadata: list[Path],
    expected_v3_metadata: list[Path],
) -> None:
    """Test that zarr.json are made at the correct paths, when saving to a separate output location."""

    input_zarr_path = tmp_path / "input.zarr"
    output_zarr_path = tmp_path / "output.zarr"

    local_store = await LocalStore.open(str(input_zarr_path))
    create_nested_zarr(local_store, separator=separator)

    result = runner.invoke(cli.app, ["migrate", "v3", str(input_zarr_path), str(output_zarr_path)])
    assert result.exit_code == 0

    # Files in input zarr should be unchanged i.e. still v2 only
    zarr_json_paths = sorted(input_zarr_path.rglob("zarr.json"))
    assert len(zarr_json_paths) == 0

    paths = [
        path
        for path in input_zarr_path.rglob("*")
        if path.stem in [".zarray", ".zgroup", ".zattrs"]
    ]
    expected_paths = [input_zarr_path / p for p in expected_v2_metadata]
    assert sorted(paths) == expected_paths

    # Files in output zarr should only contain v3 metadata
    zarr_json_paths = sorted(output_zarr_path.rglob("zarr.json"))
    expected_zarr_json_paths = [output_zarr_path / p for p in expected_v3_metadata]
    assert zarr_json_paths == expected_zarr_json_paths


def test_remove_v2_metadata_option_in_place(
    local_store: LocalStore, expected_paths_v3_metadata: list[Path]
) -> None:
    create_nested_zarr(local_store)

    # convert v2 metadata to v3, then remove v2 metadata
    result = runner.invoke(
        cli.app, ["migrate", "v3", str(local_store.root), "--remove-v2-metadata"]
    )
    assert result.exit_code == 0

    paths = sorted(local_store.root.rglob("*"))
    expected_paths = [local_store.root / p for p in expected_paths_v3_metadata]
    assert paths == expected_paths


async def test_remove_v2_metadata_option_separate_location(
    tmp_path: Path,
    expected_paths_v2_metadata: list[Path],
    expected_paths_v3_metadata_no_chunks: list[Path],
) -> None:
    """Check that when using --remove-v2-metadata with a separate output location, no v2 metadata is removed from
    the input location."""

    input_zarr_path = tmp_path / "input.zarr"
    output_zarr_path = tmp_path / "output.zarr"

    local_store = await LocalStore.open(str(input_zarr_path))
    create_nested_zarr(local_store)

    result = runner.invoke(
        cli.app,
        ["migrate", "v3", str(input_zarr_path), str(output_zarr_path), "--remove-v2-metadata"],
    )
    assert result.exit_code == 0

    # input image should be unchanged
    paths = sorted(input_zarr_path.rglob("*"))
    expected_paths = [input_zarr_path / p for p in expected_paths_v2_metadata]
    assert paths == expected_paths

    # output image should be only v3 metadata
    paths = sorted(output_zarr_path.rglob("*"))
    expected_paths = [output_zarr_path / p for p in expected_paths_v3_metadata_no_chunks]
    assert paths == expected_paths


def test_overwrite_option_in_place(
    local_store: LocalStore, expected_paths_v2_v3_metadata: list[Path]
) -> None:
    create_nested_zarr(local_store)

    # add v3 metadata in place
    result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)])
    assert result.exit_code == 0

    # check that v3 metadata can be overwritten with --overwrite
    result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root), "--overwrite"])
    assert result.exit_code == 0

    paths = sorted(local_store.root.rglob("*"))
    expected_paths = [local_store.root / p for p in expected_paths_v2_v3_metadata]
    assert paths == expected_paths


async def test_overwrite_option_separate_location(
    tmp_path: Path,
    expected_paths_v2_metadata: list[Path],
    expected_paths_v3_metadata_no_chunks: list[Path],
) -> None:
    input_zarr_path = tmp_path / "input.zarr"
    output_zarr_path = tmp_path / "output.zarr"

    local_store = await LocalStore.open(str(input_zarr_path))
    create_nested_zarr(local_store)

    # create v3 metadata at output_zarr_path
    result = runner.invoke(
        cli.app,
        ["migrate", "v3", str(input_zarr_path), str(output_zarr_path)],
    )
    assert result.exit_code == 0

    # re-run with --overwrite option
    result = runner.invoke(
        cli.app,
        ["migrate", "v3", str(input_zarr_path), str(output_zarr_path), "--overwrite", "--force"],
    )
    assert result.exit_code == 0

    # original image should be un-changed
    paths = sorted(input_zarr_path.rglob("*"))
    expected_paths = [input_zarr_path / p for p in expected_paths_v2_metadata]
    assert paths == expected_paths

    # output image is only v3 metadata
    paths = sorted(output_zarr_path.rglob("*"))
    expected_paths = [output_zarr_path / p for p in expected_paths_v3_metadata_no_chunks]
    assert paths == expected_paths


@pytest.mark.parametrize("separator", [".", "/"])
def test_migrate_sub_group(
    local_store: LocalStore, separator: str, expected_v3_metadata: list[Path]
) -> None:
    """Test that only arrays/groups within group_1 are converted (+ no other files in store)"""

    create_nested_zarr(local_store, separator=separator)
    group_path = local_store.root / "group_1"

    result = runner.invoke(cli.app, ["migrate", "v3", str(group_path)])
    assert result.exit_code == 0

    zarr_json_paths = sorted(local_store.root.rglob("zarr.json"))
    expected_zarr_json_paths = [
        local_store.root / p
        for p in expected_v3_metadata
        if group_path in (local_store.root / p).parents
    ]
    assert zarr_json_paths == expected_zarr_json_paths


@pytest.mark.parametrize(
    ("compressor_v2", "compressor_v3"),
    [
        (
            numcodecs.Blosc(cname="zstd", clevel=3, shuffle=1),
            BloscCodec(typesize=2, cname="zstd", clevel=3, shuffle="shuffle", blocksize=0),
        ),
        (numcodecs.Zstd(level=3), ZstdCodec(level=3)),
        (numcodecs.GZip(level=3), GzipCodec(level=3)),
    ],
    ids=["blosc", "zstd", "gzip"],
)
def test_migrate_compressor(
    local_store: LocalStore, compressor_v2: numcodecs.abc.Codec, compressor_v3: Codec
) -> None:
    zarr_array = zarr.create_array(
        store=local_store,
        shape=(10, 10),
        chunks=(10, 10),
        dtype="uint16",
        compressors=compressor_v2,
        zarr_format=2,
        fill_value=0,
    )
    zarr_array[:] = 1

    result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)])
    assert result.exit_code == 0
    assert (local_store.root / "zarr.json").exists()

    zarr_array = zarr.open_array(local_store.root, zarr_format=3)
    metadata = zarr_array.metadata
    assert metadata.zarr_format == 3
    assert metadata.codecs == (
        BytesCodec(endian="little"),
        compressor_v3,
    )
    assert np.all(zarr_array[:] == 1)


@pytest.mark.filterwarnings(f"ignore:{NUMCODECS_USER_WARNING}:UserWarning")
def test_migrate_numcodecs_compressor(local_store: LocalStore) -> None:
    """Test migration of a numcodecs compressor without a zarr.codecs equivalent."""

    lzma_settings = {
        "format": lzma.FORMAT_RAW,
        "check": -1,
        "preset": None,
        "filters": [
            {"id": lzma.FILTER_DELTA, "dist": 4},
            {"id": lzma.FILTER_LZMA2, "preset": 1},
        ],
    }

    zarr_array = zarr.create_array(
        store=local_store,
        shape=(10, 10),
        chunks=(10, 10),
        dtype="uint16",
        compressors=numcodecs.LZMA.from_config(lzma_settings),
        zarr_format=2,
        fill_value=0,
    )
    zarr_array[:] = 1

    result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)])
    assert result.exit_code == 0
    assert (local_store.root / "zarr.json").exists()

    zarr_array = zarr.open_array(local_store.root, zarr_format=3)
    metadata = zarr_array.metadata
    assert metadata.zarr_format == 3
    assert metadata.codecs == (
        BytesCodec(endian="little"),
        LZMA(
            format=lzma_settings["format"],
            check=lzma_settings["check"],
            preset=lzma_settings["preset"],
            filters=lzma_settings["filters"],
        ),
    )
    assert np.all(zarr_array[:] == 1)


@pytest.mark.filterwarnings(f"ignore:{NUMCODECS_USER_WARNING}:UserWarning")
def test_migrate_filter(local_store: LocalStore) -> None:
    filter_v2 = numcodecs.Delta(dtype="<u2", astype="<u2")
    filter_v3 = Delta(dtype="<u2", astype="<u2")

    zarr.create_array(
        store=local_store,
        shape=(10, 10),
        chunks=(10, 10),
        dtype="uint16",
        compressors=None,
        filters=filter_v2,
        zarr_format=2,
        fill_value=0,
    )

    result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)])
    assert result.exit_code == 0
    assert (local_store.root / "zarr.json").exists()

    zarr_array = zarr.open_array(local_store.root, zarr_format=3)
    metadata = zarr_array.metadata
    assert metadata.zarr_format == 3
    assert metadata.codecs == (
        filter_v3,
        BytesCodec(endian="little"),
    )


@pytest.mark.parametrize(
    ("order", "expected_codecs"),
    [
        ("C", (BytesCodec(endian="little"),)),
        ("F", (TransposeCodec(order=(1, 0)), BytesCodec(endian="little"))),
    ],
)
def test_migrate_C_vs_F_order(
    local_store: LocalStore, order: Literal["C", "F"], expected_codecs: tuple[Codec]
) -> None:
    zarr_array = zarr.create_array(
        store=local_store,
        shape=(10, 10),
        chunks=(10, 10),
        dtype="uint16",
        compressors=None,
        zarr_format=2,
        fill_value=0,
        order=order,
    )
    zarr_array[:] = 1

    result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)])
    assert result.exit_code == 0
    assert (local_store.root / "zarr.json").exists()

    zarr_array = zarr.open_array(local_store.root, zarr_format=3)
    metadata = zarr_array.metadata
    assert metadata.zarr_format == 3
    assert metadata.codecs == expected_codecs
    assert np.all(zarr_array[:] == 1)


@pytest.mark.parametrize(
    ("dtype", "expected_data_type", "expected_codecs"),
    [
        ("uint8", UInt8(), (BytesCodec(endian=None),)),
        ("uint16", UInt16(), (BytesCodec(endian="little"),)),
    ],
    ids=["single_byte", "multi_byte"],
)
def test_migrate_endian(
    local_store: LocalStore,
    dtype: str,
    expected_data_type: UInt8 | UInt16,
    expected_codecs: tuple[Codec],
) -> None:
    zarr_array = zarr.create_array(
        store=local_store,
        shape=(10, 10),
        chunks=(10, 10),
        dtype=dtype,
        compressors=None,
        zarr_format=2,
        fill_value=0,
    )
    zarr_array[:] = 1

    result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)])
    assert result.exit_code == 0
    assert (local_store.root / "zarr.json").exists()

    zarr_array = zarr.open_array(local_store.root, zarr_format=3)
    metadata = zarr_array.metadata
    assert metadata.zarr_format == 3
    assert metadata.data_type == expected_data_type
    assert metadata.codecs == expected_codecs
    assert np.all(zarr_array[:] == 1)


@pytest.mark.parametrize("node_type", ["array", "group"])
def test_migrate_v3(local_store: LocalStore, node_type: str) -> None:
    """Attempting to convert a v3 array/group should always fail"""

    if node_type == "array":
        zarr.create_array(
            store=local_store, shape=(10, 10), chunks=(10, 10), zarr_format=3, dtype="uint16"
        )
    else:
        zarr.create_group(store=local_store, zarr_format=3)

    result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)])
    assert result.exit_code == 1
    assert isinstance(result.exception, TypeError)
    assert str(result.exception) == "Only arrays / groups with zarr v2 metadata can be converted"


def test_migrate_consolidated_metadata(local_store: LocalStore) -> None:
    """Attempting to convert a group with consolidated metadata should always fail"""

    group = zarr.create_group(store=local_store, zarr_format=2)
    group.create_array(shape=(1,), name="a", dtype="uint8")
    zarr.consolidate_metadata(local_store)

    result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)])
    assert result.exit_code == 1
    assert isinstance(result.exception, NotImplementedError)
    assert str(result.exception) == "Migration of consolidated metadata isn't supported."


def test_migrate_unknown_codec(local_store: LocalStore) -> None:
    """Attempting to convert a codec without a v3 equivalent should always fail"""

    zarr.create_array(
        store=local_store,
        shape=(10, 10),
        chunks=(10, 10),
        dtype="uint16",
        filters=[numcodecs.Categorize(labels=["a", "b"], dtype=object)],
        zarr_format=2,
        fill_value=0,
    )

    result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)])
    assert result.exit_code == 1
    assert isinstance(result.exception, ValueError)
    assert (
        str(result.exception)
        == "Couldn't find corresponding zarr.codecs.numcodecs codec for categorize"
    )


def test_migrate_incorrect_filter(local_store: LocalStore) -> None:
    """Attempting to convert a filter (which is the wrong type of codec) should always fail"""

    zarr.create_array(
        store=local_store,
        shape=(10, 10),
        chunks=(10, 10),
        dtype="uint16",
        filters=[numcodecs.Zstd(level=3)],
        zarr_format=2,
        fill_value=0,
    )

    with pytest.warns(UserWarning, match=NUMCODECS_USER_WARNING):
        result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)])

    assert result.exit_code == 1
    assert isinstance(result.exception, TypeError)
    assert (
        str(result.exception)
        == "Filter <class 'zarr.codecs.numcodecs._codecs.Zstd'> is not an ArrayArrayCodec"
    )


def test_migrate_incorrect_compressor(local_store: LocalStore) -> None:
    """Attempting to convert a compressor (which is the wrong type of codec) should always fail"""

    zarr.create_array(
        store=local_store,
        shape=(10, 10),
        chunks=(10, 10),
        dtype="uint16",
        compressors=numcodecs.Delta(dtype="<u2", astype="<u2"),
        zarr_format=2,
        fill_value=0,
    )

    with pytest.warns(UserWarning, match=NUMCODECS_USER_WARNING):
        result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)])

    assert result.exit_code == 1
    assert isinstance(result.exception, TypeError)
    assert (
        str(result.exception)
        == "Compressor <class 'zarr.codecs.numcodecs._codecs.Delta'> is not a BytesBytesCodec"
    )


@pytest.mark.parametrize("zarr_format", [2, 3])
def test_remove_metadata_fails_without_force(
    local_store: LocalStore, zarr_format: ZarrFormat
) -> None:
    """Test removing metadata (when no alternate metadata is present) fails without --force."""

    create_nested_zarr(local_store, zarr_format=zarr_format)

    result = runner.invoke(cli.app, ["remove-metadata", f"v{zarr_format}", str(local_store.root)])
    assert result.exit_code == 1
    assert isinstance(result.exception, ValueError)
    assert str(result.exception).startswith(f"Cannot remove v{zarr_format} metadata at file")


@pytest.mark.parametrize("zarr_format", [2, 3])
def test_remove_metadata_succeeds_with_force(
    local_store: LocalStore, zarr_format: ZarrFormat, expected_paths_no_metadata: list[Path]
) -> None:
    """Test removing metadata (when no alternate metadata is present) succeeds with --force."""

    create_nested_zarr(local_store, zarr_format=zarr_format)

    result = runner.invoke(
        cli.app, ["remove-metadata", f"v{zarr_format}", str(local_store.root), "--force"]
    )
    assert result.exit_code == 0

    paths = sorted(local_store.root.rglob("*"))
    expected_paths = [local_store.root / p for p in expected_paths_no_metadata]
    assert paths == expected_paths


def test_remove_metadata_sub_group(
    local_store: LocalStore, expected_paths_no_metadata: list[Path]
) -> None:
    """Test only v2 metadata within group_1 is removed and rest remains un-changed."""

    create_nested_zarr(local_store)

    result = runner.invoke(
        cli.app, ["remove-metadata", "v2", str(local_store.root / "group_1"), "--force"]
    )
    assert result.exit_code == 0

    # check all metadata files inside group_1 are removed (.zattrs / .zgroup / .zarray should remain only inside the top
    # group)
    paths = sorted(local_store.root.rglob("*"))

    expected_paths = [local_store.root / p for p in expected_paths_no_metadata]
    expected_paths.append(local_store.root / ".zattrs")
    expected_paths.append(local_store.root / ".zgroup")
    expected_paths.append(local_store.root / "array_0" / ".zarray")
    expected_paths.append(local_store.root / "array_0" / ".zattrs")
    assert paths == sorted(expected_paths)


@pytest.mark.parametrize(
    ("zarr_format", "expected_output_paths"),
    [("v2", "expected_paths_v3_metadata"), ("v3", "expected_paths_v2_metadata")],
)
def test_remove_metadata_after_conversion(
    local_store: LocalStore,
    request: pytest.FixtureRequest,
    zarr_format: str,
    expected_output_paths: str,
) -> None:
    """Test all v2/v3 metadata can be removed after metadata conversion (all groups / arrays /
    metadata of other versions should remain as-is)"""

    create_nested_zarr(local_store)

    # convert v2 metadata to v3 (so now both v2 and v3 metadata present!), then remove either the v2 or v3 metadata
    result = runner.invoke(cli.app, ["migrate", "v3", str(local_store.root)])
    assert result.exit_code == 0
    result = runner.invoke(cli.app, ["remove-metadata", zarr_format, str(local_store.root)])
    assert result.exit_code == 0

    paths = sorted(local_store.root.rglob("*"))
    expected_paths = request.getfixturevalue(expected_output_paths)
    expected_paths = [local_store.root / p for p in expected_paths]
    assert paths == expected_paths


@pytest.mark.parametrize("cli_command", ["migrate", "remove-metadata"])
def test_dry_run(
    local_store: LocalStore, cli_command: str, expected_paths_v2_metadata: list[Path]
) -> None:
    """Test that all files are un-changed after a dry run"""

    create_nested_zarr(local_store)

    if cli_command == "migrate":
        result = runner.invoke(
            cli.app, ["migrate", "v3", str(local_store.root), "--overwrite", "--force", "--dry-run"]
        )
    else:
        result = runner.invoke(
            cli.app, ["remove-metadata", "v2", str(local_store.root), "--force", "--dry-run"]
        )

    assert result.exit_code == 0

    paths = sorted(local_store.root.rglob("*"))
    expected_paths = [local_store.root / p for p in expected_paths_v2_metadata]
    assert paths == expected_paths