Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
test(frames,background,scene): drop duplicate tests and grid rows
Soohong Kim0d147282515a
diff --git a/tests/background/test_tile.py b/tests/background/test_tile.pyindex 8379e24..80cf815 100644--- a/tests/background/test_tile.py+++ b/tests/background/test_tile.py@@ -58,7 +58,7 @@ def test_bounded_search_includes_last_available_crop():assert report["quilt_seam"]["mean_squared_error"] == 0[email protected]("overlap", [1, 2, 4, 7])[email protected]("overlap", [1, 4])def test_alpha_silhouettes_copy_whole_pixels_and_select_tail_at_zero(overlap):period = 8y, x = np.indices((9, period + overlap))@@ -94,9 +94,8 @@ def test_y_axis_is_transposed_x_quilting_with_real_crop_coordinates():@pytest.mark.parametrize("period,overlap,axis", [- (0, 2, "x"), (1, 1, "x"), (5, 0, "x"), (5, -1, "x"),- (5, 5, "x"), (5, 6, "x"), (19, 2, "x"), (9, 2, "y"),- (5, 2, "z"), (5.5, 2, "x"), (True, 2, "x"), (5, 1.5, "x"),+ (0, 2, "x"), (5, 0, "x"), (5, 5, "x"), (19, 2, "x"),+ (5, 2, "z"), (5.5, 2, "x"), (True, 2, "x"),])def test_impossible_geometry_is_rejected(period, overlap, axis):with pytest.raises((ValueError, TypeError)):diff --git a/tests/background/test_tile_cli.py b/tests/background/test_tile_cli.pyindex f0aed05..3247796 100644--- a/tests/background/test_tile_cli.py+++ b/tests/background/test_tile_cli.py@@ -1,7 +1,6 @@# SPDX-License-Identifier: Apache-2.0"""The standalone entrypoint publishes external PNGs through canonical run IO."""-import argparseimport jsonimport osfrom pathlib import Path@@ -14,8 +13,6 @@ from PIL import Imagefrom sprite_gen.background import tilefrom sprite_gen.spec import runio-from conftest import symlink_or_skip-def invoke(source, out, *extra):return subprocess.run(@@ -53,33 +50,16 @@ def test_module_publishes_png_and_report_without_sprite_run(source, tmp_path):assert not list(tmp_path.rglob(runio.LOCK_FILENAME))-def test_registration_arguments_use_the_same_run_function(source, tmp_path):- parser = argparse.ArgumentParser()- tile.add_arguments(parser)- args = parser.parse_args(["--source", str(source), "--out", str(tmp_path / "out.png"),- "--period", "8", "--overlap", "3", "--axis", "y"])- try:- assert tile.run(**vars(args)) == 0- finally:- runio.release_run_dir_lock(tmp_path)- report = json.loads((tmp_path / "out.report.json").read_text())- assert report["size"] == [24, 8]- assert report["axis"] == "y"--[email protected]("alias", ["direct", "symlink", "hardlink", "report-hardlink"])[email protected]("alias", ["direct", "hardlink", "report-hardlink"])def test_source_overwrite_and_aliases_are_refused(source, tmp_path, alias):before = source.read_bytes()out = tmp_path / "new" / "tile.png"report = tmp_path / "new" / "report.json"if alias == "direct":out = source- elif alias in ("symlink", "hardlink"):+ elif alias == "hardlink":out = tmp_path / "alias.png"- if alias == "symlink":- symlink_or_skip(out, source)- else:- os.link(source, out)+ os.link(source, out)else:report = tmp_path / "alias.json"os.link(source, report)@@ -91,7 +71,7 @@ def test_source_overwrite_and_aliases_are_refused(source, tmp_path, alias):assert not list(tmp_path.rglob(runio.LOCK_FILENAME))[email protected]("failure", ["geometry", "bad-axis", "bad-overlap", "not-png", "animation",[email protected]("failure", ["geometry", "not-png", "animation","out-format", "report-format", "nested-paths", "parent-file"])def test_invalid_inputs_do_not_create_output_dirs_or_locks(source, tmp_path, failure):out = tmp_path / "new" / "out.png"@@ -99,10 +79,6 @@ def test_invalid_inputs_do_not_create_output_dirs_or_locks(source, tmp_path, faiextra = []if failure == "geometry":extra = ["--period", "40"]- elif failure == "bad-axis":- extra = ["--axis", "z"]- elif failure == "bad-overlap":- extra = ["--overlap", "0"]elif failure == "not-png":Image.new("RGB", (24, 13)).save(source, format="JPEG")elif failure == "animation":@@ -134,20 +110,6 @@ def test_report_may_not_alias_output(source, tmp_path):assert out.read_bytes() == report.read_bytes() == b"original output"-def test_active_writer_lock_is_not_retried_or_overwritten(source, tmp_path):- output = tmp_path / "output"- output.mkdir()- lock = output / runio.LOCK_FILENAME- lock.write_text(json.dumps({"pid": os.getpid(), "owner": "synthetic-test-writer"}))- before = lock.read_bytes()- proc = invoke(source, output / "tile.png")- assert proc.returncode != 0- assert "locked by synthetic-test-writer" in proc.stderr- assert lock.read_bytes() == before- assert not (output / "tile.png").exists()- assert not (output / "tile.report.json").exists()--def test_canonical_publication_stages_complete_set_and_surfaces_failure(source, tmp_path, monkeypatch):out, report = tmp_path / "tile.png", tmp_path / "tile.json"out.write_bytes(b"previous PNG")diff --git a/tests/background/test_tile_xy.py b/tests/background/test_tile_xy.pyindex 9c9b576..43e4dfa 100644--- a/tests/background/test_tile_xy.py+++ b/tests/background/test_tile_xy.py@@ -66,7 +66,7 @@ def test_a_join_that_stays_visible_on_one_axis_fails_the_report_and_names_that_aassert all(reason.startswith(f"{bad}: ") for reason in report["review_reasons"])[email protected]("bad", ["x", "y"])[email protected]("bad", ["x"])def test_inspection_of_both_axes_catches_a_tile_seamless_on_only_one(bad):# Periodic along one axis, a hard break along the other: one-axis inspection along the good axis passes.good = "y" if bad == "x" else "x"diff --git a/tests/frames/test_chroma_decontam.py b/tests/frames/test_chroma_decontam.pyindex 18b74ac..c319556 100644--- a/tests/frames/test_chroma_decontam.py+++ b/tests/frames/test_chroma_decontam.py@@ -243,16 +243,6 @@ def test_red_strand_blend_comes_back_red_with_partial_coverage():assert go > 0.35 * ro # the engine's result is not red-def test_interior_pixels_stay_byte_identical():- F, A = _render()- raw = _composite_on(F, A, GREEN_PAINTED)- _, interior = _edge(raw)- off, _ = _key(raw)- pal, _ = _key(raw, decontam="palette")- assert interior.sum() > 1000- assert np.array_equal(off[interior], pal[interior])--def test_same_input_same_bytes():F, A = _render()raw = _subsample_420(_composite_on(F, A, GREEN_PAINTED))@@ -261,12 +251,6 @@ def test_same_input_same_bytes():assert np.array_equal(first, second) and s1 == s2-def test_transparent_pixels_carry_no_colour():- F, A = _render()- pal, _ = _key(_composite_on(F, A, GREEN_PAINTED), decontam="palette")- assert not pal[pal[..., 3] == 0, :3].any()--def test_magenta_key_is_handled_by_the_same_pass():# a teal subject, the kind a magenta key is chosen for (red would be magenta-adjacent)F, A = _render(subject=(30, 150, 140), lineart=(12, 52, 60), highlight=(150, 235, 225))@@ -357,15 +341,6 @@ def test_degenerate_key_fails_loud():_key(raw, (128, 128, 128), decontam="palette")-def test_nothing_to_learn_from_fails_loud():- F, A = _render()- raw = _composite_on(F, A, GREEN_PAINTED)- raw[:, :] = GREEN_PAINTED- raw[60:63, 20:140] = HAIR # a 3 px bar: every subject pixel is edge- with pytest.raises(SystemExit, match="no subject pixel lies deeper"):- _key(raw, decontam="palette")--def test_unknown_mode_and_fit_fail_loud():raw = _composite_on(*_render(), GREEN_PAINTED)with pytest.raises(SystemExit, match="unknown mode"):@@ -471,7 +446,9 @@ def test_row_extractor_reads_and_records_chroma_decontam(fixture_run_dir: Path):request_path = fixture_run_dir / "sprite-request.json"plain = run_script("extract_sprite_row_frames.py", "--run-dir", str(fixture_run_dir))assert plain.returncode == 0, plain.stderr- assert "decontam" not in json.loads(request_path.read_text())["chroma"]+ chroma = json.loads(request_path.read_text())["chroma"]+ assert "decontam" not in chroma+ assert chroma["mode"] == "rgb"frames_off = {p.name: p.read_bytes() for p in sorted((fixture_run_dir / "frames").rglob("frame-*.png"))}with_flag = run_script("extract_sprite_row_frames.py", "--run-dir", str(fixture_run_dir), "--decontam", "palette")diff --git a/tests/frames/test_chroma_key_relative.py b/tests/frames/test_chroma_key_relative.pyindex c7b627e..03a9c82 100644--- a/tests/frames/test_chroma_key_relative.py+++ b/tests/frames/test_chroma_key_relative.py@@ -17,9 +17,9 @@ because a partial result is exactly the failure mode (a half-keyed backgroundis not "mostly fine", it is what breaks every downstream gate).Before the relative-threshold fix these cases fail on both the `cutout` route-and the underlying `remove_chroma_background` engine. (5, 200, 10) and-(250, 8, 240) are within 96 of their keys and pass on the old code; they are kept-so the fix cannot regress the easy case.+and the underlying `remove_chroma_background` engine. (5, 200, 10) is within 96+of its key and passes on the old code; it is kept so the fix cannot regress the+easy case."""from __future__ import annotations@@ -44,22 +44,23 @@ SUBJECT_BOX = (32, 32, 96, 96) # x0, y0, x1, y1 (exclusive)HIGHLIGHT_BOX = (56, 56, 72, 72)# (declared key name, key rgb, model-returned flat background, rgb distance to key)+# One case per ball the engine keys from: the pure key's (the easy case), the detected+# family colour's (the measured green, the dark magenta) and the border candidate's (Grok).DARK_KEY_CASES = [pytest.param("green", (0, 255, 0), (8, 162, 24), id="green-measured-8-162-24-dist96.38"),- pytest.param("green", (0, 255, 0), (10, 150, 30), id="green-darker-10-150-30-dist109.66"),pytest.param("green", (0, 255, 0), (5, 200, 10), id="green-easy-5-200-10-dist56.12"),pytest.param("magenta", (255, 0, 255), (170, 8, 180), id="magenta-dark-170-8-180-dist113.64"),- pytest.param("magenta", (255, 0, 255), (180, 10, 175), id="magenta-dark-180-10-175-dist110.11"),- pytest.param("magenta", (255, 0, 255), (250, 8, 240), id="magenta-easy-250-8-240-dist17.72"),# Grok's #FF00FF (measured 2026-09-11, samurai-village rev3 objects): the blue channel- # sits well under the red one (147/216 = 0.68, 155/225 = 0.69), so the keyed-channel- # balance rule of `is_key_family` says "not the key's family" even though the whole- # border is this one flat colour — the detector falls back to the declared key and- # the ~124 / ~117 distance keeps the entire background opaque.+ # sits well under the red one (147/216 = 0.68), so the keyed-channel balance rule of+ # `is_key_family` says "not the key's family" even though the whole border is this one+ # flat colour — the detector falls back to the declared key and the ~124 distance keeps+ # the entire background opaque.pytest.param("magenta", (255, 0, 255), (216, 46, 147), id="magenta-grok-216-46-147-dist123.70"),- pytest.param("magenta", (255, 0, 255), (225, 52, 155), id="magenta-grok-225-52-155-dist116.64"),]GROK_MAGENTA_CASES = [c for c in DARK_KEY_CASES if "grok" in c.id]+# `cutout --key` hands an explicit key to the engine above, which checks the pixels per colour:+# one green and one Grok magenta show the route.+CUTOUT_KEY_CASES = [c for c in DARK_KEY_CASES if c.id.startswith(("green-measured", "magenta-grok"))]def make_flat_key_still(background: tuple[int, int, int]) -> Image.Image:@@ -111,7 +112,7 @@ def test_remove_chroma_background_keys_out_dark_flat_key(assert subject_changed == 0, f"{background} on key {key}: {subject_changed} subject px altered"[email protected](("key", "key_rgb", "background"), DARK_KEY_CASES)[email protected](("key", "key_rgb", "background"), CUTOUT_KEY_CASES)def test_cutout_explicit_key_keys_out_dark_flat_key(tmp_path: Path, key: str, key_rgb: tuple[int, int, int], background: tuple[int, int, int]) -> None:@@ -132,23 +133,6 @@ def test_cutout_explicit_key_keys_out_dark_flat_key(assert stats["alpha_zero_pct"] == expected_alpha_zero_pct-def test_boundary_pair_must_not_split(tmp_path: Path) -> None:- """The measured pair: (7,163,24) keyed out, (8,162,24) survived — one brightness step apart.-- Whatever the fixed rule is, two flat backgrounds this close must be treated- the same. This is the pixel-level "half keyed" symptom stated as a test.- """- key_rgb = (0, 255, 0)- outcomes = {}- for background in ((7, 163, 24), (8, 162, 24)):- source = make_flat_key_still(background)- result = remove_chroma_background(- source, key_rgb, _EXTRACT_KEY_THRESHOLD, _EXTRACT_FRINGE_THRESHOLD, _EXTRACT_FRINGE_DELTA- )- outcomes[background] = audit(result, source)- assert outcomes[(7, 163, 24)] == outcomes[(8, 162, 24)] == (0, 0), outcomes--# --- the detection layer itself ----------------------------------------------# `remove_chroma_background` keys from the smaller of the distance to the# declared key and to the background colour it detects on the borders. These@@ -163,24 +147,17 @@ HOT_PINK = (250, 77, 150) # ~129 from magenta — subject material the trap-banPURPLE = (213, 112, 246) # ~153 from magenta — same+# The border rule is the family rule OR more, so a colour it refuses (its table below) is never+# family; the false rows here are the ones only the family rule refuses: keyed channels out of+# balance, and the degenerate key.@pytest.mark.parametrize(("color", "key", "expected"),[((8, 162, 24), GREEN, True),- ((10, 150, 30), GREEN, True),((20, 120, 25), GREEN, True), # brightness is free- ((3, 248, 5), GREEN, True),((170, 8, 180), MAGENTA, True),- ((251, 2, 248), MAGENTA, True),- ((0, 255, 255), GREEN, False), # cyan: blue is not dark- ((120, 255, 120), GREEN, False), # washed out: unkeyed channels too high- ((30, 60, 30), GREEN, False), # too dark to read as a lit key channel- (HOT_PINK, MAGENTA, False),- (PURPLE, MAGENTA, False),((255, 0, 128), MAGENTA, False), # keyed channels out of balance((216, 46, 147), MAGENTA, False), # Grok magenta: out of balance too — interior rule stays strict- ((225, 52, 155), MAGENTA, False), # (the border-candidate rule below is what admits these)- ((248, 247, 242), GREEN, False),((8, 162, 24), (128, 128, 128), False), # degenerate key has no family],)@@ -273,14 +250,6 @@ def test_cutout_auto_route_uses_the_engine_family_rule() -> None:# must share that one rule.[email protected](("key", "key_rgb", "background"), GROK_MAGENTA_CASES)-def test_detect_accepts_grok_magenta_painted_on_a_flat_border(- key: str, key_rgb: tuple[int, int, int], background: tuple[int, int, int]-) -> None:- """The detector returns the painted border colour, not the declared key, for an off-balance magenta."""- assert detect_background_key_rgb(make_flat_key_still(background), key_rgb) == background--@pytest.mark.parametrize(("key", "key_rgb", "background"), GROK_MAGENTA_CASES)def test_cutout_auto_routes_grok_magenta_corners_to_extract(tmp_path: Path, key: str, key_rgb: tuple[int, int, int], background: tuple[int, int, int]@@ -325,25 +294,18 @@ def test_hot_pink_block_inside_the_subject_survives_a_grok_magenta_key() -> Nonefrom sprite_gen.frames.extract import is_border_key_candidate # noqa: E402+# One row per branch of the rule: the interior rule's colours, the off-balance painted keys, and+# each of the hue signature's three conditions failing. Purple, ivory and cyan are refused through+# the detector in `test_border_candidate_rule_still_rejects_subject_colours_and_non_keys`.@pytest.mark.parametrize(("color", "key", "expected"),[((216, 46, 147), MAGENTA, True), # Grok, 2026-09-11 (blue/red 0.68)- ((225, 52, 155), MAGENTA, True),((236, 59, 161), MAGENTA, True), # prop-fence-bamboo raw border- ((230, 40, 170), MAGENTA, True), # variants a model could paint next- ((200, 60, 140), MAGENTA, True),- ((255, 0, 128), MAGENTA, True), # off-balance but unmistakably the key's hue on a border((170, 8, 180), MAGENTA, True), # everything the interior rule admits, the border rule admits- ((8, 162, 24), GREEN, True),- ((20, 120, 25), GREEN, True),(HOT_PINK, MAGENTA, False), # unkeyed (green) channel lit: 77 >= 64- (PURPLE, MAGENTA, False), # 112 >= 64- ((0, 255, 255), GREEN, False), # cyan- ((120, 255, 120), GREEN, False), # washed out((30, 60, 30), GREEN, False), # keyed channel not lit((70, 60, 65), MAGENTA, False), # dark grey-mauve: unkeyed dark but not saturated (60/70)- ((248, 247, 242), MAGENTA, False),((216, 46, 147), (128, 128, 128), False), # degenerate key has no candidates],)diff --git a/tests/frames/test_cutout.py b/tests/frames/test_cutout.pyindex 9ed3915..50a77fd 100644--- a/tests/frames/test_cutout.py+++ b/tests/frames/test_cutout.py@@ -14,12 +14,10 @@ from pathlib import Pathimport pytestfrom PIL import Image-from sprite_gen.frames.cutout import cutout, estimate_background, _detect_key_kind+from sprite_gen.frames.cutout import cutout, estimate_backgroundIVORY = (248, 247, 242)GREEN = (86, 133, 39)-MAGENTA = (255, 0, 255)-KEY_GREEN = (0, 255, 0)def _make_icon(with_interior_white: bool = False) -> Image.Image:@@ -68,17 +66,6 @@ def test_interior_white_highlight_preserved(tmp_path: Path) -> None:assert (r, g, b) == (255, 255, 255)-def test_no_silent_fallback_holds(tmp_path: Path) -> None:- """cutout() completes without raising — every transparent pixel has zeroed RGB."""- src = tmp_path / "icon.png"- _make_icon().save(src)- out = tmp_path / "icon_cutout.png"- cutout(src, out) # would SystemExit if a transparent pixel kept non-zero RGB- px = Image.open(out).convert("RGBA").load()- r, g, b, a = px[0, 0]- assert (r, g, b, a) == (0, 0, 0, 0)--def test_white_check_composites_written(tmp_path: Path) -> None:src = tmp_path / "icon.png"_make_icon().save(src)@@ -105,58 +92,9 @@ def test_estimate_background_from_corners(tmp_path: Path) -> None:# --- key-colour routing (imported images already on a magenta/green key) ---------def _make_key_icon(bg: tuple[int, int, int], obj: tuple[int, int, int]) -> Image.Image:- img = Image.new("RGBA", (128, 128), bg + (255,))- px = img.load()- for y in range(32, 96):- for x in range(32, 96):- px[x, y] = obj + (255,)- return img---def test_detect_key_kind_classifies_routes() -> None:- assert _detect_key_kind(MAGENTA) == "magenta"- assert _detect_key_kind(KEY_GREEN) == "green"- assert _detect_key_kind(IVORY) == "white"- assert _detect_key_kind((240, 240, 240)) == "white" # low-saturation → matte---def test_magenta_background_routes_to_extract(tmp_path: Path) -> None:- src = tmp_path / "m.png"- _make_key_icon(MAGENTA, (90, 140, 60)).save(src) # green object, no magenta in it- out = tmp_path / "m_cutout.png"- stats = cutout(src, out, key="auto")- assert stats["route"] == "extract:magenta"- px = Image.open(out).convert("RGBA").load()- assert px[0, 0][3] == 0 # magenta background gone- assert px[64, 64][3] == 255 # object intact, no hole---def test_green_background_routes_to_extract(tmp_path: Path) -> None:- src = tmp_path / "g.png"- _make_key_icon(KEY_GREEN, (200, 80, 160)).save(src) # magenta-ish object, no key green in it- out = tmp_path / "g_cutout.png"- stats = cutout(src, out, key="auto")- assert stats["route"] == "extract:green"- px = Image.open(out).convert("RGBA").load()- assert px[0, 0][3] == 0- assert px[64, 64][3] == 255---def test_white_background_stays_on_matte(tmp_path: Path) -> None:- src = tmp_path / "w.png"- _make_icon().save(src)- stats = cutout(src, tmp_path / "w_cutout.png", key="auto")- assert stats["route"] == "matte"---def test_explicit_key_overrides_detection(tmp_path: Path) -> None:- src = tmp_path / "m.png"- _make_key_icon(MAGENTA, (90, 140, 60)).save(src)- stats = cutout(src, tmp_path / "m_cutout.png", key="magenta")- assert stats["route"] == "extract:magenta"+# The routes themselves are checked where the keying is: `test_chroma_key_relative.py`+# (auto and explicit keys, the shared family rule) and `test_chroma_decontam.py` (a white+# background stays on the matte).def test_unknown_key_raises(tmp_path: Path) -> None:diff --git a/tests/frames/test_despill_full_tint_bar.py b/tests/frames/test_despill_full_tint_bar.pyindex 76a71ef..dd1b9b9 100644--- a/tests/frames/test_despill_full_tint_bar.py+++ b/tests/frames/test_despill_full_tint_bar.py@@ -53,15 +53,6 @@ def test_the_full_bar_reaches_a_tint_the_default_bar_leaves_alone(tmp_path: Pathassert _residual_tint(full_keyed).max() < 15, "the full bar has to reach it"-def test_lifting_only_the_size_cap_is_not_enough(tmp_path: Path) -> None:- """The bug as it stood: `full` moved `spill_max_fraction` and nothing changed."""- src = _green_canvas_with_tinted_subject(tmp_path / "in.png", tint=20)- image = Image.open(src).convert("RGBA")- small, _ = extract_route(image, "green")- size_cap_only, _ = extract_route(image, "green", spill_max_fraction=1.0)- assert _residual_tint(small).max() == _residual_tint(size_cap_only).max()--def test_a_subject_that_owns_key_material_is_still_judged_small(tmp_path: Path) -> None:"""The decision reads the bar the treatment will use, so a genuinely green subjectkeeps its green: it is `small`, and `full`'s lowered bar never touches it."""diff --git a/tests/frames/test_extract_perf_equivalence.py b/tests/frames/test_extract_perf_equivalence.pyindex 0f24477..15180ba 100644--- a/tests/frames/test_extract_perf_equivalence.py+++ b/tests/frames/test_extract_perf_equivalence.py@@ -12,15 +12,15 @@ trips here.For the grid scorer the reference is the *integer-exact* naive form, not theoriginal float reduction (plan `sprite-gen/best-phase-hotspot`, 2026-07-25).-The metric is unchanged; only its evaluation is. See-`test_grid_uniformity_matches_the_exact_rational_value` for why the rational-value — not the old float's bit pattern — is the truth being pinned.+The metric is unchanged; only its evaluation is: the old form accumulated+floats per pixel and lands a last-ulp apart from the on-paper rational value,+so the rational value — not the old float's bit pattern — is the truth, and the+optimized scorer is pinned bit for bit to the naive form of it."""from __future__ import annotationsimport math-from fractions import Fractionfrom PIL import Image@@ -89,40 +89,6 @@ def _ref_grid_uniformity(component, pitch, phase):return (total_dev / total_n) if total_n else 1e9-def _ref_grid_uniformity_rational(component, pitch, phase):- """Ground truth with no rounding anywhere — the metric as written on paper- (`mean absolute deviation from the cell mean, weighted by cell size`).- Independent of how either implementation gets there."""- total_dev = Fraction(0)- total_n = 0- for acc in _ref_cells(component, pitch, phase):- n = len(acc)- if n < 2:- continue- mean = [Fraction(sum(c[k] for c in acc), n) for k in range(3)]- dev = sum(sum(abs(c[k] - mean[k]) for k in range(3)) for c in acc) / n- total_dev += dev * n- total_n += n- return (total_dev / total_n) if total_n else Fraction(10 ** 9)---def _ref_grid_uniformity_float(component, pitch, phase):- """The pre-2026-07-25 form: float mean, float absolute deviations, float- reduction. Kept to show the rewrite did not change the *metric* — only how- exactly it is evaluated."""- total_dev = 0.0- total_n = 0- for acc in _ref_cells(component, pitch, phase):- n = len(acc)- if n < 2:- continue- mean = [sum(c[k] for c in acc) / n for k in range(3)]- dev = sum(sum(abs(c[k] - mean[k]) for k in range(3)) for c in acc) / n- total_dev += dev * n- total_n += n- return (total_dev / total_n) if total_n else 1e9--def _ref_matte(source, key):width, height = source.sizeout = Image.new("RGBA", source.size, (0, 0, 0, 0))@@ -273,27 +239,6 @@ def test_grid_uniformity_byte_identical_to_reference():assert got == ref, f"pitch={pitch} phase={phase}: {got!r} != {ref!r}"-def test_grid_uniformity_matches_the_exact_rational_value():- """The scorer's only rounding is one division per cell plus the float- accumulation across cells — so it tracks the on-paper value to ~1e-15.-- This is the contract that replaced "byte-identical to the old float- reduction" (plan `sprite-gen/best-phase-hotspot`, 2026-07-25). The old form- accumulated floats per pixel; the integer-exact form is the same metric- evaluated without that accumulation, which lands a last-ulp apart (measured- max relative gap 1.8e-16 on synthetic_fixture_b). The truth is the rational value,- not the old float's bit pattern — so both are checked against it here.- """- img = _synthetic_keyed()- for pitch in [(7.0, 7.0), (7.82, 8.28), (6.17, 6.32)]:- for phase in [(0.0, 0.0), (1.3, 2.9), (pitch[0] * 5 / 8, pitch[1] * 3 / 8)]:- exact = float(_ref_grid_uniformity_rational(img, pitch, phase))- got = extract._grid_uniformity(img, pitch, phase)- old = _ref_grid_uniformity_float(img, pitch, phase)- assert math.isclose(got, exact, rel_tol=1e-14), f"{pitch} {phase}: {got!r} vs {exact!r}"- assert math.isclose(old, exact, rel_tol=1e-14), f"{pitch} {phase}: {old!r} vs {exact!r}"--def test_grid_rows_rejects_a_non_rgba_component():"""The row index reads alpha at stride 4 — a 3-channel image would silentlyread colour bytes as alpha, so it has to fail loudly instead."""diff --git a/tests/frames/test_extraction_golden.py b/tests/frames/test_extraction_golden.pyindex 051d010..ded96f3 100644--- a/tests/frames/test_extraction_golden.py+++ b/tests/frames/test_extraction_golden.py@@ -32,11 +32,7 @@ def test_extraction_matches_golden_manifest(fixture_run_dir: Path) -> None:_row.pop("engine_revision", None)assert manifest == EXPECTED--def test_extracted_frames_are_cell_sized_rgba(fixture_run_dir: Path) -> None:- result = run_script("extract_sprite_row_frames.py", "--run-dir", str(fixture_run_dir))- assert result.returncode == 0, result.stdout + result.stderr-+ # every frame the manifest names is written, cell-sized and RGBAfor row in EXPECTED["rows"]:for relative in row["files"]:frame_path = fixture_run_dir / relativediff --git a/tests/frames/test_grid_record_exactness.py b/tests/frames/test_grid_record_exactness.pyindex 78c51fc..be1ac44 100644--- a/tests/frames/test_grid_record_exactness.py+++ b/tests/frames/test_grid_record_exactness.py@@ -85,40 +85,6 @@ def _cell_counts(grid: dict) -> tuple[int, int]:return len(grid["x"]) - 1, len(grid["y"]) - 1-def test_recorded_grid_cell_count_equals_final_pixel_count(tmp_path) -> None:- """기록 칸수 == 최종 콘텐츠 픽셀 수. **정확 일치**다 (관용치 없음).-- 이게 깨지면 기록이 진실이 아니라는 뜻이고, 오버레이는 최종 픽셀과 무관한 격자를 그린다."""- run_dir = _build_run(tmp_path, pitch=8)- assert extract_module.run(run_dir=run_dir) == 0- row, scale = _row_and_scale(run_dir)- grids = row.get("input_grids")- assert grids, "input_grids 가 기록되지 않았다 — 격자 진실의 소유자가 없어진다"- for index, rel in enumerate(row["files"]):- final = _content_logical_size(run_dir / rel, scale)- assert _cell_counts(grids[index]) == final, (- f"frame {index}: 기록 칸수 {_cell_counts(grids[index])} != 최종 픽셀 수 {final}")---def test_cell_count_invariant_catches_a_half_pitch_harmonic(tmp_path) -> None:- """mutant 검증: 반피치 하모닉으로 기록을 오염시키면 위 단정이 **실제로** 잡는가.-- 2026-07-18 회귀의 형태를 그대로 재현한다 (기록 45칸 vs 최종 31칸). 단정이 잡지 못하면- 그 테스트는 통과만 하는 장식이다."""- run_dir = _build_run(tmp_path, pitch=8)- assert extract_module.run(run_dir=run_dir) == 0- row, scale = _row_and_scale(run_dir)- grid = dict(row["input_grids"][0])- # 반피치: 절단선 사이에 중간점을 끼워 칸수를 2배로 만든다 (하모닉 오검출과 같은 결과)- harmonic_x = [grid["x"][0]]- for a, b in zip(grid["x"], grid["x"][1:]):- harmonic_x += [(a + b) / 2, b]- mutant = {"x": harmonic_x, "y": grid["y"]}- final = _content_logical_size(run_dir / row["files"][0], scale)- assert _cell_counts(grid) == final # 원본은 통과- assert _cell_counts(mutant) != final, "mutant 가 단정을 통과했다 — 불변식이 아무것도 막지 못한다"--def test_twin_footprint_matches_the_final_frame_exactly(tmp_path) -> None:"""orig 쌍둥이의 콘텐츠 bbox 가 최종 프레임과 **논리픽셀 단위로 정확히** 겹친다.diff --git a/tests/frames/test_heal_async.py b/tests/frames/test_heal_async.pyindex eb468ad..21e4006 100644--- a/tests/frames/test_heal_async.py+++ b/tests/frames/test_heal_async.py@@ -43,31 +43,6 @@ def _noop_report(run_dir):return {"healed": [], "kept_stale": [], "failed": [], "notes": []}-def test_long_heal_returns_busy_within_grace(tmp_path: Path, monkeypatch) -> None:- release = {"at": time.monotonic() + 4.0}-- def slow_heal(run_dir):- while time.monotonic() < release["at"]:- time.sleep(0.05)- return _walk_report(run_dir)-- monkeypatch.setattr(serve_curation, "heal_run", slow_heal)- started = time.monotonic()- busy = serve_curation.maybe_heal(tmp_path)- elapsed = time.monotonic() - started- assert busy is True- # 그레이스(1.5s) + 여유 안에 응답해야 첫 탭이 로딩 UI 를 본다- assert elapsed < serve_curation._HEAL_GRACE_SECONDS + 1.0-- # heal 완료 후: busy 해제 + 리포트가 단일 소비자에서 1회 나온다- serve_curation._heal_state["thread"].join(timeout=10)- monkeypatch.setattr(serve_curation, "heal_run", _noop_report)- assert serve_curation.maybe_heal(tmp_path) is False- report = serve_curation.take_heal_report()- assert report is not None and report["healed"] == ["walk"]- assert serve_curation.take_heal_report() is None # 정확히 1회--def test_progress_poll_never_steals_the_heal_report(tmp_path: Path, monkeypatch) -> None:"""validator validator 재현 결함의 회귀 가드: 장기 heal 완료 직후/api/progress(또는 다운로드) 역할의 maybe_heal 이 먼저 호출돼도 리포트는@@ -80,7 +55,10 @@ def test_progress_poll_never_steals_the_heal_report(tmp_path: Path, monkeypatch)return _walk_report(run_dir)monkeypatch.setattr(serve_curation, "heal_run", slow_heal)+ started = time.monotonic()assert serve_curation.maybe_heal(tmp_path) is True # 장기 heal — busy 즉답+ # 그레이스(1.5s) + 여유 안에 응답해야 첫 탭이 로딩 UI 를 본다+ assert time.monotonic() - started < serve_curation._HEAL_GRACE_SECONDS + 1.0serve_curation._heal_state["thread"].join(timeout=10)# 완료 직후: 트리 폴링/다운로드 경로가 먼저 도착하는 시나리오diff --git a/tests/frames/test_keyed_resample.py b/tests/frames/test_keyed_resample.pyindex c085362..144933a 100644--- a/tests/frames/test_keyed_resample.py+++ b/tests/frames/test_keyed_resample.py@@ -5,8 +5,9 @@(the original-quality twin beside a pixel-unfake frame) and `slice_sheet` (a sheet's figuresbrought to one height) used LANCZOS over premultiplied RGBA, which drew a lighter rim and akey tint at the edge that the keyed picture did not have. They scale through `resize_cell`-(`tests/video/test_strip_resample.py` holds its own properties). Each test fails with LANCZOS-put back.+(`tests/video/test_strip_resample.py` holds its own properties, at a shrink and a growth). The+callers do not branch on size, so each is checked at one size. Each test fails with LANCZOS put+back."""from __future__ import annotations@@ -27,7 +28,7 @@ def _shrunk_into(cell: int, margin: int, sprite: Image.Image) -> tuple[int, int]return max(1, round(sprite.width * scale)), max(1, round(sprite.height * scale))[email protected]("cell", (64, 96, 150))[email protected]("cell", (96,))def test_a_frame_fitted_to_its_cell_carries_no_colour_the_frame_did_not_have(cell: int) -> None:src = figure()sprite = src.crop(src.getbbox())@@ -57,7 +58,7 @@ def test_the_other_fit_filters_are_left_as_they_were(monkeypatch) -> None:assert extract.fit_to_cell(src, 96, 96, 4, 4, {"resample": "kcentroid"}).getbbox() is not None[email protected]("box_height", (60, 172, 240)) # the twin shrinks, nearly keeps its size, grows[email protected]("box_height", (60,)) # the twin shrinksdef test_the_twin_beside_a_pixel_frame_carries_no_colour_the_component_did_not_have(box_height: int) -> None:src = figure()sprite = src.crop(src.getbbox())@@ -74,8 +75,8 @@ def test_the_twin_beside_a_pixel_frame_carries_no_colour_the_component_did_not_hassert colour_outside(sprite, sprite.resize(size, Image.Resampling.LANCZOS)) > 50-# the main component (the body) is 96-97 px tall on the sheet: the figures shrink, nearly keep their size, grow[email protected]("target_height", (72.0, 99.0, 130.0))+# the main component (the body) is 96-97 px tall on the sheet: the figures shrink[email protected]("target_height", (72.0,))def test_a_sliced_figure_carries_no_colour_its_keyed_piece_did_not_have(tmp_path: Path, monkeypatch, target_height: float) -> None:fig = figure()sheet = Image.new("RGBA", (2 * fig.width, fig.height), GREEN + (255,))diff --git a/tests/frames/test_pitch_ground_truth.py b/tests/frames/test_pitch_ground_truth.pyindex 4d2308a..6a5aced 100644--- a/tests/frames/test_pitch_ground_truth.py+++ b/tests/frames/test_pitch_ground_truth.py@@ -42,18 +42,12 @@ def _logical_art(width: int = 24, height: int = 40, seed: int = 11) -> Image.Imadef test_integer_pitch_is_detected_exactly():art = _logical_art()+ # k=12 는 약수 6 을 반환하던 회귀의 재현이다for k in (4, 6, 8, 10, 12, 14, 16, 17, 20, 24, 32):upscaled = art.resize((art.width * k, art.height * k), Image.NEAREST)assert detect_pixel_pitch(upscaled) == k, f"pitch {k} misdetected"-def test_divisor_is_not_preferred_over_true_pitch():- """k=12 에서 6 을 반환하던 회귀의 최소 재현."""- art = _logical_art()- upscaled = art.resize((art.width * 12, art.height * 12), Image.NEAREST)- assert detect_pixel_pitch(upscaled) == 12--def test_phase_follows_crop_offset():art = _logical_art()k = 16@@ -86,7 +80,8 @@ def _mismatch(a: Image.Image, b: Image.Image) -> int:return sum(1 for y in range(a.height) for x in range(a.width) if pa[x, y] != pb[x, y])[email protected]("scale", [12.0, 14.35, 16.0, 16.2, 17.24, 20.0, 23.7])+# integer scales are `test_integer_pitch_still_snaps_exactly`, which asks for an exact match[email protected]("scale", [14.35, 16.2, 17.24, 23.7])def test_fractional_pitch_roundtrips_to_the_original_logical_art(scale):"""소수 배율로 늘린 도트를 스냅하면 원본 논리 픽셀이 그대로 돌아와야 한다.@@ -139,22 +134,6 @@ def test_non_integer_bbox_does_not_stretch_the_grid(fringe):assert abs(w - k) <= 1, f"cell width {w} drifted from pitch {k} (widths={widths})"-def test_pitch_is_detected_per_axis():- """가로/세로 블록 크기가 다르면 축별로 따로 잡아야 한다.-- 비균등 리스케일된 생성물은 가로 블록과 세로 블록이 어긋난다 (chibi 베이스:- 가로 30.38 / 세로 30.92). 한 피치를 두 축에 강제하면 한 축이 통째로 미끄러졌다- — 실측 가로 정렬률 11.7%.- """- art = _logical_art(width=20, height=24)- upscaled = art.resize((art.width * 24, art.height * 30), Image.NEAREST)-- (pitch_x, pitch_y), _ = detect_pixel_grid(upscaled)-- assert abs(pitch_x - 24) < 0.6, f"x pitch {pitch_x:.2f} != 24"- assert abs(pitch_y - 30) < 0.6, f"y pitch {pitch_y:.2f} != 30"--def test_non_square_pitch_roundtrips():art = _logical_art(width=20, height=24)upscaled = art.resize((art.width * 24, art.height * 30), Image.NEAREST)@@ -270,7 +249,7 @@ def test_measured_phase_survives_an_offset_grid_where_the_histogram_phase_does_nf"offset {offset}: 실측 위상인데 픽셀이 어긋난다 ({_mismatch(snapped, art)})")[email protected]("scale", [12.0, 14.35, 16.0, 17.24, 20.0])[email protected]("scale", [14.35, 17.24])def test_measured_phase_roundtrips_like_the_detected_phase(scale):"""스냅 경로가 쓰는 위상(`_best_phase`)도 원본 논리 픽셀을 되돌려야 한다.diff --git a/tests/frames/test_row_scale.py b/tests/frames/test_row_scale.pyindex 399fa27..d42c3e3 100644--- a/tests/frames/test_row_scale.py+++ b/tests/frames/test_row_scale.py@@ -1,10 +1,7 @@# SPDX-License-Identifier: Apache-2.0"""Weapon motion must not change the size of an unchanged body in an image row."""-import json-import pytestfrom PIL import Image, ImageDraw-from conftest import run_scriptfrom sprite_gen.frames import extract@@ -31,9 +28,14 @@ def red_body_size(frame):return box[2]-box[0], box[3]-box[1][email protected]('route', ['components', 'slots'])[email protected]('resample', ['nearest', 'lanczos', 'kcentroid'])[email protected]('cell', [(128, 128), (192, 128), (128, 192)])+# The row's one scale is computed before the resampler is chosen; the resampler only fills the new size and+# the cell shape only decides which side binds, so each resampler, each cell shape and each route is met once.[email protected]('route, resample, cell', [+ ('components', 'nearest', (128, 128)),+ ('components', 'lanczos', (192, 128)),+ ('components', 'kcentroid', (128, 192)),+ ('slots', 'lanczos', (128, 128)),+])def test_weapon_pose_changes_preserve_body_scale(route, resample, cell):fn = extract.extract_component_frames if route == 'components' else extract.extract_slot_framesframes = fn(attack_strip(), 3, *cell, 12, 12,@@ -48,26 +50,6 @@ def test_weapon_pose_changes_preserve_body_scale(route, resample, cell):assert x0 >= 12 and y0 >= 12 and x1 <= cell[0]-12 and y1 <= cell[1]-12-def test_cli_extract_preserves_body_scale(tmp_path):- prepared = run_script('prepare_sprite_run.py', '--out-dir', str(tmp_path),- '--character-id', 'weapon-scale', '--cell-size', '128',- '--safe-margin', '12', '--no-fit-pixel-unfake',- '--fit-align-x', 'bbox-center', '--fit-resample', 'nearest',- '--chroma-key', '#00FF00', '--request-json', json.dumps({- 'states': {'attack': {'frames': 3, 'fps': 8, 'loop': False}}}))- assert prepared.returncode == 0, prepared.stdout + prepared.stderr- attack_strip().save(tmp_path / 'raw/attack.png')- extracted = run_script('extract_sprite_row_frames.py', '--run-dir', str(tmp_path))- assert extracted.returncode == 0, extracted.stdout + extracted.stderr- manifest = json.loads((tmp_path / 'frames/frames-manifest.json').read_text())- row = manifest['rows'][0]- assert manifest['ok'] and row['method'] == 'components'- sizes = [red_body_size(Image.open(tmp_path / path).convert('RGBA')) for path in row['files']]- assert len(sizes) == 3- for axis in (0, 1):- assert max(size[axis] for size in sizes) - min(size[axis] for size in sizes) <= 1--def red_body_centre_x(frame):mask = Image.new('L', frame.size)mask.putdata([255 if r > 180 and g < 80 and b < 80 and a > 128 else 0@@ -77,7 +59,7 @@ def red_body_centre_x(frame):return (box[0] + box[2]) / 2[email protected]('route', ['components', 'slots'])[email protected]('route', ['components'])@pytest.mark.parametrize('align_x', ['foot-centroid', 'centroid', 'alpha-centroid', 'bbox-center'])def test_a_reaching_weapon_does_not_push_its_pose_off_its_anchor(route, align_x):"""The row scale used to fit the widest pose by its own width; placed at its anchor (the legs, bydiff --git a/tests/frames/test_segment_projection.py b/tests/frames/test_segment_projection.pyindex 4ddfbac..5689675 100644--- a/tests/frames/test_segment_projection.py+++ b/tests/frames/test_segment_projection.py@@ -76,21 +76,6 @@ def test_fused_extraction_matches_golden_manifest(fused_run_dir: Path) -> None:assert "[segment] kick: projection split at columns" in result.stderr-def test_fused_strip_fails_without_opt_in(fused_run_dir: Path) -> None:- # Default segmentation is components: the fused strip is one blob and the- # run must fail loudly (this is the failure mode the port addresses).- _set_segmentation(fused_run_dir, None)- result = run_script("extract_sprite_row_frames.py", "--run-dir", str(fused_run_dir))- assert result.returncode == 1- # Strict whole-generation atomicity: a failed FIRST extract publishes no partial generation- # to canonical frames/ — the per-state failure signal is written OUTSIDE frames/ as- # extract-failure.json (still observable, still consumed by the correction loop).- assert not (fused_run_dir / "frames").exists()- failure = json.loads((fused_run_dir / "extract-failure.json").read_text(encoding="utf-8"))- assert failure["ok"] is False- assert any("could not extract 3 sprite components" in error for error in failure["errors"])--def test_cli_flag_enables_projection_without_request_opt_in(fused_run_dir: Path) -> None:_set_segmentation(fused_run_dir, None)result = run_script(diff --git a/tests/frames/test_slice_sheet.py b/tests/frames/test_slice_sheet.pyindex 87dc5ae..e96e20e 100644--- a/tests/frames/test_slice_sheet.py+++ b/tests/frames/test_slice_sheet.py@@ -74,57 +74,24 @@ def test_slice_sheet_normalizes_height_and_baseline(tmp_path: Path) -> None:assert bottom == round(BASELINE), path.nameif path.stem != "cell-1": # cell 1 carries an effect above the headassert (bottom - top) == round(TARGET), path.name+ # no chroma residue in any cell+ pixels = image.load()+ for y in range(image.size[1]):+ for x in range(image.size[0]):+ r, g, b, a = pixels[x, y]+ assert not (a > 60 and r > 150 and b > 150 and g < 100), f"{path.name} keeps magenta"--def test_slice_sheet_drops_neighbour_overhang_keeps_effect(tmp_path: Path) -> None:- sheet_path = tmp_path / "sheet.png"- _synthetic_sheet().save(sheet_path)- written = slice_sheet(- sheet_path,- tmp_path / "out",- parse_chroma_key("magenta"),- grid=GRID,- canvas=CANVAS,- baseline_y=BASELINE,- target_height=TARGET,- noise_min=10,- )+ # the neighbour's overhang is dropped from cell 1, its detached in-cell effect keptcell1 = Image.open(next(p for p in written if p.stem == "cell-1"))pixels = cell1.load()- reds = greys = 0+ reds = 0for y in range(cell1.size[1]):for x in range(cell1.size[0]):r, g, b, a = pixels[x, y]- if a == 0:- continue- if r > 150 and g < 90:+ if a and r > 150 and g < 90:reds += 1- if r < 90 and b > 60:- greys += 1assert reds > 0, "detached in-cell effect must survive"# 오버행 팔은 셀 좌측 경계에 붙은 얇은 조각으로 들어오므로, 본체+이펙트 외의# 좌측 경계 접촉 픽셀이 남아 있으면 실패다: 경계 3px 안 불투명 픽셀 검사left_edge = sum(1 for y in range(cell1.size[1]) for x in range(0, 3) if pixels[x, y][3] > 0)assert left_edge == 0, "neighbour overhang must be dropped"---def test_slice_sheet_no_chroma_residue(tmp_path: Path) -> None:- sheet_path = tmp_path / "sheet.png"- _synthetic_sheet().save(sheet_path)- written = slice_sheet(- sheet_path,- tmp_path / "out",- parse_chroma_key("magenta"),- grid=GRID,- canvas=CANVAS,- baseline_y=BASELINE,- target_height=TARGET,- noise_min=10,- )- for path in written:- pixels = Image.open(path).load()- image = Image.open(path)- for y in range(image.size[1]):- for x in range(image.size[0]):- r, g, b, a = pixels[x, y]- assert not (a > 60 and r > 150 and b > 150 and g < 100), f"{path.name} keeps magenta"diff --git a/tests/frames/test_slice_sheet_scale.py b/tests/frames/test_slice_sheet_scale.pyindex 163da1f..6f4edff 100644--- a/tests/frames/test_slice_sheet_scale.py+++ b/tests/frames/test_slice_sheet_scale.py@@ -33,19 +33,12 @@ def chroma_sheet(path: Path, boxes, cell: int = 100) -> Path:return path-def transparent_sheet(path: Path, boxes, cell: int = 100, haze: bool = False) -> Path:- """The same boxes on a sheet that is already transparent; ``haze`` rings each with faint alpha 6 px wide."""+def transparent_sheet(path: Path, boxes, cell: int = 100) -> Path:+ """The same boxes on a sheet that is already transparent."""pixels = np.zeros((cell, cell * len(boxes), 4), dtype=np.uint8)for index, (w, h) in enumerate(boxes):x0, bottom = index * cell + (cell - w) // 2, cell - 10pixels[bottom - h:bottom, x0:x0 + w] = PROP- if haze:- solid = pixels[..., 3] > 0- near = np.zeros_like(solid)- for dy in range(-6, 7):- for dx in range(-6, 7):- near |= np.roll(np.roll(solid, dy, 0), dx, 1)- pixels[near & ~solid] = (200, 200, 220, 20)Image.fromarray(pixels).save(path)return path@@ -139,24 +132,6 @@ def test_sheet_scale_with_contain_takes_the_one_factor_every_cut_fits(tmp_path):assert abs(anchor_y - y1) <= 1 and abs(anchor_x - (x0 + x1) / 2) <= 1, path.name-def test_sheet_scale_after_the_alpha_cleanup_keeps_the_drawn_heights_relative(tmp_path):- boxes = [(40, 60), (40, 30), (40, 15)]- sheet = transparent_sheet(tmp_path / "props.png", boxes, haze=True)- written = slice_sheet(sheet, tmp_path / "out", None, grid=(3, 1), canvas=(128, 192), baseline_y=180.0,- target_height=120.0, alpha_floor=64, scale="sheet", fit="contain")- data = report(tmp_path / "out")- assert data["alpha_cleanup"] == "alpha-cleanup.json"- assert (tmp_path / "out" / "alpha-cleanup.json").is_file()- heights = []- for path, (_w, h), cell in zip(written, boxes, data["cells"]):- x0, y0, x1, y1 = opaque_box(path)- assert abs((y1 - y0) - h * data["factor"]) <= 1, path.name- assert cell["clipped_px"] == 0- heights.append(y1 - y0)- # drawn 60 : 30 : 15, cut 4 : 2 : 1 within a pixel- assert abs(heights[0] - 2 * heights[1]) <= 2 and abs(heights[1] - 2 * heights[2]) <= 2--def test_game_pack_images_keep_the_sliced_sizes_and_stand_on_the_reported_anchor(tmp_path):boxes = [(30, 60), (30, 30), (80, 20)]sheet = transparent_sheet(tmp_path / "props.png", boxes)diff --git a/tests/frames/test_slice_sheet_transparent.py b/tests/frames/test_slice_sheet_transparent.pyindex 8412f4a..3427f17 100644--- a/tests/frames/test_slice_sheet_transparent.py+++ b/tests/frames/test_slice_sheet_transparent.py@@ -12,7 +12,6 @@ import numpy as npfrom PIL import Imagefrom sprite_gen import cli-from sprite_gen.frames import slice_sheet as slice_modulefrom sprite_gen.frames.slice_sheet import slice_sheetPROP = (60, 90, 140, 250)@@ -48,14 +47,6 @@ def slice_(tmp_path, name, **kwargs):target_height=120.0, **kwargs)-def test_none_keeps_the_sheets_own_alpha(tmp_path):- written = slice_(tmp_path, "plain")- assert len(written) == 6- with Image.open(written[0]) as image:- alpha = np.asarray(image.convert("RGBA"))[..., 3]- assert alpha.max() >= 240 and alpha[0, 0] == 0--def test_alpha_floor_clears_the_haze_ring_before_measuring_parts(tmp_path):hazy = slice_(tmp_path, "hazy")clean = slice_(tmp_path, "clean", alpha_floor=64)@@ -67,6 +58,8 @@ def test_alpha_floor_clears_the_haze_ring_before_measuring_parts(tmp_path):assert report["haze_fraction_before"] > 0 and report["haze_fraction_after"] == 0assert report["changed_solid_pixels"] == 0assert not (tmp_path / "hazy" / "alpha-cleanup.json").exists()+ # the slice report names the cleanup report+ assert json.loads((tmp_path / "clean" / "slice-sheet.json").read_text())["alpha_cleanup"] == "alpha-cleanup.json"def test_cli_takes_none_and_the_floor(tmp_path):@@ -78,8 +71,3 @@ def test_cli_takes_none_and_the_floor(tmp_path):"--baseline-y", "180", "--target-height", "120"]) == 0assert (out / "prop_alpha-cleanup.json").is_file()assert len(list(out.glob("prop_cell-*.png"))) == 6---def test_parse_chroma_key_reads_none():- assert slice_module.parse_chroma_key("none") is None- assert slice_module.parse_chroma_key("magenta") == (255, 0, 255)diff --git a/tests/frames/test_takes_heal.py b/tests/frames/test_takes_heal.pyindex cf9390b..21185fb 100644--- a/tests/frames/test_takes_heal.py+++ b/tests/frames/test_takes_heal.py@@ -108,25 +108,6 @@ def test_takes_require_pixel_perfect(tmp_path: Path) -> None:assert extract_module.run(run_dir=run_dir) == 1-def test_heal_rederives_stale_rows(tmp_path: Path) -> None:- run_dir = _build_run(tmp_path)- assert extract_module.run(run_dir=run_dir) == 0- manifest_path = run_dir / "frames" / "frames-manifest.json"-- # 현재 엔진으로 갓 구운 런은 이미 신선 — no-op- report = extract_module.heal_run(run_dir)- assert report["healed"] == [] and report["kept_stale"] == []-- # 구엔진 스탬프 시뮬레이션 → heal 이 raw 에서 재유도하고 재스탬프- manifest = _manifest(run_dir)- manifest["rows"][0]["engine_revision"] = "0" * 12- manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")- report = extract_module.heal_run(run_dir)- assert report["healed"] == ["walk"]- assert _manifest(run_dir)["rows"][0]["engine_revision"] == extract_module.engine_revision()- assert (run_dir / "frames" / "walk" / "frame-1.png").is_file()--def test_heal_keeps_stale_row_without_raw(tmp_path: Path) -> None:run_dir = _build_run(tmp_path)assert extract_module.run(run_dir=run_dir) == 0diff --git a/tests/frames/test_ui_kit.py b/tests/frames/test_ui_kit.pyindex ea69570..e64053c 100644--- a/tests/frames/test_ui_kit.py+++ b/tests/frames/test_ui_kit.py@@ -21,10 +21,10 @@ centres lie in the boxes above theirs, is fitted to the drawing before its partsA kit is written whole into a new or empty directory: one that holds anything is refused and left asit was. The kit is published at one step, the rename that gives it the out-dir's name or, with the-report outside, the link that gives the report its name. A failure, an interrupt or a kill just-before or just after any filesystem step of the publish leaves nothing before that step and the whole-kit from it on; an interrupt of any kind at any line or instruction of the publish leaves nothing or-the whole kit; and a run that another run's kit or report reaches first takes its own back out.+report outside, the link that gives the report its name. A failure or a kill just before or just+after any filesystem step of the publish leaves nothing before that step and the whole kit from it on;+an interrupt of any kind at any line or instruction of the publish leaves nothing or the whole kit;+and a run that another run's kit or report reaches first takes its own back out."""import contextlib@@ -556,7 +556,7 @@ def test_the_frames_are_required_and_the_band_is_optional():assert [slot.name for slot in ui_kit.LAYOUT if slot.optional] == BAND[email protected]("missing", ["joystick_knob", "pip_off", "xp_bar_fill", ("slot", "badge"), tuple(BAND)])[email protected]("missing", ["pip_off", tuple(BAND)])def test_an_empty_box_of_the_band_leaves_that_element_out_of_the_kit(missing):gone = [missing] if isinstance(missing, str) else list(missing)image, drawn = synthetic_sheet(size=TALL, missing=missing)@@ -571,13 +571,6 @@ def test_an_empty_box_of_the_band_leaves_that_element_out_of_the_kit(missing):assert all(0 <= value <= 2 for value in offset(report, drawn, name)), name[email protected]("name", FRAMES)-def test_an_empty_frame_box_of_the_tall_sheet_still_refuses_the_sheet(name):- image, _ = synthetic_sheet(size=TALL, missing=name)- with pytest.raises(ValueError, match=f"^{name}: its box holds no element; generate the sheet again$"):- ui_kit.split_ui_kit(image)--def test_every_empty_frame_box_is_named_and_an_empty_band_box_is_not():image, _ = synthetic_sheet(size=TALL, missing=("panel", "card", "pip_on"))with pytest.raises(ValueError, match="^panel, card: their boxes hold no element; generate the sheet again$"):@@ -718,8 +711,8 @@ KILLED = 97class Faults:"""Every filesystem call the publish makes once the sheet is cut, counted. The k-th one fails once, just before it- runs or just after it returned: by an OSError (EIO), by a real SIGINT, which Python's own handler raises as- KeyboardInterrupt, or by ending the process there, as a kill would."""+ runs or just after it returned: by an OSError (EIO), or by ending the process there, as a kill would. An interrupt+ at a call is an interrupt at that call's instruction, which the instruction sweep below raises."""def __init__(self, monkeypatch, cut):self.armed, self.calls, self.fail_at, self.when, self.mode, self.fired = False, [], None, None, None, False@@ -736,8 +729,6 @@ class Faults:self.fired = Trueif self.mode == "kill":os._exit(KILLED)- if self.mode == "interrupt":- signal.raise_signal(signal.SIGINT)raise OSError(errno.EIO, f"injected {name} failure")def wrap(self, name, call):@@ -758,20 +749,15 @@ class Faults:return faultydef run(self, args, fail_at=None, when=None, mode=None):- """The command's exit code, its refusal or "KeyboardInterrupt"; a kill runs it in a child process and gives- the child's code."""+ """The command's exit code or its refusal; a kill runs it in a child process and gives the child's code."""self.calls, self.fail_at, self.when, self.mode, self.fired = [], fail_at, when, mode, Falseif mode != "kill":- interrupt = signal.signal(signal.SIGINT, signal.default_int_handler)try:return ui_kit.main(args)except SystemExit as exc:return str(exc)- except KeyboardInterrupt:- return "KeyboardInterrupt"finally:self.armed = False- signal.signal(signal.SIGINT, interrupt)pid = os.fork()if pid == 0:code = 1@@ -791,21 +777,20 @@ def files_of(state):# A kill forks the test process, which pytest-xdist runs with threads of its own: the child makes only the publish's# filesystem calls and leaves by os._exit, and one that hung would end the test by its timeout.@pytest.mark.filterwarnings("ignore:This process .* is multi-threaded, use of fork:DeprecationWarning")[email protected]("mode", ["raise", "interrupt", pytest.param("kill", marks=pytest.mark.skipif([email protected]("mode", ["raise", pytest.param("kill", marks=pytest.mark.skipif(not hasattr(os, "fork"), reason="a kill is a child process ended at the fault"))])@pytest.mark.parametrize("when", ["before", "after"])@pytest.mark.parametrize("start", ["absent", "empty", "empty, removed first"])@pytest.mark.parametrize("placement", sorted(PUBLISH_PLACES))-def test_a_failure_an_interrupt_or_a_kill_at_any_step_of_the_publish_leaves_nothing_or_the_whole_kit(+def test_a_failure_or_a_kill_at_any_step_of_the_publish_leaves_nothing_or_the_whole_kit(tmp_path, monkeypatch, placement, start, when, mode):# Each filesystem call of the publish fails once, just before it runs or just after it returned, in a copy of the# same start. One of those calls publishes the kit: the rename that gives it --out-dir's name or, with the report- # outside, the link that gives the report its name. An error or an interrupt before that leaves the start exactly,- # with nothing hidden; from it on, the whole kit, and an interrupt still ends the run. A kill leaves what the run- # had made: the start, the whole kit or, killed between the rename and the link, the whole --out-dir and no- # report yet; never part of a kit under the out-dir's name, and nothing hidden but the run's own staging- # directory or report temp beside them. "removed first" is the Windows rename, which takes no existing- # directory's name, so an empty --out-dir is removed just before it.+ # outside, the link that gives the report its name. An error before that leaves the start exactly, with nothing+ # hidden; from it on, the whole kit. A kill leaves what the run had made: the start, the whole kit or, killed+ # between the rename and the link, the whole --out-dir and no report yet; never part of a kit under the out-dir's+ # name, and nothing hidden but the run's own staging directory or report temp beside them. "removed first" is the+ # Windows rename, which takes no existing directory's name, so an empty --out-dir is removed just before it.out_rel, report_rel = PUBLISH_PLACES[placement]sheet = tmp_path / "uikit.png"image, _ = synthetic_sheet(size=TALL, missing="pip_off")@@ -869,10 +854,7 @@ def test_a_failure_an_interrupt_or_a_kill_at_any_step_of_the_publish_leaves_nothassert kept <= directories <= kept | {path for path, data in complete.items() if data is None}, wherecontinueassert faults.fired, where- if mode == "interrupt":- assert outcome == "KeyboardInterrupt", where- else:- assert outcome in (0, f"ui-kit: [Errno {errno.EIO}] injected {call[:call.index('(')]} failure"), where+ assert outcome in (0, f"ui-kit: [Errno {errno.EIO}] injected {call[:call.index('(')]} failure"), whereif ran(published):# hidden: only the report's temp, when removing it after the kit was published is what failedassert after == complete and (hidden == [] or (@@ -885,81 +867,15 @@ class Halt(BaseException):"""An exception of no standard kind."""-# How each kind of interrupt arrives and what it ends the run with: a real signal through its handler (Python's own-# for SIGINT; for SIGTERM, one that exits, as a service installs), or an exception of no standard kind.+# How each kind of interrupt arrives and what it ends the run with: a real signal through Python's own SIGINT+# handler, or an exception of no standard kind. A SIGTERM handler that exits ends the run through the same+# `except BaseException`, with no signal-specific code, so it is not swept again.INTERRUPTS = {"SIGINT": (signal.SIGINT, signal.default_int_handler, KeyboardInterrupt),- "SIGTERM": (signal.SIGTERM, lambda signum, frame: sys.exit(128 + signum), SystemExit),"BaseException": (None, None, Halt),}[email protected]("kind", sorted(INTERRUPTS))[email protected]("placement", sorted(PUBLISH_PLACES))-def test_any_interrupt_from_the_rename_on_leaves_nothing_before_the_kit_is_published_and_the_whole_kit_after(- tmp_path, placement, kind):- # Nothing is replaced: a profile hook sees the real filesystem calls of a run on a whole sheet, and the interrupt- # arrives just before each one from the rename that gives the kit --out-dir's name on, or just after it returned.- # Before the step that publishes the kit (that rename, or with the report outside, the link that gives the report- # its name) the run leaves nothing; from it on, the whole kit, its report naming only files that are there.- out_rel, report_rel = PUBLISH_PLACES[placement]- sheet = tmp_path / "uikit.png"- synthetic_sheet(size=TALL)[0].save(sheet)- signum, handler, ends = INTERRUPTS[kind]- watched = {id(getattr(os, name)): name for name in FS_CALLS}-- def publish(root, point=None):- """Run the command into ``root``, interrupted at ``point``: the k-th call and "c_call", just before it, or- "c_return", just after it returned. Answers the calls the run made, by name, and what ended it."""- root.mkdir()- names = []-- def hook(frame, event, arg):- if event not in ("c_call", "c_return") or id(arg) not in watched:- return- if event == "c_call":- names.append(watched[id(arg)])- if (len(names), event) == point:- sys.setprofile(None)- if signum is None:- raise Halt- signal.raise_signal(signum)-- previous = signal.signal(signum, handler) if signum is not None else None- sys.setprofile(hook)- try:- ended = ui_kit.main(["--sheet", str(sheet), "--out-dir", str(root / out_rel)]- + (["--report", str(root / report_rel)] if report_rel else []))- except BaseException as exc:- ended = exc- finally:- sys.setprofile(None)- if signum is not None:- signal.signal(signum, previous)- return names, ended-- names, ended = publish(tmp_path / "reference")- assert ended == 0- complete = tree(tmp_path / "reference")- report = tmp_path / "reference" / (report_rel or f"{out_rel}/ui-kit.json")- elements = json.loads(report.read_text())["elements"]- out = (tmp_path / "reference" / out_rel).resolve()- assert len(elements) == 15 and {ui_kit.element_path(report, entry["file"]).resolve()- for entry in elements.values()} == {out / f"{name}.png" for name in elements}- assert sorted(path.name for path in out.iterdir()) == sorted(- [f"{name}.png" for name in elements] + ([] if report_rel else ["ui-kit.json"]))- renamed = names.index("rename") + 1- published = names.index("link") + 1 if report_rel else renamed- for k in range(renamed, len(names) + 1):- for event in ("c_call", "c_return"):- root = tmp_path / f"{k}-{event}"- _, ended = publish(root, (k, event))- where = (k, names[k - 1], event, repr(ended), tree(root))- assert isinstance(ended, ends) and (signum != signal.SIGTERM or ended.code == 128 + signum), where- assert tree(root) == (complete if k > published or (k == published and event == "c_return")- else ({}, [])), where--# Interrupted after a file is opened and before its with statement holds it, or as that statement closes it, a run# leaves the file object to be closed when the run's frames go, which Python reports as an unclosed file.@pytest.mark.filterwarnings("ignore:unclosed file:ResourceWarning")@@ -1055,8 +971,7 @@ def test_an_interrupt_at_any_line_or_instruction_of_the_publish_leaves_nothing_omissed.append(at)continueassert given == before- if not (isinstance(ended, ends) and (signum != signal.SIGTERM or ended.code == 128 + signum)- and after in (before, complete)):+ if not (isinstance(ended, ends) and after in (before, complete)):bad.append((f"{at}#{target[2]}", repr(ended), sorted(after[0]), after[1]))assert bad == []# Every line event of the reference run recurs in a faulted one. A tracer's instruction events can differ a little@@ -1187,9 +1102,16 @@ def test_a_packed_fill_is_stored_as_its_bar_frames_content_area(tmp_path, scale)ends = np.asarray(resized)assert np.array_equal(cells[:, :left], ends[:, :left])assert np.array_equal(cells[:, rect["w"] - right:], ends[:, resized.width - right:])+ # round parts keep their aspect: scaled by `scale` alone, never stretched+ report = json.loads((tmp_path / "ui" / "ui-kit.json").read_text())+ for name in ("pip_on", "pip_off", "joystick_base", "joystick_knob"):+ entry, source = nine[name], report["elements"][name]["size"]+ assert entry["stretch"] == "none" and set(entry["insets"].values()) == {0}+ assert entry["size"] == {"w": max(1, round(source["w"] * scale)), "h": max(1, round(source["h"] * scale))}+ assert stored_frame(out, result, entry["frame"]).size == (entry["size"]["w"], entry["size"]["h"])[email protected]("missing", ["pip_off", "xp_bar_fill", ("joystick_base", "joystick_knob"), tuple(BAND)])[email protected]("missing", ["xp_bar_fill", tuple(BAND)])def test_a_partial_kit_packs_only_the_elements_it_holds(tmp_path, missing):gone = {missing} if isinstance(missing, str) else set(missing)result, out = pack_tall_kit(tmp_path, 0.5, missing=missing)@@ -1200,18 +1122,7 @@ def test_a_partial_kit_packs_only_the_elements_it_holds(tmp_path, missing):assert json.loads((out / "game-pack.json").read_text())["ui"]["nine_slice"] == nine[email protected]("scale", [1, 0.5, 0.37])-def test_packed_round_parts_keep_their_aspect(tmp_path, scale):- result, out = pack_tall_kit(tmp_path, scale)- report = json.loads((tmp_path / "ui" / "ui-kit.json").read_text())- for name in ("pip_on", "pip_off", "joystick_base", "joystick_knob"):- entry, source = result["ui"]["nine_slice"][name], report["elements"][name]["size"]- assert entry["stretch"] == "none" and set(entry["insets"].values()) == {0}- assert entry["size"] == {"w": max(1, round(source["w"] * scale)), "h": max(1, round(source["h"] * scale))}- assert stored_frame(out, result, entry["frame"]).size == (entry["size"]["w"], entry["size"]["h"])--[email protected]("size", [(SIZE, SIZE), TALL])[email protected]("size", [TALL])@pytest.mark.parametrize("scale", [0.75, 0.5, 0.37, 0.25])def test_packed_kit_keeps_ornament_fringes_out_of_the_stretched_middle(tmp_path, scale, size):image, _ = synthetic_sheet(size=size, noise=False, haze=False)diff --git a/tests/scene/test_inspect_scene.py b/tests/scene/test_inspect_scene.pyindex e447b9f..6d5a857 100644--- a/tests/scene/test_inspect_scene.py+++ b/tests/scene/test_inspect_scene.py@@ -14,8 +14,6 @@ from sprite_gen.scene.inspect_scene import inspect_scene, output_path, runfrom sprite_gen.scene.model import load_scenefrom sprite_gen.spec import runio-from conftest import symlink_or_skip-def frames_asset(tmp_path, name, images, duration=0.1):entries = []@@ -167,14 +165,12 @@ def test_run_publishes_the_report_under_the_writer_lock_and_releases_it(tmp_pathassert calls == [("lock", "scene-inspect"), ("write",), ("release",)][email protected]("target", [".sprite-gen.lock", "reports/.sprite-gen.lock", ".out.sg-rwlock", "scene.json", "ramp-3.png",- "spec-symlink.json", "asset-hardlink.png", "a-directory", "ramp-0.png/report.json"])[email protected]("target", [".sprite-gen.lock", ".out.sg-rwlock", "scene.json",+ "asset-hardlink.png", "a-directory", "ramp-0.png/report.json"])def test_run_refuses_reserved_names_scene_inputs_and_their_aliases(tmp_path, capsys, target):spec = ramp_scene(tmp_path)out = tmp_path / target- if target == "spec-symlink.json":- symlink_or_skip(out, spec)- elif target == "asset-hardlink.png":+ if target == "asset-hardlink.png":os.link(tmp_path / "ramp-1.png", out)elif target == "a-directory":out.mkdir()diff --git a/tests/scene/test_layer_resample.py b/tests/scene/test_layer_resample.pyindex 2915e64..ac34ea6 100644--- a/tests/scene/test_layer_resample.py+++ b/tests/scene/test_layer_resample.py@@ -20,7 +20,7 @@ from sprite_gen.scene.render import Rendererfrom sprite_gen.util.resample import resize_cell[email protected]("scale", (0.5, 0.75, 1.25, 2.0))[email protected]("scale", (2.0,))def test_a_scaled_layer_carries_no_colour_its_frame_did_not_have(tmp_path: Path, scale: float) -> None:src = figure()src.save(tmp_path / "hero.png")@@ -36,13 +36,3 @@ def test_a_scaled_layer_carries_no_colour_its_frame_did_not_have(tmp_path: Path,assert colour_outside(src, image) == 0assert image.tobytes() == resize_cell(src, size).tobytes()assert colour_outside(src, src.resize(size, Image.Resampling.LANCZOS)) > 100---def test_a_layer_at_its_own_size_is_the_frame_itself(tmp_path: Path) -> None:- src = figure()- src.save(tmp_path / "hero.png")- (tmp_path / "scene.json").write_text(json.dumps({- "kind": "sprite-gen-scene", "version": 1, "canvas": {"width": 200, "height": 200}, "fps": 10, "duration": 0.5,- "assets": {"hero": "hero.png"}, "layers": [{"id": "hero", "asset": "hero", "at": [100, 190]}]}))- (image, _anchor, _shadow, _bbox), = Renderer(load_scene(tmp_path / "scene.json")).prepared["hero"].values()- assert image.tobytes() == src.tobytes()diff --git a/tests/scene/test_render.py b/tests/scene/test_render.pyindex 0d1c007..2b86936 100644--- a/tests/scene/test_render.py+++ b/tests/scene/test_render.py@@ -129,13 +129,10 @@ def test_export_layers_publishes_frame_zero_plates_and_records_it(tmp_path):("png,mp4", {}, "even canvas dimensions"),("gif", {"gif_fps": 20}, "cannot exceed the scene fps"),("gif", {"gif_width": 40}, "gif_width"),- ("gif", {"gif_width": 0}, "gif_width"),("gif", {"gif_colors": 1}, "gif_colors"),- ("gif", {"gif_colors": 257}, "gif_colors"),("gif", {"gif_dither": "random"}, "gif_dither"),("gif", {"gif_max_bytes": 0}, "gif_max_bytes"),("webm", {}, "formats"),- ("", {}, "formats"),])def test_prerequisites_fail_before_any_output_exists_and_the_corrected_call_succeeds(tmp_path, formats, kwargs, message):spec = write_scene(tmp_path, [{"id": "hero", "asset": "red", "at": [8, 12]}], width=15)@@ -148,7 +145,7 @@ def test_prerequisites_fail_before_any_output_exists_and_the_corrected_call_succassert render_scene(spec, out, formats="png")["frames"] == 5[email protected]("formats", ["mp4", "gif", "png,gif"])[email protected]("formats", ["mp4", "gif"])def test_missing_ffmpeg_is_reported_before_any_directory_is_created(tmp_path, monkeypatch, formats):spec = write_scene(tmp_path, [{"id": "hero", "asset": "red", "at": [8, 12]}])monkeypatch.setattr(render.shutil, "which", lambda name: None)@@ -233,34 +230,6 @@ def test_input_replaced_after_decoding_is_detected_and_nothing_is_published(tmp_assert frame.getpixel((2, 2)) == BLUE-def test_shared_source_replaced_between_asset_loads_fails_before_any_output_exists(tmp_path, monkeypatch):- actor = square(tmp_path / "actor.png")- spec = write_scene(tmp_path, [{"id": "left", "asset": "first", "at": [4, 8]}, {"id": "right", "asset": "second", "at": [12, 8]}],- assets={"first": "actor.png", "second": "actor.png"}, height=8, fps=1, duration=1)- original = assets._read_bytes- reads = []-- def replace_after_first_read(path):- data = original(path)- if Path(path).name == "actor.png":- reads.append(data)- if len(reads) == 1:- square(actor, BLUE)- return data-- monkeypatch.setattr(assets, "_read_bytes", replace_after_first_read)- out = tmp_path / "out"- with pytest.raises(ValueError, match="changed during load"):- render_scene(spec, out, formats="png")- assert len(reads) == 2 and reads[0] != reads[1]- assert not out.exists() and sorted(p.name for p in tmp_path.iterdir()) == ["actor.png", "scene.json"]- monkeypatch.undo()- report = render_scene(spec, out, formats="png")- assert report["source_fingerprints"][str(actor.resolve())] == hashlib.sha256(actor.read_bytes()).hexdigest()- with Image.open(out / "check-00000.png") as frame:- assert frame.getpixel((4, 6)) == BLUE and frame.getpixel((12, 6)) == BLUE--@pytest.mark.parametrize("problem", ["inputs-inside", "nonempty", "live-lock", "file"])def test_output_directory_rules_are_enforced_without_touching_the_destination(tmp_path, problem):spec = write_scene(tmp_path, [{"id": "hero", "asset": "red", "at": [8, 12]}])