"""Checks for scripts/split_qc_figures.py. The split is only safe if the archives it produces, taken together, extract to exactly the tree the original archive extracted to. Everything here is built in a temporary directory; no repository archive is touched. Run: python scripts/test_split_qc_figures.py """ import filecmp import os import shutil import sys import tempfile import zipfile sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from split_qc_figures import is_figure_entry, plan_shards, split_one # noqa: E402 PASS = FAIL = 0 def check(cond, label, detail=""): global PASS, FAIL if cond: PASS += 1 print(f" ok {label}") else: FAIL += 1 print(f" FAIL {label} {detail}") def section(title): print(f"\n=== {title} ===") def build_archive(path, entries): with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z: for name, data in entries: z.writestr(name, data) def extract(zip_paths, dest): os.makedirs(dest, exist_ok=True) for p in zip_paths: with zipfile.ZipFile(p) as z: z.extractall(dest) return dest def tree(root): out = {} for dirpath, _, files in os.walk(root): for f in files: full = os.path.join(dirpath, f) out[os.path.relpath(full, root)] = os.path.getsize(full) return out # ---------------------------------------------------------------- 1. classifier section("1. the figure classifier matches directories, not lookalike names") for name in [ "X/Landmarks-fig/a.png", "X/Landmarks-Label1-fig-v1.4.0/a.png", "X/Landmarks-fig-w-projection/b.png", "X/X-subset/Landmarks-Label2-fig-v1.4.0/s.png", # deep nesting: BraTS24 / MSD "X/Landmarks-PSMA-Label1-fig-v1.2.0/c.png", ]: check(is_figure_entry(name), f"figure: {name}") for name in [ "X/Landmarks-Label1-v1.4.0/plan.json.gz", "X/config-notes.txt", # holds 'fig', lacks '-fig' "X/benchmark_plan_biometry_v1.4.0.json.gz", "X/figures.txt", # 'fig' at the start of a component, still not '-fig' "X/X-subset/Landmarks-Label2-v1.4.0/plan.json.gz", ]: check(not is_figure_entry(name), f"kept: {name}") # ------------------------------------------------------------------- 2. packing section("2. shard packing respects the byte ceiling") class FakeInfo: def __init__(self, size): self.compress_size = size shards = plan_shards([FakeInfo(30) for _ in range(10)], shard_bytes=100) check(all(sum(i.compress_size for i in s) <= 100 for s in shards), "no shard exceeds the ceiling") check(sum(len(s) for s in shards) == 10, "every entry is placed exactly once") oversized = plan_shards([FakeInfo(500)], shard_bytes=100) check(len(oversized) == 1 and len(oversized[0]) == 1, "an entry larger than the ceiling still ships") check(len(plan_shards([FakeInfo(10)], shard_bytes=100)) == 1, "a small set stays in one shard") # ------------------------------------- 3. round-trip: split then extract == original section("3. split archives re-extract to the original tree") tmp = tempfile.mkdtemp(prefix="qcfig-test-") try: entries = [ ("SYNTH/", b""), ("SYNTH/SYNTH-subset/", b""), ("SYNTH/SYNTH-subset/Landmarks-Label1-v1.4.0/plan.json.gz", b"KEEP" * 100), ("SYNTH/config-notes.txt", b"the substring fig appears here"), ("SYNTH/Landmarks-fig/a.png", os.urandom(50_000)), ("SYNTH/Landmarks-fig-w-projection/b.png", os.urandom(50_000)), ] + [ (f"SYNTH/SYNTH-subset/Landmarks-Label2-fig-v1.4.0/s{i}.png", os.urandom(40_000)) for i in range(20) ] src = os.path.join(tmp, "SYNTH.zip") build_archive(src, entries) reference = extract([src], os.path.join(tmp, "reference")) ref_tree = tree(reference) # A 100 KB ceiling against ~1 MB of figures forces real sharding. report = split_one(src, shard_bytes=100_000, dry_run=False) print(f" [{report.strip()}]") produced = sorted(f for f in os.listdir(tmp) if f.endswith(".zip")) shard_files = [f for f in produced if "_fig" in f] check(len(shard_files) > 1, "sharding actually happened", f"got {shard_files}") check( all(f.startswith("SYNTH_fig.part") for f in shard_files), "multi-shard sets use the partNN name", f"got {shard_files}", ) check( all(os.path.getsize(os.path.join(tmp, f)) <= 150_000 for f in shard_files), "each shard stays near the ceiling", ) # The dataset archive alone must carry no figures... with zipfile.ZipFile(src) as z: names = z.namelist() check(not any(is_figure_entry(n) for n in names), "dataset archive holds no figures") check( any(n.endswith("plan.json.gz") for n in names) and "SYNTH/config-notes.txt" in names, "dataset archive keeps the annotations", ) # ...and every shard must carry nothing but figures. for f in shard_files: with zipfile.ZipFile(os.path.join(tmp, f)) as z: check( all(is_figure_entry(n) for n in z.namelist()), f"{f} holds only figures", ) # The restore path MedVision.py uses: extractall the dataset archive, then # extractall every shard, into the same root. restored = extract( [src] + [os.path.join(tmp, f) for f in shard_files], os.path.join(tmp, "restored"), ) check(tree(restored) == ref_tree, "restored tree matches the original exactly") match, mismatch, errors = filecmp.cmpfiles( reference, restored, list(ref_tree), shallow=False ) check(not mismatch and not errors, "every file is byte-identical", f"{mismatch} {errors}") # Dataset-archive-only extraction is what a default user gets. default_only = extract([src], os.path.join(tmp, "default")) check( all(not is_figure_entry(p.replace(os.sep, "/")) for p in tree(default_only)), "a default download contains no figures", ) # ------------------------------------------------------- 4. idempotent re-run section("4. re-running is a no-op") again = split_one(src, shard_bytes=100_000, dry_run=False) check("no figures, untouched" in again, "second run leaves the archive alone", again) # -------------------------------------------- 5. an archive without figures section("5. an archive with no figures is never rewritten") plain = os.path.join(tmp, "PLAIN.zip") build_archive(plain, [("PLAIN/Landmarks-Label1-v1.4.0/plan.json.gz", b"x" * 10)]) before = os.path.getsize(plain) msg = split_one(plain, shard_bytes=100_000, dry_run=False) check("no figures, untouched" in msg, "reported untouched", msg) check(os.path.getsize(plain) == before, "byte size unchanged") check(not os.path.exists(os.path.join(tmp, "PLAIN_fig.zip")), "no empty figure archive created") # ------------------------------------------- 6. single shard keeps plain name section("6. a figure set under the ceiling uses _fig.zip") small = os.path.join(tmp, "SMALL.zip") build_archive( small, [ ("SMALL/Landmarks-Label1-v1.4.0/plan.json.gz", b"k" * 100), ("SMALL/Landmarks-Label1-fig-v1.4.0/one.png", os.urandom(1000)), ], ) split_one(small, shard_bytes=40_000_000_000, dry_run=False) check(os.path.exists(os.path.join(tmp, "SMALL_fig.zip")), "named SMALL_fig.zip") check(not os.path.exists(os.path.join(tmp, "SMALL_fig.part01.zip")), "no partNN suffix") finally: shutil.rmtree(tmp, ignore_errors=True) print(f"\n{PASS} passed, {FAIL} failed") sys.exit(1 if FAIL else 0)