Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
test(out-dir): what a verb reads is never what it writes or deletes — video-loop, video-stop, video-frames, correction-loop, logo, video-extend and video-edit given an input that is, lies inside or goes through what the run replaces, or that sits in a folder of an old fixed scratch name, keep it byte for byte and refuse before anything is made; video-sway-inspect takes a loop directory spelt in capitals for the loop directory (red)
Soohong Kimed8cd2c0c510
diff --git a/tests/conftest.py b/tests/conftest.pyindex 6ff3516..99a3fdb 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -70,6 +70,14 @@ NOT_RIFE_SKIPS = {# lane's Linux volume tells the two spellings apart, so the layout the case measures cannot be made there."tests/effects/test_breathe_publish.py::test_overlapping_folders_are_refused_before_anything_is_made""[out_inside_frames_spelt_in_capitals]",+ "tests/video/test_loop_inputs_kept.py::test_a_cut_never_writes_over_or_deletes_the_frames_it_reads"+ "[out_spelt_in_capitals]",+ "tests/video/test_frames_inputs_kept.py::test_frames_never_write_over_or_delete_the_clip_or_still_they_read"+ "[source_manifest_spelt_in_capitals]",+ "tests/gen/test_logo.py::test_a_given_lettering_spelt_in_capitals_is_its_own_file_and_is_cut_again",+ "tests/gen/test_video_modes.py::test_the_result_is_never_published_over_the_clip_it_is_made_from[extend-capitals]",+ "tests/gen/test_video_modes.py::test_the_result_is_never_published_over_the_clip_it_is_made_from[edit-capitals]",+ "tests/video/test_follow_inspect.py::test_the_loop_directory_spelt_in_capitals_is_the_loop_directory",}diff --git a/tests/gen/test_logo.py b/tests/gen/test_logo.pyindex 1d4efc4..9aeb792 100644--- a/tests/gen/test_logo.py+++ b/tests/gen/test_logo.py@@ -9,7 +9,9 @@ report says. Nothing here draws a font: a logo comes from the model or not at alfrom __future__ import annotations+import hashlibimport json+import reimport unicodedatafrom pathlib import Path@@ -359,6 +361,62 @@ def test_a_lettering_image_is_cut_again_without_generating(tmp_path, fake) -> Noassert (out / "logo.png").is_file()+def _ran(tmp_path: Path, **overrides) -> str:+ """`logo` 한 번 — 끝난 모양을 한 줄로(rc, 아니면 멈춘 까닭)."""+ try:+ return f"rc={_run(tmp_path, **overrides)}"+ except (SystemExit, OSError) as stopped:+ return f"{type(stopped).__name__}: {stopped}"+++def test_a_given_lettering_spelt_in_capitals_is_its_own_file_and_is_cut_again(tmp_path, fake) -> None:+ """In place again, by another spelling of the same file (a volume that ignores case): the input is the run's+ own `lettering.png`, kept and cut again, not removed as an earlier run's result."""+ fake(reads=(["ION"],))+ out = tmp_path / "logo"+ out.mkdir()+ lettering(key=GREEN_PAINTED, fill=(255, 214, 40), glow=(255, 120, 20), glow_strength=0.7).image.save(out / "lettering.png")+ if not (out / "LETTERING.png").exists():+ pytest.skip("대소문자를 가리는 볼륨 — 철자가 다르면 다른 파일이다")+ said = _ran(tmp_path, lettering=out / "LETTERING.png")+ assert said == "rc=0", f"제 lettering.png 를 다른 철자로 받은 입력을 지웠다 ({said})"+ assert (out / "logo.png").is_file()+++def test_a_mood_image_in_a_folder_of_the_old_working_name_is_never_touched(tmp_path, fake) -> None:+ fake(reads=(["ION"], ["ION"]))+ given = tmp_path / "logo" / ".logo-work" / "title.png"+ given.parent.mkdir(parents=True)+ _scene().save(given)+ read = hashlib.sha256(given.read_bytes()).hexdigest()+ said = _ran(tmp_path, mood=given)+ assert given.is_file() and hashlib.sha256(given.read_bytes()).hexdigest() == read, f"out 안 .logo-work 의 --mood 를 지웠다 ({said})"+ assert said == "rc=0", said+ left = sorted(p.name for p in (tmp_path / "logo").iterdir() if p.name.startswith("."))+ assert left == [".logo-work"], f"이 실행의 작업 폴더가 남았다: {left}"++[email protected](("flag", "place", "why"), [+ ("lettering", "logo.png", r"--lettering and logo\.png in --out-dir are the same file"),+ ("lettering", "logo.preview.png", r"--lettering and logo\.preview\.png in --out-dir are the same file"),+ ("mood", "lettering.png", r"--mood and lettering\.png in --out-dir are the same file"),+ ("mood", "logo.report.json", r"--mood and logo\.report\.json in --out-dir are the same file"),+])+def test_a_picture_given_as_a_file_the_run_writes_is_refused_before_anything_is_made(tmp_path, fake, flag, place, why) -> None:+ """Only `mood.png` for `--mood` and `lettering.png` for `--lettering` take back a picture the run made; any other+ file the run removes or writes would replace the picture it was given."""+ fake(reads=(["ION"], ["ION"]))+ out = tmp_path / "logo"+ out.mkdir()+ picture = (lettering(key=GREEN_PAINTED).image if flag == "lettering" else _scene())+ picture.save(out / place, format="PNG")+ read, before = hashlib.sha256((out / place).read_bytes()).hexdigest(), sorted(p.name for p in out.iterdir())+ said = _ran(tmp_path, **{flag: out / place})+ assert hashlib.sha256((out / place).read_bytes()).hexdigest() == read, f"--{flag} 로 받은 {place} 를 덮어썼다 ({said})"+ assert re.search(why, said), f"출력 파일인 입력을 거절하지 않았다 ({said})"+ assert sorted(p.name for p in out.iterdir()) == before, f"거절했는데 무엇이 생겼다 ({said})"++def test_a_mood_image_full_of_magenta_moves_the_lettering_to_the_green_key(tmp_path, fake) -> None:provider = fake(mood=_scene((220, 50, 200)))assert _run(tmp_path) == 0diff --git a/tests/gen/test_video_modes.py b/tests/gen/test_video_modes.pyindex 28cbf7b..ae63318 100644--- a/tests/gen/test_video_modes.py+++ b/tests/gen/test_video_modes.py@@ -6,6 +6,7 @@ run before any call, and the report's `mode` / `inputs`. No network — HTTP isfrom __future__ import annotationsimport json+import refrom pathlib import Pathimport pytest@@ -272,6 +273,30 @@ def test_edit_precheck_rejects_before_any_call(tmp_path: Path, build, seconds, eassert api.calls == [][email protected]("spelling", ["same", "capitals"])[email protected]("verb", ["extend", "edit"])+def test_the_result_is_never_published_over_the_clip_it_is_made_from(tmp_path: Path, verb: str, spelling: str) -> None:+ """`--out` naming the input clip — as given, or spelt in capitals on a volume that ignores case — is refused before+ any call: the result is published over `--out`, which would replace the clip."""+ given = MP4 + b"the input clip"+ api = _FakeApi(done={"status": "done", "video": {"url": "https://vidgen.x.ai/v/4.mp4", "duration": 5}, "model": "grok-imagine-video"})+ clip = tmp_path / "take.mp4"+ out = clip if spelling == "same" else tmp_path / "TAKE.MP4"+ request = _ext(tmp_path, video=clip, out=out) if verb == "extend" else _edit(tmp_path, video=clip, out=out)+ _clip(tmp_path, "take.mp4", given) # after the request: `_ext`/`_edit` write their own default clip, `in.mp4`+ if not out.exists():+ pytest.skip("대소문자를 가리는 볼륨 — 철자가 다르면 다른 파일이다")+ make = video.extend_video if verb == "extend" else video.edit_video+ try:+ make(request, probe=_probe(5.0, 10.0), **api.kw())+ said = "published"+ except SystemExit as refusal:+ said = str(refusal)+ assert clip.read_bytes() == given, f"video-{verb} 이 입력 클립 위에 결과를 내놓았다 ({said}, calls {len(api.calls)})"+ assert re.search(rf"video-{verb}: --video and --out are the same file", said), said+ assert api.calls == []++def test_edit_accepts_exactly_the_limit(tmp_path: Path) -> None:api = _FakeApi()video.edit_video(_edit(tmp_path), probe=lambda clip: 8.7, **api.kw())diff --git a/tests/qa/test_correction_loop_inputs_kept.py b/tests/qa/test_correction_loop_inputs_kept.pynew file mode 100644index 0000000..e10cceb--- /dev/null+++ b/tests/qa/test_correction_loop_inputs_kept.py@@ -0,0 +1,78 @@+# SPDX-License-Identifier: Apache-2.0+"""`correction-loop` 이 읽는 런을 지키는 계약 — 출력 폴더가 런과 겹치는 배치.++지키는 것 (구현이 아니라 계약):+ 1. 런 폴더(`--run-dir`)와 최선 후보의 복사가 따라가는 링크 하나하나(그 경로가 지나는 링크와 폴더까지)가+ `--out-dir` 와 같거나 그 안에 들면 아무것도 만들기 전에 거절한다 — 루프는 거기에 시도와 최선 후보를 쓰고+ 옛 최선 후보를 지운다+ 2. `--out-dir` 가 런 폴더 안이면(기본값 `<run-dir>/correction-loop`) 루프는 거기에 더할 뿐이고, 최선 후보의+ 복사는 그 폴더를 빼고 런만 복사한다 — 제 출력을 제 안에 복사하지 않는다+"""++from __future__ import annotations++import re+from pathlib import Path++import pytest++from tests.video.test_loop_inputs_kept import _digest, _state+from sprite_gen.qa.correction_loop import run_loop+++def _loop(run_dir: Path, out_dir: Path | None) -> str:+ """dry-run 한 번 — 끝난 모양을 한 줄로(끝나면 rc=0 과 최선 후보, 거절·실패면 그 문구)."""+ try:+ result = run_loop(run_dir, states="walk", out_dir=out_dir, dry_run=True)+ except (SystemExit, OSError) as stopped:+ return f"{type(stopped).__name__}: {str(stopped)[:300]}"+ return f"rc=0, best {result['preserved_best']}"+++def _readable(folder: Path) -> dict[str, str]:+ """런 폴더에서 열리는 모든 파일 — 상대 경로 → 바이트의 sha256(링크는 따라가 읽는다)."""+ return {p.relative_to(folder).as_posix(): _digest(p.read_bytes()) for p in sorted(folder.rglob("*")) if p.is_file()}+++# ── 1. 출력이 런과 겹치는 배치 — 만들기 전에 거절 ──────────────────────────────++def _run_is_the_best_candidate(root: Path, run: Path):+ (root / "loop").mkdir()+ run.rename(root / "loop" / "best-candidate")+ return root / "loop" / "best-candidate", root / "loop", r"--run-dir lies inside --out-dir"+++def _run_is_the_out_dir(root: Path, run: Path):+ return run, run, r"--run-dir and --out-dir are the same folder"+++def _a_link_in_the_run_into_the_best_candidate(root: Path, run: Path):+ (root / "loop" / "best-candidate").mkdir(parents=True)+ (root / "loop" / "best-candidate" / "notes.txt").write_bytes(b"what the run's link reads\n")+ (run / "notes.txt").symlink_to(root / "loop" / "best-candidate" / "notes.txt")+ return run, root / "loop", r"notes\.txt in --run-dir lies inside --out-dir"+++OVERLAPS = [_run_is_the_best_candidate, _run_is_the_out_dir, _a_link_in_the_run_into_the_best_candidate]++[email protected]("layout", OVERLAPS, ids=[layout.__name__.strip("_") for layout in OVERLAPS])+def test_the_loop_never_writes_over_or_deletes_the_run_it_reads(tmp_path, fixture_run_dir, layout) -> None:+ run_dir, out_dir, why = layout(tmp_path, fixture_run_dir)+ read, before = _readable(run_dir), _state(tmp_path)+ said = _loop(run_dir, out_dir)+ assert _readable(run_dir) == read, f"correction-loop 이 읽은 런을 지우거나 바꿨다 ({said})"+ assert re.search(why, said), f"런과 겹치는 출력을 거절하지 않았다 ({said})"+ assert _state(tmp_path) == before, f"거절했는데 무엇이 생기거나 바뀌었다 ({said})"+++# ── 2. 기본 out 은 런 안 — 더할 뿐, 복사는 그 폴더를 뺀다 ──────────────────────────++def test_the_default_out_dir_inside_the_run_is_left_out_of_the_best_candidates_copy(fixture_run_dir) -> None:+ read = _readable(fixture_run_dir)+ said = _loop(fixture_run_dir, None)+ assert said.startswith("rc=0"), f"기본 out(런 안)으로 돌지 못했다 ({said})"+ best = fixture_run_dir / "correction-loop" / "best-candidate"+ assert _readable(best) == read, "최선 후보가 런 그대로가 아니다 — 제 출력을 제 안에 복사했다"+ kept = {name: data for name, data in _readable(fixture_run_dir).items() if not name.startswith("correction-loop/")}+ assert kept == read, "런의 원래 파일이 바뀌었다"diff --git a/tests/video/test_follow_inspect.py b/tests/video/test_follow_inspect.pyindex 1407f36..87269a6 100644--- a/tests/video/test_follow_inspect.py+++ b/tests/video/test_follow_inspect.py@@ -141,6 +141,22 @@ def test_the_loop_directory_is_read_and_not_written(tmp_path):assert snapshot(loop_dir) == followed+def test_the_loop_directory_spelt_in_capitals_is_the_loop_directory(tmp_path):+ """On a volume that ignores case, `LOOP` is `loop`: an out dir spelt so is the loop directory, or inside it."""+ loop_dir = strip_dir(tmp_path/'loop')+ if not (tmp_path/'LOOP').exists():+ pytest.skip('대소문자를 가리는 볼륨 — 철자가 다르면 다른 폴더다')+ as_cut = snapshot(loop_dir)+ for inside in (tmp_path/'LOOP', tmp_path/'LOOP'/'inspect'):+ try:+ follow_inspect.inspect_loop(loop_dir, [CHEST], inside)+ said = 'written'+ except SystemExit as refusal:+ said = str(refusal)+ assert snapshot(loop_dir) == as_cut, f'{inside.name}: the inspection wrote into the loop directory ({said})'+ assert 'is in the loop directory; an inspection writes nothing there' in said, said++def test_inspecting_first_changes_nothing_video_follow_writes(tmp_path):inspected, plain = strip_dir(tmp_path/'inspected'), strip_dir(tmp_path/'plain')inspect(inspected, [CHEST], tmp_path/'out', on_fold='lower')diff --git a/tests/video/test_frames_inputs_kept.py b/tests/video/test_frames_inputs_kept.pynew file mode 100644index 0000000..1a5ed0f--- /dev/null+++ b/tests/video/test_frames_inputs_kept.py@@ -0,0 +1,116 @@+# SPDX-License-Identifier: Apache-2.0+"""`video-frames` 가 읽는 클립과 스틸을 지키는 계약 — 출력 폴더가 입력을 품거나 입력과 겹치는 배치.++지키는 것 (구현이 아니라 계약):+ 1. 실행이 갈아 끼우거나 지우는 것(`raw/` 의 프레임, `keyed/`, `keyed.refused/`, 보고서, `--source-manifest`)과+ 입력(`--clip`, `--reference`, 그 경로가 지나는 링크와 폴더)이 같거나, 입력이 그 안에 들거나, 입력 경로가 그 안의+ 항목을 지나면 아무것도 만들기 전에 거절한다 — 링크로 닿아도, 대소문자만 다른 철자여도 같은 파일이다+ 2. 키잉의 작업 폴더는 이 실행만의 새 이름이다 — out 안 옛 고정 이름 `.keyed.work` 의 폴더는 입력이든 남의+ 것이든 건드리지 않는다+"""++from __future__ import annotations++import re+import shutil+import subprocess+from pathlib import Path++import pytest+from PIL import Image++from tests.video.test_loop_inputs_kept import _read, _state+from tests.video.test_source_restoration import frames as figure_frames+from sprite_gen.video.frames import run_frames++JUNK = b"\x00\x00\x00\x18ftypisom" + b"\x00" * 64 # 클립 이름의 파일 — 거절이 먼저라 ffmpeg 가 읽지 않는다++[email protected](scope="module")+def clip(tmp_path_factory) -> Path:+ """초록 키 위 합성 인물 12 프레임의 mp4 (`test_source_restoration` 의 그림, 같은 ffmpeg 레시피)."""+ if not shutil.which("ffmpeg"):+ pytest.skip("ffmpeg required")+ made = tmp_path_factory.mktemp("clip")+ for k, f in enumerate(figure_frames()):+ canvas = Image.new("RGB", f.size, (0, 255, 0))+ canvas.paste(f, mask=f.getchannel("A"))+ canvas.save(made / f"frame-{k:04}.png")+ subprocess.run(["ffmpeg", "-v", "error", "-framerate", "24", "-i", str(made / "frame-%04d.png"), "-c:v", "libx264",+ "-pix_fmt", "yuv420p", str(made / "clip.mp4")], check=True)+ return made / "clip.mp4"+++def _frames(root: Path, clip: Path, **kwargs) -> str:+ """`video-frames` 한 번 — 끝난 모양을 한 줄로(통과면 rc=0, 거절·실패면 그 문구)."""+ args = {"key": "green", "allow_edge_contact": False, "report_path": None, **kwargs}+ try:+ return f"rc=0, keyed {run_frames(clip, root / 'out', **args)['keyed_dir']}"+ except SystemExit as refusal:+ return str(refusal)+++# ── 1. 출력이 입력과 겹치는 배치 — 만들기 전에 거절 ──────────────────────────────++def _clip_in_keyed(root: Path, clip: Path):+ (root / "out" / "keyed").mkdir(parents=True)+ (root / "out" / "keyed" / "c.mp4").write_bytes(JUNK)+ return root / "out" / "keyed" / "c.mp4", {}, r"--clip lies inside keyed in --out-dir"+++def _clip_linked_into_keyed(root: Path, clip: Path):+ (root / "out" / "keyed").mkdir(parents=True)+ (root / "out" / "keyed" / "c.mp4").write_bytes(JUNK)+ (root / "in.mp4").symlink_to(root / "out" / "keyed" / "c.mp4")+ return root / "in.mp4", {}, r"--clip lies inside keyed in --out-dir"+++def _reference_in_keyed(root: Path, clip: Path):+ (root / "out" / "keyed").mkdir(parents=True)+ Image.new("RGB", (8, 8), (0, 255, 0)).save(root / "out" / "keyed" / "still.png")+ (root / "c.mp4").write_bytes(JUNK)+ return (root / "c.mp4", {"reference": root / "out" / "keyed" / "still.png"},+ r"--reference lies inside keyed in --out-dir")+++def _report_is_the_clip(root: Path, clip: Path):+ shutil.copyfile(clip, root / "c.mp4")+ return root / "c.mp4", {"report_path": root / "c.mp4"}, r"--clip and --report are the same file"+++def _source_manifest_spelt_in_capitals(root: Path, clip: Path):+ shutil.copyfile(clip, root / "c.mp4")+ Image.new("RGB", (8, 8), (0, 255, 0)).save(root / "still.png")+ if not (root / "C.MP4").exists():+ pytest.skip("대소문자를 가리는 볼륨 — 철자가 다르면 다른 파일이다")+ return (root / "c.mp4", {"reference": root / "still.png", "source_manifest": root / "C.MP4"},+ r"--clip and --source-manifest are the same file")+++OVERLAPS = [_clip_in_keyed, _clip_linked_into_keyed, _reference_in_keyed, _report_is_the_clip,+ _source_manifest_spelt_in_capitals]++[email protected]("layout", OVERLAPS, ids=[layout.__name__.strip("_") for layout in OVERLAPS])+def test_frames_never_write_over_or_delete_the_clip_or_still_they_read(tmp_path, clip, layout) -> None:+ given, kwargs, why = layout(tmp_path, clip)+ inputs = [given, *([kwargs["reference"]] if "reference" in kwargs else [])]+ read, before = _read(inputs), _state(tmp_path)+ said = _frames(tmp_path, given, **kwargs)+ assert _read(inputs) == read, f"video-frames 가 읽은 입력을 지우거나 바꿨다 ({said})"+ assert re.search(why, said), f"입력과 겹치는 출력을 거절하지 않았다 ({said})"+ assert _state(tmp_path) == before, f"거절했는데 무엇이 생기거나 바뀌었다 ({said})"+++# ── 2. 옛 고정 작업 폴더 이름 — 이 실행의 것이 아니면 건드리지 않는다 ─────────────────++def test_a_folder_of_the_old_working_name_beside_keyed_is_never_touched(tmp_path, clip) -> None:+ work = tmp_path / "out" / ".keyed.work"+ work.mkdir(parents=True)+ shutil.copyfile(clip, work / "c.mp4")+ read = _read([work / "c.mp4"])+ said = _frames(tmp_path, work / "c.mp4")+ assert _read([work / "c.mp4"]) == read, f"out 안 .keyed.work 의 입력 클립을 지웠다 ({said})"+ assert said.startswith("rc=0"), said+ left = sorted(p.name for p in (tmp_path / "out").iterdir() if p.name.startswith("."))+ assert left == [".keyed.work"], f"이 실행의 작업 폴더가 남았다: {left}"diff --git a/tests/video/test_loop_inputs_kept.py b/tests/video/test_loop_inputs_kept.pynew file mode 100644index 0000000..8982356--- /dev/null+++ b/tests/video/test_loop_inputs_kept.py@@ -0,0 +1,213 @@+# SPDX-License-Identifier: Apache-2.0+"""`video-loop` 과 `video-stop` 이 읽는 프레임을 지키는 계약 — 출력 폴더가 입력을 품거나 입력과 겹치는 배치.++지키는 것 (구현이 아니라 계약):+ 1. 컷이 갈아 끼우거나 지우는 것(`cycle/`, `cycle.source/`, `cycle.refused/`, `follow.source.png`, strip·GIF·WebP,+ 보고서)과 입력(`--frames-dir`, 그 안에서 찾은 프레임 하나하나, 그 경로가 지나는 링크와 폴더)이 같거나, 입력이+ 그 안에 들거나, 입력 경로가 그 안의 항목을 지나면 프레임 하나 읽기 전에 거절한다 — 링크로 닿아도, 대소문자만+ 다른 철자여도 같은 항목이다. `--out-dir` 자체는 비교하지 않는다(프레임은 흔히 그 안 `keyed/` 에 있다)+ 2. 실행이 쓰고 지우는 임시 폴더는 이 실행만의 새 이름이다 — out 안 `.webp-frames`, `.gait-fallback-frames`+ 같은 옛 고정 이름의 폴더는 입력이든 남의 것이든 건드리지 않는다+ 3. `video-stop` 도 같다: `--frames-dir` 와 그 프레임, `--loop` 와 그 옆 strip 은 stop 이 쓰는 파일과 보고서가+ 아니다+"""++from __future__ import annotations++import hashlib+import re+import shutil+from pathlib import Path++import pytest++from tests.frames.test_unpack_atlas_publish import _tree+from tests.video import test_stop as runs+from tests.video.test_idle_still import _still_frames+from sprite_gen.video import loop as loop_mod+from sprite_gen.video import stop as stop_mod++[email protected](scope="module")+def still(tmp_path_factory) -> Path:+ """한 번 만든 서 있는 몸 48 프레임(`test_idle_still`) — 배치마다 복사해 쓴다."""+ return _still_frames(tmp_path_factory.mktemp("still"))+++def _place(still: Path, folder: Path) -> Path:+ shutil.copytree(still, folder)+ return folder+++def _loop(frames_dir: Path, out_dir: Path, **kwargs) -> dict:+ return loop_mod.run_loop(frames_dir, out_dir, fps=24.0, state="idle", min_len=None, max_len=None, n_out=None,+ seam_max=loop_mod.SEAM_RATIO_MAX, name="idle", cycle_mode="pinned",+ **{"report_path": None, **kwargs})+++def _digest(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++def _read(paths: list[Path]) -> dict[str, str | None]:+ """입력 경로(받은 철자 그대로)마다 지금 열리는 바이트의 sha256 — 열리지 않으면 None. 바이트 대신 digest 를 견주어+ 실패한 단언이 큰 바이트의 차이를 그리지 않는다."""+ got: dict[str, str | None] = {}+ for path in paths:+ try:+ got[str(path)] = _digest(path.read_bytes())+ except OSError:+ got[str(path)] = None+ return got+++def _state(folder: Path) -> dict[str, object]:+ """`_tree` 의 파일 바이트를 sha256 으로 — 폴더 안 모든 것."""+ return {name: _digest(got) if isinstance(got, bytes) else got for name, got in _tree(folder).items()}+++# ── 1. 출력이 입력과 겹치는 배치 — 만들기 전에 거절 ──────────────────────────────++def _frames_in_cycle_source(root: Path, still: Path):+ _place(still, root / "out" / "cycle.source" / "keyed")+ return root / "out" / "cycle.source" / "keyed", root / "out", {}, r"--frames-dir lies inside cycle\.source in --out-dir"+++def _frames_are_the_cycle(root: Path, still: Path):+ _place(still, root / "out" / "cycle")+ return root / "out" / "cycle", root / "out", {}, r"--frames-dir and cycle in --out-dir are the same folder"+++def _frames_are_cycle_refused(root: Path, still: Path):+ _place(still, root / "out" / "cycle.refused")+ return root / "out" / "cycle.refused", root / "out", {}, r"--frames-dir and cycle\.refused in --out-dir are the same folder"+++def _frames_dir_links_to_cycle_source(root: Path, still: Path):+ _place(still, root / "out" / "cycle.source")+ (root / "in").symlink_to(root / "out" / "cycle.source", target_is_directory=True)+ return root / "in", root / "out", {}, r"--frames-dir and cycle\.source in --out-dir are the same folder"+++def _a_frame_linked_into_cycle_source(root: Path, still: Path):+ keyed = _place(still, root / "keyed")+ (root / "out" / "cycle.source").mkdir(parents=True)+ (keyed / "frame-0000.png").rename(root / "out" / "cycle.source" / "frame-0000.png")+ (keyed / "frame-0000.png").symlink_to(root / "out" / "cycle.source" / "frame-0000.png")+ return keyed, root / "out", {}, r"frame-0000\.png in --frames-dir lies inside cycle\.source in --out-dir"+++def _frames_through_a_link_in_cycle_source(root: Path, still: Path):+ _place(still, root / "elsewhere" / "keyed")+ (root / "out" / "cycle.source").mkdir(parents=True)+ (root / "out" / "cycle.source" / "hop").symlink_to(root / "elsewhere", target_is_directory=True)+ return (root / "out" / "cycle.source" / "hop" / "keyed", root / "out", {},+ r"--frames-dir goes through .*hop, inside cycle\.source in --out-dir")+++def _out_spelt_in_capitals(root: Path, still: Path):+ _place(still, root / "out" / "cycle.source" / "keyed")+ if not (root / "OUT").exists():+ pytest.skip("대소문자를 가리는 볼륨 — 철자가 다르면 다른 폴더다")+ return root / "out" / "cycle.source" / "keyed", root / "OUT", {}, r"--frames-dir lies inside cycle\.source in --out-dir"+++def _report_is_a_frame(root: Path, still: Path):+ keyed = _place(still, root / "keyed")+ return (keyed, root / "out", {"report_path": keyed / "frame-0003.png"},+ r"frame-0003\.png in --frames-dir and --report are the same file")+++OVERLAPS = [_frames_in_cycle_source, _frames_are_the_cycle, _frames_are_cycle_refused, _frames_dir_links_to_cycle_source,+ _a_frame_linked_into_cycle_source, _frames_through_a_link_in_cycle_source, _out_spelt_in_capitals,+ _report_is_a_frame]++[email protected]("layout", OVERLAPS, ids=[layout.__name__.strip("_") for layout in OVERLAPS])+def test_a_cut_never_writes_over_or_deletes_the_frames_it_reads(tmp_path, still, layout) -> None:+ frames_dir, out_dir, kwargs, why = layout(tmp_path, still)+ inputs = sorted(frames_dir.glob("*.png"))+ read, before = _read(inputs), _state(tmp_path)+ try:+ said = f"rc=0, cycle {_loop(frames_dir, out_dir, **kwargs)['cycle']['kind']}"+ except SystemExit as refusal:+ said = str(refusal)+ assert _read(inputs) == read, f"video-loop 이 읽은 프레임을 지우거나 바꿨다 ({said})"+ assert re.search(why, said), f"입력과 겹치는 출력을 거절하지 않았다 ({said})"+ assert _state(tmp_path) == before, f"거절했는데 무엇이 생기거나 바뀌었다 ({said})"+++# ── 2. 옛 고정 임시 이름 — 이 실행의 것이 아니면 건드리지 않는다 ─────────────────────+[email protected]("scratch", [".webp-frames", ".gait-fallback-frames"])+def test_a_folder_of_an_old_scratch_name_in_the_out_dir_is_never_touched(tmp_path, still, scratch) -> None:+ frames_dir = _place(still, tmp_path / "out" / scratch)+ inputs = sorted(frames_dir.glob("*.png"))+ read = _read(inputs)+ try:+ said = f"rc=0, cycle {_loop(frames_dir, tmp_path / 'out')['cycle']['kind']}"+ except SystemExit as refusal:+ said = str(refusal)+ assert _read(inputs) == read, f"out 안 {scratch} 의 입력 프레임을 지우거나 바꿨다 ({said})"+ assert sorted(p.name for p in frames_dir.iterdir()) == [p.name for p in inputs], f"{scratch} 에 무엇을 썼다 ({said})"+ assert said.startswith("rc=0"), said+ left = [p.name for p in (tmp_path / "out").iterdir() if p.name.startswith(".") and p.name != scratch]+ assert left == [], f"이 실행의 임시 폴더가 남았다: {left}"+++# ── 3. video-stop ───────────────────────────────────────────────────────────+[email protected](scope="module")+def run_loop_cut(tmp_path_factory) -> tuple[Path, Path]:+ """한 번 만든 달리기 클립의 keyed 프레임과 그 루프(`test_stop` 의 합성 러너) — 배치마다 복사해 쓴다."""+ made = tmp_path_factory.mktemp("run")+ keyed, run_from = runs.clip(made)+ return keyed, runs.cut(made, keyed, run_from + runs.PERIOD)+++def _stop_copy(root: Path, made: tuple[Path, Path], keyed_at: Path) -> tuple[Path, Path]:+ keyed, meta = made+ shutil.copytree(keyed, keyed_at)+ shutil.copytree(meta.parent, root / "loop")+ return keyed_at, root / "loop" / meta.name+++def test_a_stop_never_writes_into_a_frames_folder_of_the_old_scratch_name(tmp_path, run_loop_cut) -> None:+ keyed, meta = _stop_copy(tmp_path, run_loop_cut, tmp_path / "stop" / ".webp-frames")+ inputs = sorted(keyed.glob("*.png"))+ read = _read(inputs)+ try:+ said = f"rc=0, {stop_mod.make_stop(keyed, meta, tmp_path / 'stop')['status']}"+ except SystemExit as refusal:+ said = str(refusal)+ assert _read(inputs) == read, f"video-stop 이 out 안 .webp-frames 의 입력 프레임을 지우거나 바꿨다 ({said})"+ assert sorted(p.name for p in keyed.iterdir()) == [p.name for p in inputs], f".webp-frames 에 무엇을 썼다 ({said})"+ assert said == "rc=0, passed", said+++def _stop_over_its_loop(root: Path, made: tuple[Path, Path]):+ keyed, meta = _stop_copy(root, made, root / "keyed")+ return keyed, meta, root / "loop", {"name": "run"}, r"--loop and run\.strip\.json in --out-dir are the same file"+++def _stop_report_is_a_frame(root: Path, made: tuple[Path, Path]):+ keyed, meta = _stop_copy(root, made, root / "keyed")+ return (keyed, meta, root / "stop", {"report_path": keyed / "frame-0002.png"},+ r"frame-0002\.png in --frames-dir and --report are the same file")+++STOP_OVERLAPS = [_stop_over_its_loop, _stop_report_is_a_frame]++[email protected]("layout", STOP_OVERLAPS, ids=[layout.__name__.strip("_") for layout in STOP_OVERLAPS])+def test_a_stop_never_writes_over_what_it_reads(tmp_path, run_loop_cut, layout) -> None:+ keyed, meta, out_dir, kwargs, why = layout(tmp_path, run_loop_cut)+ inputs = [*sorted(keyed.glob("*.png")), meta, meta.with_name(meta.name[: -len(".json")] + ".png")]+ read, before = _read(inputs), _state(tmp_path)+ try:+ said = f"rc=0, {stop_mod.make_stop(keyed, meta, out_dir, **kwargs)['status']}"+ except SystemExit as refusal:+ said = str(refusal)+ assert _read(inputs) == read, f"video-stop 이 읽은 것을 덮어썼다 ({said})"+ assert re.search(why, said), f"입력과 겹치는 출력을 거절하지 않았다 ({said})"+ assert _state(tmp_path) == before, f"거절했는데 무엇이 생기거나 바뀌었다 ({said})"