Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

test(packaging,release,spec,qa,serve): drop duplicate tests; one loop per package scan, fewer NumPy-gate launches

Soohong Kim649b0538537f
diff --git a/tests/packaging/test_curation_asset_packaging.py b/tests/packaging/test_curation_asset_packaging.py
index 9606c8c..d57ea6c 100644
--- a/tests/packaging/test_curation_asset_packaging.py
+++ b/tests/packaging/test_curation_asset_packaging.py
@@ -10,8 +10,8 @@ checked here against what is actually on disk instead.
Checked against the build, not against the declaration string: reading the patterns and
asking "does this asset look like one of them" is how the first version of this guard passed
while the wheel was already dropping files (`fnmatch`'s `*` crosses `/`, setuptools' does
-not). Both tests below therefore go through an expansion that packaging actually performs —
-`glob(recursive=True)` for the always-on one, a real wheel build for the other.
+not). The tests below therefore read a real wheel built from this tree. setuptools is a
+declared test dependency, so the wheel fixture skipping fails the lane rather than passing it.
The same reasoning covers the subprocess routes (`/api/compose`, `/api/interpolate`,
`/api/reroll`, `/api/export`, `/api/export-gif`): naming `scripts/<tool>.py` there would
@@ -23,9 +23,7 @@ to it.
from __future__ import annotations
import ast
-import glob
import importlib.util
-import os
import re
import shutil
import subprocess
@@ -39,45 +37,15 @@ from sprite_gen.serve.serve_curation import CURATOR_DIR
ROOT = Path(__file__).resolve().parent.parent.parent
PACKAGE_DIR = ROOT / "sprite_gen"
-PYPROJECT = (ROOT / "pyproject.toml").read_text(encoding="utf-8")
# `scripts/<anything>.py` named as a path, not as prose.
SCRIPT_PATH = re.compile(r"(?:^|/)scripts/[^/]+\.py$")
-def _declared_package_data() -> list[str]:
- """The `sprite_gen = [...]` patterns under `[tool.setuptools.package-data]`.
-
- Read the package-data declaration directly, without importing the package.
- """
- section = re.search(
- r"(?ms)^\[tool\.setuptools\.package-data\]\s*$(.*?)(?=^\[|\Z)", PYPROJECT)
- assert section, "pyproject.toml is missing [tool.setuptools.package-data]"
- entry = re.search(r"(?ms)^sprite_gen\s*=\s*\[(.*?)\]", section.group(1))
- assert entry, "[tool.setuptools.package-data] declares nothing for sprite_gen"
- return re.findall(r'"([^"]+)"', entry.group(1))
-
-
def _curator_assets() -> list[Path]:
return sorted(p for p in CURATOR_DIR.rglob("*") if p.is_file())
-def _collected_package_data() -> set[str]:
- """The files the declared patterns actually collect, expanded the way the build does.
-
- setuptools' `build_py.find_data_files` runs each pattern through `glob(..., recursive=True)`
- rooted at the package source dir and keeps the regular files. That expansion is the whole
- contract: in it a lone `*` stops at a directory boundary (`**` is what descends), which is
- exactly where a hand-listed pattern silently loses a nested asset.
- """
- collected: set[str] = set()
- for pattern in _declared_package_data():
- for hit in glob.glob(os.path.join(glob.escape(str(PACKAGE_DIR)), pattern), recursive=True):
- if os.path.isfile(hit):
- collected.add(Path(hit).relative_to(PACKAGE_DIR).as_posix())
- return collected
-
-
_BUILD_WHEEL = (
"import sys\n"
"from setuptools import build_meta\n"
@@ -144,17 +112,6 @@ def test_the_spa_has_exactly_one_home() -> None:
"two curator trees exist — whichever one the server does not read will rot silently")
-def test_the_package_data_patterns_collect_every_curator_asset() -> None:
- """Not "does the asset look declared" but "does the declaration pick it up"."""
- on_disk = {p.relative_to(PACKAGE_DIR).as_posix() for p in _curator_assets()}
- missing = sorted(on_disk - _collected_package_data())
-
- assert not missing, (
- f"{len(missing)} SPA asset(s) survive no package-data pattern "
- f"{_declared_package_data()} — {missing[:5]} — so they are absent from the wheel and "
- f"404 for anyone who installed sprite-gen instead of cloning it")
-
-
def test_the_built_wheel_carries_every_curator_asset(wheel_names: set[str]) -> None:
"""The declaration is a claim; the wheel is the fact. Compare the fact to the disk."""
on_disk = {f"sprite_gen/serve/curator/{p.relative_to(CURATOR_DIR).as_posix()}"
@@ -199,16 +156,20 @@ def test_the_spa_asks_only_for_assets_that_exist() -> None:
assert not missing, f"index.html references assets that are not in the SPA tree: {missing}"
[email protected]("module", sorted(p.relative_to(ROOT).as_posix()
- for p in PACKAGE_DIR.rglob("*.py")))
-def test_the_package_never_reaches_into_the_scripts_wrappers(module: str) -> None:
- tree = ast.parse((ROOT / module).read_text(encoding="utf-8"))
- offenders = [s for s in _string_constants(tree) if s == "scripts" or SCRIPT_PATH.search(s)]
+def test_the_package_never_reaches_into_the_scripts_wrappers() -> None:
+ modules = sorted(PACKAGE_DIR.rglob("*.py"))
+ assert modules, f"no package modules found under {PACKAGE_DIR} — the scan would pass vacuously"
+ offenders: list[str] = []
+ for path in modules:
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ hits = [s for s in _string_constants(tree) if s == "scripts" or SCRIPT_PATH.search(s)]
+ if hits:
+ offenders.append(f"{path.relative_to(ROOT).as_posix()}: {hits}")
assert not offenders, (
- f"{module} builds a path into scripts/ ({offenders}) — those wrappers are not "
- f"installed, so this works in a checkout and fails in an install. Shell out with "
- f"`-m sprite_gen.<module>` instead.")
+ "these modules build a path into scripts/ — those wrappers are not installed, so this "
+ "works in a checkout and fails in an install. Shell out with `-m sprite_gen.<module>` "
+ "instead:\n" + "\n".join(offenders))
def test_built_wheel_carries_browser_audio_player(wheel_names: set[str]) -> None:
diff --git a/tests/packaging/test_curation_cli_entrypoint.py b/tests/packaging/test_curation_cli_entrypoint.py
index 17a1167..ad08cad 100644
--- a/tests/packaging/test_curation_cli_entrypoint.py
+++ b/tests/packaging/test_curation_cli_entrypoint.py
@@ -17,13 +17,6 @@ from sprite_gen.serve import serve_curation
ROOT = Path(__file__).resolve().parents[2]
-def test_curation_subcommand_reuses_the_webview_declaration() -> None:
- """Identity, not equality: the CLI table points at the webview's own functions."""
- _description, add_args, run_fn = cli.COMMANDS["curation"]
-
- assert add_args is serve_curation.add_arguments
- assert run_fn is serve_curation.run
-
def test_every_launch_form_exposes_the_same_flags() -> None:
subcommand = _help_options("-m", "sprite_gen.cli", "curation")
diff --git a/tests/packaging/test_entrypoint_interpreter.py b/tests/packaging/test_entrypoint_interpreter.py
index 76d2b20..c4a9eab 100644
--- a/tests/packaging/test_entrypoint_interpreter.py
+++ b/tests/packaging/test_entrypoint_interpreter.py
@@ -77,3 +77,7 @@ def test_skill_md_owns_the_interpreter_rule() -> None:
# missing venv is created or fails loudly — never quietly swapped for python3.
assert "폴백 금지" in text, (
"SKILL.md must keep the no-fallback clause for the interpreter rule")
+ # An agent that hits the missing-NumPy traceback (tests/packaging/test_numpy_dependency_gate.py)
+ # reads SKILL.md next; what a NumPy-less interpreter does lives there too.
+ assert "NumPy 가 없는 인터프리터" in text, (
+ "SKILL.md lost the clause telling agents what a NumPy-less interpreter does")
diff --git a/tests/packaging/test_numpy_dependency_gate.py b/tests/packaging/test_numpy_dependency_gate.py
index f0139da..7b1c079 100644
--- a/tests/packaging/test_numpy_dependency_gate.py
+++ b/tests/packaging/test_numpy_dependency_gate.py
@@ -12,8 +12,9 @@ slower" is a failure of this contract rather than an outcome it tolerates.
The absence is simulated with a `sitecustomize.py` on `PYTHONPATH` that installs
a meta-path finder raising `ModuleNotFoundError` for `numpy`, so the real
documented command line runs on the real interpreter and only the one import
-disappears. Every failing case is paired with the same command unblocked, so a
-green run cannot come from an entrypoint that was already broken.
+disappears. Every failing case is paired with the same command unblocked (here,
+or by a real run in another test), so a green run cannot come from an
+entrypoint that was already broken.
Two assertions carry this past the point where the vectorized code actually
lands. The runtime ones hold whatever `sprite_gen/frames/extract.py` does, because the
@@ -121,6 +122,33 @@ def _entry_scripts() -> list[Path]:
COMMANDS = {"package import": ["-c", "import sprite_gen"], "cli module": ["-m", "sprite_gen.cli", "--help"]}
COMMANDS.update({path.name: [str(path), "--help"] for path in _entry_scripts()})
+# The gate fires once, at `import sprite_gen` (`sprite_gen/__init__.py` -> `_deps.py`), and every
+# wrapper imports the package at load; `test_numpy_is_imported_in_exactly_one_shipped_module` rules
+# out any other NumPy import. So one probe per register stands for all of them: the bare package
+# import, the package CLI, and one `scripts/` wrapper.
+_BLOCKED_PROBES = ("package import", "cli module", "extract_sprite_row_frames.py")
+
+# Wrappers other tests already launch for real with NumPy present (test_pipeline_smoke.py,
+# tests/qa/test_inspect_score_loop.py, tests/serve/test_curation_view_contract.py and the
+# `*_cli_entrypoint` launch-form tests): an end-to-end run there is a stronger control than
+# `--help` exiting 0 here.
+_LAUNCHED_ELSEWHERE = {
+ "prepare_sprite_run.py",
+ "extract_sprite_row_frames.py",
+ "compose_sprite_atlas.py",
+ "compose_selected_cycle.py",
+ "export_curated_pngs.py",
+ "preview_animation.py",
+ "compose_sprite_gif.py",
+ "inspect_sprite_run.py",
+ "score_sprite_run.py",
+ "run_correction_loop.py",
+ "unpack_atlas_run.py",
+ "serve_curation.py",
+ "compose_layers.py",
+ "recolor.py",
+}
+
def _run(args: list[str], *, numpy_blocked: bool, tmp_path: Path) -> subprocess.CompletedProcess:
env = dict(os.environ)
@@ -140,7 +168,7 @@ def test_the_scanned_entrypoints_are_the_real_ones() -> None:
f"documented entrypoints missing from the scan: {sorted(_CORE_ENTRYPOINTS - found)}")
[email protected]("register", sorted(COMMANDS))
[email protected]("register", _BLOCKED_PROBES)
def test_entrypoint_without_numpy_fails_loudly_with_the_install_path(
register: str, tmp_path: Path
) -> None:
@@ -161,7 +189,7 @@ def test_entrypoint_without_numpy_fails_loudly_with_the_install_path(
f"{register} failure does not spell out the install command for the skill venv:\n{stderr}")
[email protected]("register", sorted(COMMANDS))
[email protected]("register", sorted(set(COMMANDS) - _LAUNCHED_ELSEWHERE))
def test_the_same_entrypoint_succeeds_when_numpy_is_importable(
register: str, tmp_path: Path
) -> None:
@@ -191,11 +219,3 @@ def test_the_gate_hands_back_the_real_numpy() -> None:
assert _deps.np is _deps.numpy
assert getattr(_deps.np, "__name__", None) == "numpy"
-
-
-def test_skill_md_documents_the_missing_numpy_behavior() -> None:
- """An agent that hits the traceback reads SKILL.md next; the rule lives there."""
- text = (ROOT / "SKILL.md").read_text(encoding="utf-8")
-
- assert "NumPy 가 없는 인터프리터" in text, (
- "SKILL.md lost the clause telling agents what a NumPy-less interpreter does")
diff --git a/tests/packaging/test_package_surface.py b/tests/packaging/test_package_surface.py
index d4d0dab..46fe233 100644
--- a/tests/packaging/test_package_surface.py
+++ b/tests/packaging/test_package_surface.py
@@ -5,10 +5,8 @@ from __future__ import annotations
import ast
import importlib
-import re
import subprocess
import sys
-from importlib import metadata
from pathlib import Path
import pytest
@@ -44,19 +42,6 @@ PACKAGE_RUN_MODULES = [
"batch",
]
-CLI_HELPERS = [
- "_parse_frame_order",
- "_parse_frames",
- "_parse_grid",
-]
-
-
-def _read_skill_version() -> str:
- text = (ROOT / "SKILL.md").read_text(encoding="utf-8")
- match = re.search(r"(?m)^version:\s*([^\s#]+)\s*$", text)
- assert match, "SKILL.md frontmatter is missing version:"
- return match.group(1)
-
@pytest.fixture
def import_probe():
@@ -98,19 +83,20 @@ def import_probe():
sys.modules.pop(module_path, None)
[email protected]("module_name", PACKAGE_RUN_MODULES)
-def test_mcp_import_surface_modules_expose_callable_run(module_name: str, import_probe) -> None:
- module_path = "sprite_gen.gen" if module_name == "gen" else qualified(module_name)
- module = import_probe(module_path)
-
- assert callable(getattr(module, "run", None)), f"{module_path}.run must be callable"
-
-
[email protected]("helper_name", CLI_HELPERS)
-def test_cli_parser_helpers_exist(helper_name: str) -> None:
- cli = importlib.import_module("sprite_gen.cli")
+def test_mcp_import_surface_modules_expose_callable_run(import_probe) -> None:
+ offenders: list[str] = []
+ for module_name in PACKAGE_RUN_MODULES:
+ module_path = "sprite_gen.gen" if module_name == "gen" else qualified(module_name)
+ try:
+ module = import_probe(module_path)
+ except Exception as exc: # one broken module must not hide the rest
+ offenders.append(f"{module_path} (import failed: {type(exc).__name__}: {exc})")
+ continue
+ if not callable(getattr(module, "run", None)):
+ offenders.append(f"{module_path} (no callable run)")
- assert callable(getattr(cli, helper_name, None)), f"sprite_gen.cli.{helper_name} must be callable"
+ assert not offenders, "every MCP import-surface module must import and expose a callable run:\n" + \
+ "\n".join(offenders)
def _sibling_module_names() -> set[str]:
@@ -169,21 +155,6 @@ def test_scripts_wrappers_reexport_their_package_module() -> None:
proc = subprocess.run([sys.executable, "-c", probe], cwd=ROOT, capture_output=True, text=True)
assert proc.returncode == 0, f"scripts/serve_curation.py stopped re-exporting the impl:\n{proc.stderr}"
-
- helped = subprocess.run(
- [sys.executable, str(ROOT / "scripts" / "serve_curation.py"), "--help"],
- cwd=ROOT, capture_output=True, text=True)
-
- assert helped.returncode == 0, helped.stderr
- assert "--run-dir" in helped.stdout, (
- f"the wrapper no longer runs the entrypoint — `python scripts/serve_curation.py` is a "
- f"documented launch command:\n{helped.stdout}")
-
-
-def test_installed_distribution_version_matches_skill_frontmatter() -> None:
- try:
- installed_version = metadata.version("sprite-gen")
- except metadata.PackageNotFoundError:
- pytest.skip("sprite-gen distribution metadata is only available after editable/package install")
-
- assert installed_version == _read_skill_version()
+ # That the wrapper also runs the entrypoint (`python scripts/serve_curation.py` is a
+ # documented launch command) is held by the wrapper leg of
+ # test_curation_cli_entrypoint.py::test_every_launch_form_exposes_the_same_flags.
diff --git a/tests/packaging/test_pipeline_smoke.py b/tests/packaging/test_pipeline_smoke.py
index 60330cb..637fe13 100644
--- a/tests/packaging/test_pipeline_smoke.py
+++ b/tests/packaging/test_pipeline_smoke.py
@@ -145,27 +145,6 @@ def test_failed_subset_reextract_preserves_prior_generation(fixture_run_dir: Pat
assert run_script("compose_sprite_atlas.py", "--run-dir", str(run)).returncode == 0
-def test_failed_reextract_signal_reaches_correction_loop_consumer(fixture_run_dir: Path) -> None:
- """The automatic correction loop drives error-driven regeneration off inspect's per-state
- errors. A failed RE-extract keeps the prior good frames byte-intact, so inspect's own
- frame-count check sees nothing wrong — the ONLY channel for 'this state's re-extract failed,
- and why' is extract-failure.json (frames/ stays complete-only). This proves the strict-
- atomicity fix keeps that signal wired, so auto-correction never goes blind."""
- from sprite_gen.qa.inspect import _manifest_state_notes
-
- run = fixture_run_dir
- assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
- target = sorted(json.loads((run / "sprite-request.json").read_text())["states"])[0]
-
- (run / "raw" / f"{target}.png").unlink() # break only this state's raw strip
- assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run), "--states", target).returncode == 1
-
- assert (run / "frames" / target).is_dir() # prior good frames intact (re-extract)
- assert (run / "extract-failure.json").is_file() # signal recorded OUTSIDE frames/
- _row, errors, _warnings = _manifest_state_notes(run, target)
- assert errors and all(e.startswith(f"{target}:") for e in errors), errors # consumer reads it
-
-
def test_successful_extract_clears_prior_failure_evidence(fixture_run_dir: Path) -> None:
"""A success resolves any prior failure: extract-failure.json must be removed so inspect and
the correction loop never re-flag a now-good state with a stale signal (Consistency)."""
@@ -265,12 +244,12 @@ def test_commit_generation_rolls_back_both_surfaces_on_evidence_failure(tmp_path
# Broken canonical records that must all fail loud, NOT be read as empty/absent. Beyond
# unparseable JSON: a syntactically-valid `{}`, a missing required field, a wrong `ok`, an
# empty failure `errors`, or a row without a `state` are all schema corruption (No Silent
-# Fallback — an existing-but-broken record never reads as "all clear").
+# Fallback — an existing-but-broken record never reads as "all clear"). `{}` stands for every
+# single missing required field: they all raise in the one required-list loop of the loader.
_BROKEN_MANIFESTS = [
"{ malformed", # unparseable
"{}", # empty dict (missing all)
'{"ok": false, "rows": [], "errors": [], "warnings": []}', # wrong ok (must be true)
- '{"ok": true, "errors": [], "warnings": []}', # missing rows
'{"ok": true, "rows": [{"files": []}], "errors": [], "warnings": []}', # row without state
]
_BROKEN_EVIDENCE = [
@@ -278,7 +257,6 @@ _BROKEN_EVIDENCE = [
"{}", # empty dict (missing all)
'{"ok": true, "errors": ["idle: x"], "warnings": [], "rows": []}', # wrong ok (must be false)
'{"ok": false, "errors": [], "warnings": [], "rows": []}', # empty errors
- '{"ok": false, "warnings": [], "rows": []}', # missing errors
'{"ok": false, "errors": [null], "warnings": [], "rows": []}', # null error entry (would be silently dropped)
'{"ok": false, "errors": ["no state prefix"], "warnings": [], "rows": []}', # not state-scoped
]
@@ -299,11 +277,14 @@ def test_commit_fails_loud_on_broken_failure_evidence(fixture_run_dir: Path, pay
assert (run / "extract-failure.json").read_text(encoding="utf-8") == payload # not deleted/rewritten
[email protected]("payload", _BROKEN_EVIDENCE)
-def test_inspect_fails_loud_on_broken_failure_evidence(fixture_run_dir: Path, payload: str) -> None:
+def test_inspect_fails_loud_on_broken_failure_evidence(fixture_run_dir: Path) -> None:
"""READER path: the correction loop reads per-state failures through inspect_run. A broken
extract-failure.json must fail loud on the read too — never be read as 'no failures' — or an
- unresolved-failure run is judged all-clear (No Silent Fallback)."""
+ unresolved-failure run is judged all-clear (No Silent Fallback).
+
+ One payload is enough here: inspect and the commit path read the record through the same
+ validator, and test_commit_fails_loud_on_broken_failure_evidence walks every broken class."""
+ payload = "{}"
run = fixture_run_dir
assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
(run / "extract-failure.json").write_text(payload, encoding="utf-8")
@@ -372,7 +353,6 @@ def test_finished_generation_consumers_fail_loud_on_broken_manifest(fixture_run_
@pytest.mark.parametrize("mutate,expect", [
(lambda m: m.update(rows=[]), "missing row"), # empty rows, but frames exist
- (lambda m: m["rows"].pop(), "missing row"), # drop a state's row
(lambda m: m["rows"].append({**m["rows"][0]}), "duplicate"), # duplicate state row
])
def test_consumer_fails_loud_on_inconsistent_manifest(fixture_run_dir: Path, mutate, expect) -> None:
@@ -389,31 +369,35 @@ def test_consumer_fails_loud_on_inconsistent_manifest(fixture_run_dir: Path, mut
assert expect in (r.stdout + r.stderr).lower()
[email protected]("tool,extra", [("compose_sprite_atlas.py", []), ("compose_sprite_gif.py", [])])
-def test_consumer_fails_loud_on_deleted_frame(fixture_run_dir: Path, tool, extra) -> None:
+def test_consumer_fails_loud_on_deleted_frame(fixture_run_dir: Path) -> None:
"""A physical frame the manifest references is deleted → the consumer fails loud, never
- silently produces a shorter output (No Silent Fallback)."""
+ silently produces a shorter output (No Silent Fallback). Every consumer reaches this through
+ `require_frames_manifest`; their wiring to it is held per tool by
+ test_finished_generation_consumers_fail_loud_on_broken_manifest."""
run = fixture_run_dir
assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
victim = sorted((run / "frames" / "idle").glob("frame-*.png"))[0] # a canonical frame (fixture is non-pp)
victim.unlink()
- r = run_script(tool, "--run-dir", str(run), *extra)
- assert r.returncode != 0, f"{tool} accepted a missing frame"
+ r = run_script("compose_sprite_atlas.py", "--run-dir", str(run))
+ assert r.returncode != 0, "compose_sprite_atlas.py accepted a missing frame"
assert "missing frame" in (r.stdout + r.stderr).lower()
def test_orphan_frames_without_manifest_fail_loud(fixture_run_dir: Path) -> None:
"""Physical frames with NO manifest are an orphan/stale generation, not a fresh scaffold —
- consumers and inspect must fail loud, not read the stale frames as a valid generation."""
+ consumers and inspect must fail loud, not read the stale frames as a valid generation.
+
+ Every reader reaches the orphan branch through `load_consistent_frames_manifest`; inspect is
+ the reader that tolerates an absent manifest, so it is the one a missing branch would fool.
+ Per-tool wiring to the loader is held by the broken-manifest tests above."""
run = fixture_run_dir
assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
(run / "frames" / "frames-manifest.json").unlink()
- for tool, extra in (("compose_sprite_atlas.py", []), ("inspect_sprite_run.py", ["--no-write"])):
- r = run_script(tool, "--run-dir", str(run), *extra)
- assert r.returncode != 0, f"{tool} accepted orphan frames"
- assert "orphan" in (r.stdout + r.stderr).lower()
+ r = run_script("inspect_sprite_run.py", "--run-dir", str(run), "--no-write")
+ assert r.returncode != 0, "inspect_sprite_run.py accepted orphan frames"
+ assert "orphan" in (r.stdout + r.stderr).lower()
def test_empty_files_generation_fails_loud(fixture_run_dir: Path) -> None:
@@ -444,14 +428,14 @@ def test_empty_files_generation_fails_loud(fixture_run_dir: Path) -> None:
assert healed.returncode == 0, healed.stdout + healed.stderr
assert "[heal]" in healed.stderr
- # raw 가 없으면: 어떤 소비자도 손상 세대를 받아들이지 않는다 (fail loud)
+ # raw 가 없으면: 어떤 소비자도 손상 세대를 받아들이지 않는다 (fail loud). 소비자는 모두 같은
+ # load_consistent_frames_manifest 검사에 닿으므로 하나만 돌린다 — 도구별 배선은 위
+ # broken-manifest 테스트가 잡는다.
corrupt()
shutil.rmtree(run / "raw")
- for tool, extra in (("compose_sprite_atlas.py", []), ("preview_animation.py", []),
- ("inspect_sprite_run.py", ["--no-write"])):
- r = run_script(tool, "--run-dir", str(run), *extra)
- assert r.returncode != 0, f"{tool} accepted an empty-files generation"
- assert "no frame files" in (r.stdout + r.stderr).lower()
+ r = run_script("compose_sprite_atlas.py", "--run-dir", str(run))
+ assert r.returncode != 0, "compose_sprite_atlas.py accepted an empty-files generation"
+ assert "no frame files" in (r.stdout + r.stderr).lower()
def test_unknown_state_row_fails_loud(fixture_run_dir: Path) -> None:
@@ -471,11 +455,11 @@ def test_unknown_state_row_fails_loud(fixture_run_dir: Path) -> None:
m["rows"].append({"state": "ghost", "frames": 1, "files": ["frames/ghost/frame-0.png"], "ok": True})
p.write_text(json.dumps(m), encoding="utf-8")
- for tool, extra in (("compose_sprite_atlas.py", []), ("preview_animation.py", []),
- ("inspect_sprite_run.py", ["--no-write"])):
- r = run_script(tool, "--run-dir", str(run), *extra)
- assert r.returncode != 0, f"{tool} accepted an unknown 'ghost' state"
- assert "not in the request" in (r.stdout + r.stderr).lower()
+ # One consumer: every reader reaches this check through `load_consistent_frames_manifest`, and
+ # per-tool wiring to it is held by the broken-manifest tests above.
+ r = run_script("compose_sprite_atlas.py", "--run-dir", str(run))
+ assert r.returncode != 0, "compose_sprite_atlas.py accepted an unknown 'ghost' state"
+ assert "not in the request" in (r.stdout + r.stderr).lower()
def test_frame_count_mismatch_fails_loud(fixture_run_dir: Path) -> None:
diff --git a/tests/packaging/test_project_metadata.py b/tests/packaging/test_project_metadata.py
index 94bccb0..4d0fe2c 100644
--- a/tests/packaging/test_project_metadata.py
+++ b/tests/packaging/test_project_metadata.py
@@ -30,18 +30,14 @@ def _ci_python_versions() -> list[str]:
def test_ci_versions_are_supported_and_documented() -> None:
- minimum_tuple = _version_tuple(_declared_min_python())
+ minimum = _declared_min_python()
+ minimum_tuple = _version_tuple(minimum)
versions = _ci_python_versions()
assert all(_version_tuple(version) >= minimum_tuple for version in versions)
readme = (ROOT / "README.md").read_text(encoding="utf-8")
assert len(versions) == 1, "CI intentionally tests a single Python version"
assert f"CI runs only {versions[0]}" in readme
-
-
-def test_readme_names_declared_python_support_and_venv_requirement() -> None:
- minimum = _declared_min_python()
- readme = (ROOT / "README.md").read_text(encoding="utf-8")
-
+ # The README also names the declared floor and the venv requirement.
assert f"CPython {minimum}+" in readme
assert "`venv`/`ensurepip`" in readme
diff --git a/tests/qa/test_handed_check.py b/tests/qa/test_handed_check.py
index 8c8c061..7c2d84f 100644
--- a/tests/qa/test_handed_check.py
+++ b/tests/qa/test_handed_check.py
@@ -26,6 +26,9 @@ DRAWN = {
("side", "right"): "hidden", ("side", "left"): "near",
}
VIEWS = list(DRAWN)
+# The side compare and the near/far rules do not depend on which side of the figure is shown, so the
+# back views repeat what the front ones prove; `tests/gen/test_handedness.py` holds the whole table.
+PASS_VIEWS = [(view, facing) for view, facing in VIEWS if not view.startswith("back")]
def figure(where: str, *, swing: int = 0, screen: int = 12, outline_split: bool = False) -> Image.Image:
@@ -60,7 +63,7 @@ def check(frames, view, facing, **kw):
return handed.check(frames, item=WATCH, view=view, facing=facing, marker=BLUE, **kw)
[email protected]("view,facing", VIEWS)
[email protected]("view,facing", PASS_VIEWS)
def test_each_view_drawn_as_its_handedness_says_passes(view, facing) -> None:
report = check(loop(DRAWN[(view, facing)]), view, facing)
assert report["ok"], report["fails"]
@@ -68,15 +71,14 @@ def test_each_view_drawn_as_its_handedness_says_passes(view, facing) -> None:
assert check(loop(DRAWN[(view, facing)]), view, facing, references=[figure("right")])["ok"]
+# The rows reach each way a mirror fails: the wrong picture side (front, a diagonal) and a side view turned
+# over both ways round (near for far, far for near). The back views and the other diagonal direction reach
+# the same branches in `handed.check`.
@pytest.mark.parametrize("view,facing,as_view,as_facing", [
("front", None, "front", None),
- ("back", None, "back", None),
("side", "right", "side", "left"), # E turned over for W: the watch stays hidden
("front_diagonal", "right", "front_diagonal", "left"), # SE for SW: the watch jumps to the picture's left
- ("back_diagonal", "right", "back_diagonal", "left"), # NE for NW: the watch jumps to the picture's right
("side", "left", "side", "right"),
- ("front_diagonal", "left", "front_diagonal", "right"),
- ("back_diagonal", "left", "back_diagonal", "right"),
])
def test_a_mirrored_view_fails(view, facing, as_view, as_facing) -> None:
"""The counterexample: the right-facing view turned over, checked as the left-facing one, fails."""
@@ -134,18 +136,6 @@ def test_a_far_part_that_does_not_swing_keeps_the_hidden_rule() -> None:
assert not caught["ok"] and "on the far side" in caught["fails"][0]["why"][0]
[email protected]("spec", ["the red anklet=left ankle", "the brass pauldron=left shoulder", "the red ribbon=left ear"])
-def test_a_far_item_off_the_wrist_keeps_the_hidden_rule(spec) -> None:
- """Only a wrist, hand, forearm or elbow swings its item into view (`handedness.limb`, the table the prompts
- read): an anklet, a shoulder piece or an ear ribbon on the far side stays hidden or a sliver, as in 2.22.0."""
- item = h.parse(spec)
- frames = loop("near")
- report = handed.check(frames, item=item, view="side", facing="right", marker=BLUE, state="walk",
- references=[figure("right")])
- assert "far_hidden" in report["rules"] and "far_in_front" not in report["rules"] and "far_shown" not in report["rules"]
- assert not report["ok"] and "on the far side" in report["fails"][0]["why"][0]
-
-
def test_a_far_sliver_turned_over_is_not_the_near_item_shown() -> None:
"""Facing right, the far wrist's watch may show as a sliver as the arm swings. Turned over to face left,
that sliver is on the arm behind the body — the own right wrist, the wrong one — and the near wrist is
diff --git a/tests/qa/test_motion.py b/tests/qa/test_motion.py
index 0f18ac4..3dd7822 100644
--- a/tests/qa/test_motion.py
+++ b/tests/qa/test_motion.py
@@ -81,16 +81,6 @@ def test_split_duplicate_holds_preserve_duration_and_stance_speed():
assert b["contact_candidates"][0]["measurement_elapsed_seconds"] == pytest.approx(0.8)
-def test_added_hold_time_reduces_speed_instead_of_being_dropped():
- original = analyze_motion(sequence(), contacts="0:4", foot_box=FOOT_BOX)
- repeated = analyze_motion(
- sequence((24, 24, 22, 22, 20, 20, 18, 18, 16, 16)),
- contacts="0:9", foot_box=FOOT_BOX,
- )
- assert repeated["duration_seconds"] == pytest.approx(original["duration_seconds"] * 2)
- assert repeated["stride_px_per_second"] == pytest.approx(original["stride_px_per_second"] / 2)
-
-
def test_nonuniform_frame_durations_determine_speed():
seq = sequence((24, 23, 20, 18, 16), durations=[0.05, 0.15, 0.1, 0.1, 0.4])
report = analyze_motion(seq, contacts=[(0, 4)], foot_box=FOOT_BOX)
diff --git a/tests/release/test_release_notes.py b/tests/release/test_release_notes.py
index 54e3876..e682992 100644
--- a/tests/release/test_release_notes.py
+++ b/tests/release/test_release_notes.py
@@ -102,27 +102,19 @@ def test_a_version_is_not_matched_by_a_pre_release_of_itself(tmp_path: Path) ->
assert page["title"] == "v1.3.0-rc1 - Release candidate", "the rc tag still gets its own section"
-def test_a_heading_inside_a_fenced_block_is_code_not_a_section(tmp_path: Path) -> None:
[email protected]("opener,closer", [
+ ("```sh", "```"),
+ # Quoted markdown uses `~~~` so its own backticks stay readable; it is still a fence.
+ ("~~~md", "~~~"),
+])
+def test_a_heading_inside_a_fenced_block_is_code_not_a_section(
+ tmp_path: Path, opener: str, closer: str
+) -> None:
"""A `## v1.2.0` line inside a code fence must not cut the section short or answer for a tag."""
fenced = (
"# Changelog\n\n## v1.3.0 - Newest\n\n"
"- What the old command printed:\n\n"
- "```sh\n## v1.2.0 - not a heading\n```\n\n"
- "- A line after the fence.\n\n"
- "## v1.2.0 - Middle\n\n- The real middle section.\n"
- )
- newest = _render(tmp_path, "v1.3.0", fenced, with_footer=False)
- assert "A line after the fence." in str(newest["body"])
- middle = _render(tmp_path, "v1.2.0", fenced, with_footer=False)
- assert middle["body"] == "- The real middle section."
-
-
-def test_a_tilde_fence_hides_a_heading_the_way_a_backtick_fence_does(tmp_path: Path) -> None:
- """Quoted markdown uses `~~~` so its own backticks stay readable; it is still a fence."""
- fenced = (
- "# Changelog\n\n## v1.3.0 - Newest\n\n"
- "- The section this release's notes are quoting:\n\n"
- "~~~md\n## v1.2.0 - not a heading\n~~~\n\n"
+ f"{opener}\n## v1.2.0 - not a heading\n{closer}\n\n"
"- A line after the fence.\n\n"
"## v1.2.0 - Middle\n\n- The real middle section.\n"
)
diff --git a/tests/release/test_release_publish.py b/tests/release/test_release_publish.py
index 372bd1a..021a128 100644
--- a/tests/release/test_release_publish.py
+++ b/tests/release/test_release_publish.py
@@ -126,14 +126,6 @@ def test_a_dry_run_creates_nothing_and_shows_what_it_would_create(harness: Harne
assert not harness.published()
-def test_a_dry_run_on_a_released_tag_reports_the_no_op(harness: Harness) -> None:
- harness.state.write_text("published", encoding="utf-8")
- proc = harness.run("--dry-run")
- assert proc.returncode == 0, proc.stderr
- assert "already has a release page" in proc.stdout
- assert [c.split()[1] for c in harness.calls] == ["view"]
-
-
def test_an_unreadable_answer_is_not_read_as_a_missing_release(harness: Harness) -> None:
"""No silent fallback: a 503 must not become "no release yet" and then a create."""
proc = harness.run(unreachable=True)
@@ -150,14 +142,6 @@ def test_a_missing_changelog_section_stops_before_gh_is_called(harness: Harness)
assert harness.calls == [], "the notes are rendered before anything is asked of gh"
-def test_a_gif_named_in_the_notes_but_absent_stops_the_release(harness: Harness) -> None:
- (harness.checkout / "docs" / "assets" / "wave-cube.gif").unlink()
- proc = harness.run()
- assert proc.returncode == 2
- assert "wave-cube.gif" in proc.stderr
- assert not harness.published()
-
-
def test_a_dist_directory_with_stale_archives_is_refused(harness: Harness, tmp_path: Path) -> None:
"""Everything in the dist dir is attached, so a leftover archive would ride along."""
stale = tmp_path / "dist"
diff --git a/tests/serve/test_curation_view_contract.py b/tests/serve/test_curation_view_contract.py
index 168bb4e..895751c 100644
--- a/tests/serve/test_curation_view_contract.py
+++ b/tests/serve/test_curation_view_contract.py
@@ -115,9 +115,10 @@ def test_special_char_state_name_keeps_pixel_grid(tmp_path):
assert _serve_status(out, url) == 200
[email protected]("name", ["guide-a#b.png", "anchor-c d.png", "basis-100%done.png", "guide-café.png"])
-def test_special_char_ref_filename_is_url_encoded_and_serves(tmp_path, name):
- run = _build_import(tmp_path, [name])
+def test_special_char_ref_filename_is_url_encoded_and_serves(tmp_path):
+ # One name carries each character that breaks a URL — `#` (a fragment), a space, `%` (an escape)
+ # and a non-ASCII letter: they all go through the one `_url` quote and the one handler unquote.
+ run = _build_import(tmp_path, ["guide-a#b c-100%done-café.png"])
url = build_run_state(run)["states"][0]["refs"][0]["url"]
# nothing that breaks a URL (# → fragment) or an HTML attribute may survive raw
assert not any(c in url for c in '# "\'<>')
@@ -309,19 +310,6 @@ def test_api_run_reader_isolated_from_concurrent_publish(tmp_path):
assert outcome["at"] >= released_at, "reader returned before the publish released"
-def test_serve_fails_loud_on_orphan_frames(fixture_run_dir):
- """serve serves a scaffold only for a genuinely ungenerated run. Physical frames with NO
- manifest are an orphan/stale generation, not a fresh scaffold — build_run_state must fail loud
- (HTTP 500 in do_GET), never expose stale frames as present (No Silent Fallback / Consistency)."""
- from conftest import run_script
-
- run = fixture_run_dir
- assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
- (run / "frames" / "frames-manifest.json").unlink() # orphan: frames, no manifest
- with pytest.raises(SystemExit):
- build_run_state(run)
-
-
def test_import_fails_loud_on_multiple_base_images(tmp_path):
"""`_base/` is the run's single identity image; multiple images must fail loud, not silently
pick the first (identity SSoT / No Silent Fallback)."""
diff --git a/tests/spec/test_assets.py b/tests/spec/test_assets.py
index bd34228..f517b30 100644
--- a/tests/spec/test_assets.py
+++ b/tests/spec/test_assets.py
@@ -186,18 +186,6 @@ def test_identity_separates_states_rates_and_anchors_of_one_file_set(tmp_path):
assert not same_identity(None, walk)
-def test_fingerprints_describe_the_decoded_bytes_not_the_file_now_on_disk(tmp_path):
- source = tmp_path / "swap.png"
- Image.new("RGBA", (4, 4), "red").save(source)
- red_hash = sha(source)
- loaded = load_asset(source)
- Image.new("RGBA", (4, 4), "blue").save(source)
- assert loaded.frames[0].getpixel((0, 0)) == (255, 0, 0, 255)
- assert loaded.fingerprints() == {str(source.resolve()): red_hash}
- assert loaded.fingerprints() != load_asset(source).fingerprints()
- assert load_asset(source).fingerprints() == {str(source.resolve()): sha(source)}
-
-
def test_replacement_between_read_and_decode_cannot_separate_pixels_from_hash(tmp_path, monkeypatch):
source = tmp_path / "race.png"
Image.new("RGBA", (4, 4), "red").save(source)
diff --git a/tests/spec/test_migrate_breathe.py b/tests/spec/test_migrate_breathe.py
index 4c51400..7d56e38 100644
--- a/tests/spec/test_migrate_breathe.py
+++ b/tests/spec/test_migrate_breathe.py
@@ -29,26 +29,18 @@ def _sidecar(tmp_path, breathe):
ALL_RETIRED = {"splits": [0.32, 0.55], "amplitude": 2, "subpixel": True, "hold": 3}
[email protected]("key", sorted(RETIRED_BREATHE_KEYS))
-def test_every_retired_key_is_reported_as_dropped(key):
- """버린 것을 전부 출력한다 — 목록에서 빠진 키는 조용히 사라진다."""
- fresh, dropped = migrate_entry({key: ALL_RETIRED[key], "breaths": 3})
- assert any(line.startswith(f"{key}=") for line in dropped), \
- f"{key} 를 버렸다는 보고가 없다: {dropped}"
- assert key not in fresh
-
-
def test_breaths_survives_and_the_rest_is_reset():
- fresh, _ = migrate_entry({**ALL_RETIRED, "breaths": 5})
+ # 반공허: 폐기 키가 늘었는데 ALL_RETIRED 가 그대로면 아래 보고 단정이 그 키를 못 본다.
+ assert set(RETIRED_BREATHE_KEYS) <= set(ALL_RETIRED), \
+ f"ALL_RETIRED 에 없는 폐기 키: {sorted(set(RETIRED_BREATHE_KEYS) - set(ALL_RETIRED))}"
+ fresh, dropped = migrate_entry({**ALL_RETIRED, "breaths": 5})
assert fresh["breaths"] == 5, "사람이 고른 호흡 횟수는 보존한다"
assert set(fresh) == {"depth", "lag", "breaths"}
assert not any(k in fresh for k in RETIRED_BREATHE_KEYS)
-
-
-def test_a_non_integer_breaths_falls_back_loudly():
- fresh, dropped = migrate_entry({"splits": [0.5], "breaths": "셋"})
- assert fresh["breaths"] == 1
- assert any("breaths=" in line for line in dropped), "되돌린 사실이 보고돼야 한다"
+ # 버린 것을 전부 출력한다 — 목록에서 빠진 키는 조용히 사라진다.
+ for key in sorted(RETIRED_BREATHE_KEYS):
+ assert any(line.startswith(f"{key}=") for line in dropped), \
+ f"{key} 를 버렸다는 보고가 없다: {dropped}"
def test_dry_run_does_not_touch_the_file(tmp_path, capsys):
@@ -98,11 +90,13 @@ def test_a_non_integer_breaths_is_reported_not_truncated() -> None:
# `nan`/`inf` 도 담는다: `json.loads` 는 기본값으로 `NaN` 리터럴을 받으므로 사이드카에서
# 실제로 들어오고, `int(nan)` 은 `ValueError` 를 올려 마이그레이션을 **트레이스백으로
# 죽인다**. 값 목록에 없어서 그 회귀를 그물이 못 봤다 (노을이 실측 2026-07-26 R2).
- for value in (2.7, "3.5", 1.5, 0.5, float("nan"), float("inf"), float("-inf")):
+ # "셋" 은 `float()` 자체가 실패하는 `except` 분기를 밟는 유일한 값이다.
+ for value in (2.7, "3.5", "셋", 1.5, 0.5, float("nan"), float("inf"), float("-inf")):
fresh, dropped = migrate_entry({"splits": [10], "breaths": value})
said = [d for d in dropped if d.startswith("breaths=")]
assert said, f"breaths={value!r} 를 조용히 {fresh['breaths']} 로 바꿨다 — 버린 걸 안 말한다"
assert "정수" in said[0], f"breaths={value!r}: 정수 계약이 아닌 사유로 버렸다 ({said[0]})"
+ assert fresh["breaths"] == 1, f"breaths={value!r} 가 1 로 되돌아가지 않았다 ({fresh['breaths']})"
# 정수로 표현되는 실수·정수는 그대로 통과한다 (과잉 거부 금지)
for value in (3, 3.0):
diff --git a/tests/spec/test_request_read_no_mutation.py b/tests/spec/test_request_read_no_mutation.py
index 3e73d61..75108f1 100644
--- a/tests/spec/test_request_read_no_mutation.py
+++ b/tests/spec/test_request_read_no_mutation.py
@@ -59,28 +59,6 @@ def synthetic_fixture_a_run(tmp_path: Path) -> Path:
return run_dir
-def test_state_revision_does_not_rewrite_the_request(synthetic_fixture_a_run: Path) -> None:
- """사고 재현 고정: 조회 한 번이 canonical 런 파일을 바꾸지 않는다."""
- path = synthetic_fixture_a_run / REQUEST_FILENAME
- before = sha256_of(path)
-
- assert state_revision(synthetic_fixture_a_run, "walk") is not None
-
- assert sha256_of(path) == before, (
- "state_revision() 이 sprite-request.json 을 재기록했다 — 조회가 canonical 런을 "
- "오염시킨다 (합성 조회 회귀)")
- assert "pixel_perfect" in json.loads(path.read_text(encoding="utf-8"))["fit"]
-
-
-def test_state_revision_does_not_move_the_generation_fingerprint(synthetic_fixture_a_run: Path) -> None:
- """`run_revision` 은 request 바이트를 해싱한다 — 읽기가 파일을 쓰면 조회만으로 세대
- 지문이 움직여, 그 런의 큐레이션 사이드카가 stale 로 떨어진다. 읽기는 세대를 흔들지
- 않는다."""
- before = curation_mod.run_revision(synthetic_fixture_a_run)
- state_revision(synthetic_fixture_a_run, "walk")
- assert curation_mod.run_revision(synthetic_fixture_a_run) == before
-
-
def read_everything(run_dir: Path) -> None:
"""조회 API 전수 — 어느 진입점으로 읽어도 런 디렉터리는 바이트 불변이어야 한다."""
from sprite_gen.curate import anchor as anchor_mod
@@ -103,10 +81,17 @@ def test_read_api_surface_is_byte_stable(synthetic_fixture_a_run: Path) -> None:
"""조회 API 전수: 어느 진입점으로 읽어도 런 디렉터리 바이트가 불변이다.
한 진입점만 잠그면 다음 진입점이 같은 병을 다시 만든다 — 계약은 "이 함수" 가 아니라
- "읽는 쪽" 전체다."""
+ "읽는 쪽" 전체다.
+
+ `state_revision()` 조회 사고(request 재기록)의 재현 고정도 여기다: request 바이트가 그대로면
+ 그 바이트를 해싱하는 `run_revision` 세대 지문도 움직이지 않는다."""
before = run_dir_sha256(synthetic_fixture_a_run)
read_everything(synthetic_fixture_a_run)
- assert run_dir_sha256(synthetic_fixture_a_run) == before
+ # 반공허 단정: manifest row 가 없으면 state_revision 은 None 으로 조기 반환해 로더를 밟지 않는다.
+ assert state_revision(synthetic_fixture_a_run, "walk") is not None
+ assert run_dir_sha256(synthetic_fixture_a_run) == before, (
+ "조회가 런 디렉터리를 바꿨다 — state_revision() 등이 sprite-request.json 을 재기록하면 "
+ "canonical 런이 오염되고 세대 지문이 움직인다 (합성 조회 회귀)")
def test_read_api_surface_is_byte_stable_when_the_sidecar_is_stale(synthetic_fixture_a_run: Path) -> None:
diff --git a/tests/test_hexcolor.py b/tests/test_hexcolor.py
index facc30a..d9b94c5 100644
--- a/tests/test_hexcolor.py
+++ b/tests/test_hexcolor.py
@@ -20,10 +20,11 @@ def test_six_hex_digits_are_a_colour(text, rgb):
assert parse_hex(text) == rgb
[email protected]("text", ["#-1-1-1", "+f+f+f", "#1_0_00", "-0-0-0", "#12345", "#1234567", "zzzzzz", "##112233", ""])
[email protected]("text", ["#-1-1-1", "#1_0_00", "#1234567", ""])
def test_anything_else_is_not(text):
"""`int(…, 16)` alone takes `-1`, `+f` and `1_0`: three of the copies this replaced read `#-1-1-1`
- as the colour (-1, -1, -1)."""
+ as the colour (-1, -1, -1). One `fullmatch` refuses them all, so one case per class of refusal:
+ a sign, an underscore, the wrong length, nothing."""
with pytest.raises(ValueError, match="expected #RRGGBB"):
parse_hex(text)
diff --git a/tests/test_prepare_layout_guides.py b/tests/test_prepare_layout_guides.py
index f657e02..c96e6e0 100644
--- a/tests/test_prepare_layout_guides.py
+++ b/tests/test_prepare_layout_guides.py
@@ -2,8 +2,6 @@
"""Prepared guides carry geometry only, including when old recipes are reused."""
import json
-import subprocess
-import sys
from pathlib import Path
import pytest
@@ -13,8 +11,8 @@ from conftest import run_script
from sprite_gen.gen import prepare
[email protected]("frames", [8, 16])
-def test_reused_request_cannot_restore_pose_guides(tmp_path: Path, frames: int):
+def test_reused_request_cannot_restore_pose_guides(tmp_path: Path):
+ frames = 8 # `draw_guide` has no frame-count branch, so one count stands for any
payload = {"states": {"running-right": {
"frames": frames, "fps": 16, "loop": True, "action": "running in place",
}}}
@@ -49,20 +47,9 @@ def test_reused_request_cannot_restore_pose_guides(tmp_path: Path, frames: int):
assert prompt_texts[0] == prompt_texts[1] == prompt_texts[2]
[email protected]("entrypoint", ["wrapper", "cli"])
-def test_removed_flag_is_rejected_before_output(tmp_path: Path, entrypoint: str):
- args = ["--out-dir", str(tmp_path / "run"), "--character-id", "runner", "--motion-phase-guides"]
- if entrypoint == "wrapper":
- result = run_script("prepare_sprite_run.py", *args)
- else:
- result = subprocess.run([sys.executable, "-m", "sprite_gen.cli", "prepare", *args],
- text=True, capture_output=True)
- assert result.returncode != 0
- assert "unrecognized arguments: --motion-phase-guides" in result.stderr
- assert not (tmp_path / "run").exists()
-
-
def test_library_does_not_accept_removed_option(tmp_path: Path):
+ """The removed option stays removed at every entrypoint: the wrapper re-exports `prepare`, and
+ the CLI subparser is prepare's own parser (tests/gen/test_flags_over_spec.py)."""
with pytest.raises(TypeError, match="unexpected keyword argument.*motion_phase_guides"):
prepare.run(out_dir=tmp_path / "run", character_id="runner", motion_phase_guides=True)
assert not (tmp_path / "run").exists()
diff --git a/tests/test_subject_profile.py b/tests/test_subject_profile.py
index 9fe58b4..1a0ac69 100644
--- a/tests/test_subject_profile.py
+++ b/tests/test_subject_profile.py
@@ -82,15 +82,13 @@ def test_profile_resolves_floor_and_rejects_unknown_kinds() -> None:
subject_kind({**request, "subject": "creature"})
+# One formula with one branch: a square and a rect cell pin its values; the 64² case is in
+# test_profile_resolves_floor_and_rejects_unknown_kinds and every square size from 16 to 512 is walked
+# by test_floor_is_monotone_across_every_square_size_from_16_to_512.
@pytest.mark.parametrize(
("width", "height", "margin_x", "margin_y", "character", "effect"),
[
(16, 16, 1, 1, 16, 8),
- (32, 32, 2, 2, 32, 16),
- (64, 64, 6, 6, 64, 32),
- (128, 128, 12, 12, 128, 64),
- (256, 256, 24, 24, 256, 128),
- (512, 512, 48, 48, 512, 256),
(192, 208, 18, 19, 200, 100),
],
)
@@ -163,6 +161,14 @@ def test_effect_profile_passes_a_sparse_synthetic_effect(tmp_path: Path) -> None
assert doc["ok"] is True
px = [r["nontransparent_pixels"] for r in doc["rows"][0]["frame_records"]]
assert all(32 <= p < 64 for p in px)
+ # A profile-derived floor is not stamped into extract_args (an explicit flag is, below):
+ # frames are a derived cache of (raw + request + engine), so heal must re-resolve from the request.
+ assert "min_used_pixels" not in doc["extract_args"]
+ # compose follows the same profile floor.
+ compose = run_script("compose_sprite_atlas.py", "--run-dir", str(run))
+ assert compose.returncode == 0, compose.stdout + compose.stderr
+ manifest = json.loads((run / "manifest.json").read_text(encoding="utf-8"))
+ assert manifest["frame_layout"]["rows"]["burst"]
def test_effect_profile_still_catches_debris(tmp_path: Path) -> None:
@@ -177,27 +183,11 @@ def test_explicit_flag_beats_the_profile_and_is_stamped(tmp_path: Path) -> None:
proc = _extract(run, "--min-used-pixels", "12")
assert proc.returncode == 0, proc.stdout + proc.stderr
doc = _manifest(run)
- # explicit flag is recorded for heal reproduction...
+ # explicit flag is recorded for heal reproduction (a profile-derived floor is not; see
+ # test_effect_profile_passes_a_sparse_synthetic_effect)
assert doc["extract_args"].get("min_used_pixels") == 12
-def test_profile_derived_floor_is_not_stamped_into_extract_args(tmp_path: Path) -> None:
- # ...but a profile-derived floor is not: frames are a derived cache of
- # (raw + request + engine), so heal must re-resolve from the request.
- run = _make_run(tmp_path / "run", 40, subject="effect")
- assert _extract(run).returncode == 0
- assert "min_used_pixels" not in _manifest(run)["extract_args"]
-
-
-def test_compose_floor_follows_the_profile(tmp_path: Path) -> None:
- run = _make_run(tmp_path / "run", 40, subject="effect")
- assert _extract(run).returncode == 0
- proc = run_script("compose_sprite_atlas.py", "--run-dir", str(run))
- assert proc.returncode == 0, proc.stdout + proc.stderr
- manifest = json.loads((run / "manifest.json").read_text(encoding="utf-8"))
- assert manifest["frame_layout"]["rows"]["burst"]
-
-
def test_prepare_writes_the_subject_field_only_when_declared(tmp_path: Path) -> None:
base = ["prepare_sprite_run.py", "--character-id", "profiled"]
plain = run_script(*base, "--out-dir", str(tmp_path / "plain"))
diff --git a/tests/util/test_gif_utils.py b/tests/util/test_gif_utils.py
index 5ff0d69..43a51dd 100644
--- a/tests/util/test_gif_utils.py
+++ b/tests/util/test_gif_utils.py
@@ -7,8 +7,9 @@ from sprite_gen.util.gif_utils import save_clean_gif
from sprite_gen._deps import np
[email protected]("loop", [None, 0])
[email protected]("starts_empty", [False, True])
+# `loop` is one conditional keyword, apart from the opaque/transparent split, so pairing the two axes
+# covers both values of each (the full grid adds nothing).
[email protected]("loop,starts_empty", [(None, True), (0, False)])
def test_opaque_sequence_keeps_black_canvas_and_empty_endpoint(tmp_path, loop, starts_empty):
frames = []
for k in range(64):
@@ -36,8 +37,8 @@ def test_opaque_sequence_keeps_black_canvas_and_empty_endpoint(tmp_path, loop, s
assert preview.info["duration"] == 60
[email protected]("loop", [None, 0])
-def test_default_transparency_clears_moving_subject_and_preserves_playback(tmp_path, loop):
+def test_default_transparency_clears_moving_subject_and_preserves_playback(tmp_path):
+ loop = 0 # the unset `loop` is held by the opaque test above
frames = []
for x in (2, 12, None):
frame = Image.new("RGBA", (24, 24))
diff --git a/tests/workflow/test_workflow.py b/tests/workflow/test_workflow.py
index 2620465..6bfccc2 100644
--- a/tests/workflow/test_workflow.py
+++ b/tests/workflow/test_workflow.py
@@ -110,8 +110,16 @@ def test_first_sprite_request_and_existing_base(ready_login, tmp_path):
assert "extract" in view["pipeline"]["steps"]
[email protected]("base_provider", ["codex", "grok"])
[email protected]("method", MOTION_METHODS)
+def _crossed_pairs() -> list[tuple[str, str]]:
+ """Each motion method with the base provider it does not use itself, so two swapped fields show.
+
+ `guide.py` copies and reads each field on its own and nothing branches on the pair, so the matched
+ pairs (codex × gpt-rows, grok × grok-video) add nothing the crossed ones do not."""
+ return [(next(p for p in ("codex", "grok") if p != spec["provider"]), method)
+ for method, spec in MOTION_METHODS.items()]
+
+
[email protected]("base_provider,method", _crossed_pairs())
def test_every_sprite_combination_keeps_base_and_motion_distinct(ready_login, base_provider, method):
view = guide.guide("sprite", choices={"image_provider": base_provider, "motion_method": method}, confirmed_access=("codex", "grok"))
assert view["status"] == "ready"