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: one answer each to questions the engine answered in several places - a key given both in a spec file and as a flag (the flag wins and one stderr line says so, for pixel-draw --spec and prepare --request alike), when an answered provider POST is sent again (only an answer the provider documents as a request not taken, after one doubling wait, twice at most, for every direct provider call; video-set no longer reruns a clip on top), a refusal whose body broke on the way (no answer, on every transport), a run(**kwargs) call (one reader, a required flag left out names it), a hex colour (one reader and writer, a sign or underscore is not a colour), and G8's opaque box (the image path's solid_alpha_bbox)

Soohong Kim13b8b226d12a
diff --git a/tests/effects/test_recolor_bake.py b/tests/effects/test_recolor_bake.py
index 17d0fe9..0108d29 100644
--- a/tests/effects/test_recolor_bake.py
+++ b/tests/effects/test_recolor_bake.py
@@ -10,6 +10,7 @@ import numpy as np
from PIL import Image
import sprite_gen.effects.recolor as recolor
+from sprite_gen.util.hexcolor import format_hex
# Flat art colours in the fixture sheet.
COAT = (180, 40, 40) # mapped by every variant
@@ -37,7 +38,7 @@ def _build_sheet(path: Path) -> None:
def _spec(path: Path, *, match: str = "exact", tolerance: int = 0, extra_source: bool = False) -> None:
- variant_map = {recolor.format_hex(COAT): "#14c814"}
+ variant_map = {format_hex(COAT, lower=True): "#14c814"}
if extra_source:
variant_map["#010203"] = "#ffffff" # source absent from the sheet -> unused
spec = {
@@ -47,7 +48,7 @@ def _spec(path: Path, *, match: str = "exact", tolerance: int = 0, extra_source:
"tolerance": tolerance,
"variants": [
{"name": "green", "map": variant_map},
- {"name": "gold", "map": {recolor.format_hex(COAT): "#f0c000"}},
+ {"name": "gold", "map": {format_hex(COAT, lower=True): "#f0c000"}},
],
}
path.write_text(json.dumps(spec), encoding="utf-8")
@@ -101,7 +102,7 @@ def test_report_names_substitutions_passthrough_and_unused(tmp_path: Path) -> No
green = next(v for v in report["variants"] if v["name"] == "green")
# 4 COAT pixels swapped (the sub-threshold one does not count).
- hit = next(s for s in green["substitutions"] if s["from"] == recolor.format_hex(COAT))
+ hit = next(s for s in green["substitutions"] if s["from"] == format_hex(COAT, lower=True))
assert hit["pixels"] == 4
assert green["substituted_pixels"] == 4
@@ -110,9 +111,9 @@ def test_report_names_substitutions_passthrough_and_unused(tmp_path: Path) -> No
# TRIM, GLOW, NEAR_COAT pass through — named and counted, never dropped.
passthrough = {c["hex"]: c["pixels"] for c in green["passthrough_colors"]}
- assert passthrough[recolor.format_hex(TRIM)] == 2
- assert passthrough[recolor.format_hex(GLOW)] == 2
- assert passthrough[recolor.format_hex(NEAR_COAT)] == 1
+ assert passthrough[format_hex(TRIM, lower=True)] == 2
+ assert passthrough[format_hex(GLOW, lower=True)] == 2
+ assert passthrough[format_hex(NEAR_COAT, lower=True)] == 1
assert green["passthrough_pixels"] == 5
assert green["passthrough_color_count"] == 3
@@ -129,7 +130,7 @@ def test_tolerance_matches_near_colour_nearest_wins(tmp_path: Path) -> None:
# NEAR_COAT (2 away) now snaps to COAT's target under tolerance 3.
assert tuple(baked[2, 0, :3]) == (0x14, 0xc8, 0x14)
green = next(v for v in report["variants"] if v["name"] == "green")
- hit = next(s for s in green["substitutions"] if s["from"] == recolor.format_hex(COAT))
+ hit = next(s for s in green["substitutions"] if s["from"] == format_hex(COAT, lower=True))
assert hit["pixels"] == 5 # 4 exact + 1 near
@@ -153,9 +154,9 @@ def test_extract_palette_orders_by_frequency(tmp_path: Path) -> None:
hexes = [c["hex"] for c in palette["colors"]]
# COAT is the most frequent opaque colour (4 px), so it leads.
- assert hexes[0] == recolor.format_hex(COAT)
+ assert hexes[0] == format_hex(COAT, lower=True)
# Sub-threshold pixel excluded -> COAT count is 4, not 5.
- coat = next(c for c in palette["colors"] if c["hex"] == recolor.format_hex(COAT))
+ coat = next(c for c in palette["colors"] if c["hex"] == format_hex(COAT, lower=True))
assert coat["pixels"] == 4
assert palette["color_count"] == len(palette["colors"])
diff --git a/tests/gen/test_anthropic_api.py b/tests/gen/test_anthropic_api.py
index 0363b51..be13dc8 100644
--- a/tests/gen/test_anthropic_api.py
+++ b/tests/gen/test_anthropic_api.py
@@ -107,17 +107,48 @@ def test_a_refused_request_is_asked_again_and_said(server, capsys):
waits = []
reply = api.stream_message(KEY, body(), sleep=waits.append, label="pixel-draw c1-gen1")
assert reply.request_id == "req_2" and len(server.asked) == 3
- assert waits == [10.0, 3.0] # the schedule, then the server's retry-after
+ assert waits == [8.0, 3.0] # the doubling wait (gen.retry.backoff), then the server's retry-after
err = capsys.readouterr().err
assert "[pixel-draw c1-gen1] claude refused the request (529 overloaded_error); nothing was made" in err
assert "(1 of 2)" in err and "(2 of 2)" in err
def test_refusals_past_the_retries_end_the_call(server):
- server.script += [("json", 503, {}, {"type": "error", "error": {"type": "api_error"}})] * 3
+ server.script += [("json", 529, {}, {"type": "error", "error": {"type": "overloaded_error"}})] * 3
+ waits = []
with pytest.raises(api.ApiError) as caught:
- api.stream_message(KEY, body(), sleep=lambda s: None)
- assert caught.value.status == 503 and caught.value.billed is False and len(server.asked) == 3
+ api.stream_message(KEY, body(), sleep=waits.append)
+ assert caught.value.status == 529 and caught.value.billed is False and len(server.asked) == 3
+ assert waits == [8.0, 16.0]
+
+
[email protected](("status", "error"), [
+ (502, {}), (503, {}),
+ (504, {"type": "timeout_error"}), # "The request timed out while processing": it was worked on
+ (429, {"type": "rate_limit_error", "details": {"error_code": "enforced_spend_limit_reached"}}), # the spend cap
+])
+def test_a_refusal_anthropic_does_not_document_as_not_taken_is_not_asked_again(server, status, error):
+ """Only 429 (but the spend cap, which "fails until access resumes"), 500 and 529 are (gen.retry,
+ the errors and rate-limits pages read 2026-10-13)."""
+ server.script.append(("json", status, {}, {"type": "error", "error": error}))
+ with pytest.raises(api.ApiError) as caught:
+ api.stream_message(KEY, body(), sleep=lambda s: pytest.fail(f"a {status} is not asked again"))
+ assert caught.value.status == status and len(server.asked) == 1
+
+
+def test_a_retry_after_longer_than_the_run_waits_is_not_waited_out_early(server):
+ server.script.append(("json", 429, {"retry-after": "600"}, {"type": "error", "error": {"type": "rate_limit_error"}}))
+ with pytest.raises(api.ApiError, match=r"\(HTTP 429\)"):
+ api.stream_message(KEY, body(), sleep=lambda s: pytest.fail("never asked again sooner than it said"))
+ assert len(server.asked) == 1
+
+
+def test_a_batch_read_refused_on_the_providers_side_is_read_again(server):
+ """A GET buys nothing: a 502 on a batch's status is asked again, where the same answer to a POST is not."""
+ server.script += [("json", 502, {}, b"<html>bad gateway</html>"), ("json", 200, {}, {"id": "msgbatch_1"})]
+ waits = []
+ assert api.get_batch(KEY, "msgbatch_1", sleep=waits.append) == {"id": "msgbatch_1"}
+ assert waits == [8.0] and [asked["method"] for asked in server.asked] == ["GET", "GET"]
def test_a_bad_request_is_not_asked_again_and_the_key_is_masked(server):
diff --git a/tests/gen/test_flags_over_spec.py b/tests/gen/test_flags_over_spec.py
new file mode 100644
index 0000000..1e683a9
--- /dev/null
+++ b/tests/gen/test_flags_over_spec.py
@@ -0,0 +1,107 @@
+# SPDX-License-Identifier: Apache-2.0
+"""A key given both in a file and as a flag is one answer, `gen.base.flags_over_spec`: the flag wins,
+and one stderr line names every flag the file also set. `pixel-draw --spec` refused the pair, and
+`prepare --request` let the flag win for some keys and the request for others (`--style`,
+`--cell-size`, `--safe-margin`), in silence either way; both now ask it."""
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+import pytest
+
+from sprite_gen.gen import pixel_draw, prepare
+from sprite_gen.gen.base import flags_over_spec
+
+
+def test_the_flag_wins_and_one_line_names_every_flag_the_file_set(capsys):
+ spec = {"size": 16, "kind": "icon", "cell": {"width": 128, "height": 96}}
+ merged = flags_over_spec(spec, {"size": 24, "walk_cycle": True, "cell.width": 64, "fit.resample": "nearest"},
+ verb="pixel-draw", source="--spec", spelled={"cell.width": "--cell-width"})
+ assert merged == {"size": 24, "kind": "icon", "walk_cycle": True, "cell": {"width": 64, "height": 96},
+ "fit": {"resample": "nearest"}}
+ assert spec == {"size": 16, "kind": "icon", "cell": {"width": 128, "height": 96}} # the file's own dict is left as it was
+ assert capsys.readouterr().err == "[pixel-draw] --size, --cell-width given both as a flag and in --spec: the flag wins\n"
+
+
+def test_no_key_given_both_ways_says_nothing(capsys):
+ assert flags_over_spec({"size": 16}, {"kind": "tile"}, verb="pixel-draw", source="--spec") == {"size": 16, "kind": "tile"}
+ assert capsys.readouterr().err == ""
+
+
+# --- pixel-draw --spec --------------------------------------------------------------------------------
+
+
+def _pixel_args(*argv: str) -> argparse.Namespace:
+ parser = argparse.ArgumentParser()
+ pixel_draw.add_arguments(parser)
+ return parser.parse_args(["--out-dir", "unused", *argv])
+
+
+def test_a_pixel_draw_flag_wins_over_its_spec_and_says_so(tmp_path, capsys):
+ spec = tmp_path / "spec.json"
+ spec.write_text(json.dumps({"subject": "a slime", "size": 16, "kind": "icon"}), encoding="utf-8")
+ request = pixel_draw.resolve_request(_pixel_args("--spec", str(spec), "--size", "24", "--kind", "icon"))
+ assert (request.subject, request.size, request.kind) == ("a slime", 24, "icon")
+ assert capsys.readouterr().err == "[pixel-draw] --size, --kind given both as a flag and in --spec: the flag wins\n"
+
+
+# --- prepare --request ---------------------------------------------------------------------------------
+
+
+def _prepare(tmp_path: Path, request: dict, **flags) -> dict:
+ out = tmp_path / "run"
+ assert prepare.run(out_dir=out, character_id="hero", request_json=json.dumps(request), **flags) == 0
+ return json.loads((out / "sprite-request.json").read_text(encoding="utf-8"))
+
+
+STATES = {"idle": {"frames": 4, "fps": 8, "loop": True, "action": "breathing"}}
+
+
[email protected](("request_keys", "flags", "check", "named"), [
+ ({"style": "ink wash"}, {"style": "flat pixel"}, lambda r: r["style"] == "flat pixel", "--style"),
+ ({"cell": {"size": 128, "safe_margin": 10}}, {"safe_margin": 5},
+ lambda r: (r["cell"]["safe_margin_x"], r["cell"]["safe_margin_y"]) == (5, 5), "--safe-margin"),
+ ({"cell": {"size": 128}}, {"cell_size": 64}, lambda r: (r["cell"]["width"], r["cell"]["height"]) == (64, 64),
+ "--cell-size"),
+ ({"cell": {"size": 128}}, {"cell_width": 96}, lambda r: (r["cell"]["width"], r["cell"]["height"]) == (96, 128),
+ "--cell-width"),
+ ({"fit": {"resample": "lanczos"}}, {"fit_resample": "nearest"}, lambda r: r["fit"] == {"resample": "nearest"},
+ "--fit-resample"),
+ ({"subject": "effect"}, {"subject": "character"}, lambda r: r["subject"] == "character", "--subject"),
+], ids=["style", "safe-margin", "cell-size", "cell-width", "fit", "subject"])
+def test_a_prepare_flag_wins_over_its_request_and_says_so(tmp_path, capsys, request_keys, flags, check, named):
+ """`--style`, `--cell-size` and `--safe-margin` lost to the request before; the others won in silence."""
+ emitted = _prepare(tmp_path, {"states": STATES, **request_keys}, **flags)
+ assert check(emitted)
+ assert f"[prepare] {named} given both as a flag and in --request-json: the flag wins" in capsys.readouterr().err
+
+
+def test_a_request_alone_or_a_flag_alone_says_nothing_and_keeps_its_value(tmp_path, capsys):
+ emitted = _prepare(tmp_path, {"states": STATES, "style": "ink wash", "cell": {"size": 128}}, fit_resample="nearest")
+ assert emitted["style"] == "ink wash" and emitted["cell"]["width"] == 128 and emitted["fit"] == {"resample": "nearest"}
+ assert "given both" not in capsys.readouterr().err
+
+
+def test_a_request_subject_is_carried_and_no_note_says_it_was_dropped(tmp_path, capsys):
+ """prepare reads `subject` off the request; its note listed it among the keys it drops."""
+ emitted = _prepare(tmp_path, {"states": STATES, "subject": "effect"})
+ assert emitted["subject"] == "effect"
+ assert "subject" not in capsys.readouterr().err
+
+
+def test_both_verbs_ask_the_one_function(monkeypatch, tmp_path):
+ seen = []
+
+ def spy(spec, flags, **kwargs):
+ seen.append((kwargs["verb"], kwargs["source"]))
+ return flags_over_spec(spec, flags, **kwargs)
+
+ monkeypatch.setattr(pixel_draw, "flags_over_spec", spy)
+ monkeypatch.setattr(prepare, "flags_over_spec", spy)
+ spec = tmp_path / "spec.json"
+ spec.write_text(json.dumps({"subject": "a slime"}), encoding="utf-8")
+ pixel_draw.resolve_request(_pixel_args("--spec", str(spec)))
+ _prepare(tmp_path, {"states": STATES})
+ assert seen == [("pixel-draw", "--spec"), ("prepare", "--request-json")]
diff --git a/tests/gen/test_grok_provider.py b/tests/gen/test_grok_provider.py
index 8a4744e..9201ce3 100644
--- a/tests/gen/test_grok_provider.py
+++ b/tests/gen/test_grok_provider.py
@@ -11,7 +11,7 @@ from PIL import Image
from sprite_gen import gen
from sprite_gen.gen import base as gen_base
-from sprite_gen.gen import grok_provider as grok, xai
+from sprite_gen.gen import grok_provider as grok, retry, xai
from sprite_gen.gen.base import GenRequest
from sprite_gen.workflow import access, guide
@@ -31,7 +31,8 @@ def api(monkeypatch, tmp_path):
monkeypatch.setenv("XAI_API_KEY", "synthetic-secret")
monkeypatch.setenv("GROK_HOME", str(tmp_path / "no-login"))
monkeypatch.setattr(subprocess, "run", lambda *a, **k: pytest.fail("Grok Build must never be spawned"))
- state = {"status": 200, "body": {"data": [{"b64_json": encoded_image()}]}, "calls": []}
+ state = {"status": 200, "body": {"data": [{"b64_json": encoded_image()}]}, "calls": [], "slept": []}
+ monkeypatch.setattr(retry, "_sleep", state["slept"].append)
class Response:
def __enter__(self):
@@ -46,6 +47,8 @@ def api(monkeypatch, tmp_path):
def open_request(request, *, timeout):
state["calls"].append((request, timeout))
+ if state.get("script"): # one (status, body) per request, in order
+ state["status"], state["body"] = state["script"].pop(0)
return Response()
monkeypatch.setattr(xai.urllib.request, "urlopen", open_request)
@@ -101,7 +104,7 @@ def test_direct_output_keeps_chroma_pipeline(tmp_path, api):
assert image.getpixel((6, 4))[3] == 255
[email protected]("status", [400, 401, 403, 429, 500])
[email protected]("status", [400, 401, 403, 500, 503])
def test_api_failure_keeps_existing_output_and_does_not_retry(tmp_path, api, status):
api.update(status=status, body={"error": "synthetic-secret https://signed.invalid/private?sig=abc"})
out = tmp_path / "existing.png"
@@ -115,6 +118,24 @@ def test_api_failure_keeps_existing_output_and_does_not_retry(tmp_path, api, sta
assert len(api["calls"]) == 1
+def test_a_rate_limit_is_sent_again_and_the_image_published_once(tmp_path, api, capsys):
+ """xAI documents 429 as a request not taken ("reached the rate limit", read 2026-10-13, gen.retry):
+ the image is asked for again after the doubling wait, as the video polls wait."""
+ api["script"] = [(429, {"code": "resource-exhausted", "error": "slow down"}), (200, {"data": [{"b64_json": encoded_image()}]})]
+ result = gen.generate_image("grok", "x", tmp_path / "out.png")
+ assert len(api["calls"]) == 2 and api["slept"] == [8.0] and result.out.is_file()
+ assert "[gen] grok refused the request (429 resource-exhausted); nothing was made — asking again in 8s (1 of 2)" \
+ in capsys.readouterr().err
+
+
+def test_a_rate_limit_still_there_after_two_more_sends_ends_the_call(tmp_path, api):
+ api.update(status=429, body={"code": "resource-exhausted", "error": "slow down"})
+ with pytest.raises(SystemExit) as error:
+ gen.generate_image("grok", "x", tmp_path / "out.png")
+ assert "(HTTP 429) code=resource-exhausted; sent 3 times, no provider fallback" in str(error.value)
+ assert len(api["calls"]) == 3 and api["slept"] == [8.0, 16.0]
+
+
@pytest.mark.parametrize("body", [{}, {"data": []}, {"data": [None]}, {"data": [{}, {}]},
{"data": [{"b64_json": "???"}]},
{"data": [{"b64_json": base64.b64encode(b"invalid image").decode()}]},
@@ -183,7 +204,7 @@ def _subscription_login(tmp_path, monkeypatch):
"key": "subscription-token", "expires_at": "2100-01-01T00:00:00Z"}}))
[email protected]("status", [200, 403, 429])
[email protected]("status", [200, 403, 503])
def test_images_use_subscription_even_with_api_key(tmp_path, api, monkeypatch, status):
_subscription_login(tmp_path, monkeypatch)
api["status"] = status
diff --git a/tests/gen/test_openai_provider.py b/tests/gen/test_openai_provider.py
index e2d31fb..10c3865 100644
--- a/tests/gen/test_openai_provider.py
+++ b/tests/gen/test_openai_provider.py
@@ -20,7 +20,7 @@ from PIL import Image
from sprite_gen import gen
from sprite_gen.gen import grok_provider as grok
from sprite_gen.gen import openai_provider as openai
-from sprite_gen.gen import xai
+from sprite_gen.gen import retry, xai
from sprite_gen.gen.base import GenRequest
from sprite_gen.workflow import access
from sprite_gen.workflow.catalog import FIELDS, GUIDED_PROVIDERS, PROVIDER_LABELS, validate_choices
@@ -65,7 +65,9 @@ def api(monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", KEY)
monkeypatch.setattr(subprocess, "run", lambda *a, **k: pytest.fail("no provider subprocess may be spawned"))
state = {"status": 200, "body": {"data": [{"b64_json": encoded_image()}],
- "usage": {"input_tokens": 12, "output_tokens": 340}}, "headers": {}, "calls": []}
+ "usage": {"input_tokens": 12, "output_tokens": 340}}, "headers": {}, "calls": [],
+ "slept": []}
+ monkeypatch.setattr(retry, "_sleep", state["slept"].append)
class Response:
def __enter__(self):
@@ -87,6 +89,8 @@ def api(monkeypatch):
def open_request(request, *, timeout):
state["calls"].append((request, timeout))
+ if state.get("script"): # one (status, body, headers) per request, in order
+ state["status"], state["body"], state["headers"] = state["script"].pop(0)
if state["status"] == 200:
return Response()
raise urllib.error.HTTPError(request.full_url, state["status"], "error", state["headers"],
@@ -196,7 +200,7 @@ def test_reference_edit_posts_multipart_images_in_order(tmp_path, api):
assert positions == sorted(positions), "reference images are read positionally; order must survive"
[email protected]("status", [400, 401, 403, 429, 500])
[email protected]("status", [400, 401, 403, 500, 502])
def test_api_failure_keeps_existing_output_and_does_not_retry(tmp_path, api, status):
api.update(status=status, body={"error": {"message": f"{KEY} https://signed.invalid/private?sig=abc"}})
out = tmp_path / "existing.png"
@@ -210,6 +214,39 @@ def test_api_failure_keeps_existing_output_and_does_not_retry(tmp_path, api, sta
assert len(api["calls"]) == 1
[email protected](("refused", "slept"), [
+ ((429, {"error": {"type": "rate_limit_error", "code": "rate_limit_exceeded"}}, {"retry-after": "2"}), [2.0]),
+ ((429, {"error": {"type": "rate_limit_error", "code": "slow_down"}}, {}), [8.0]),
+ ((503, {"error": {"type": "service_unavailable_error", "code": "server_is_overloaded"}}, {}), [8.0]),
+], ids=["rate-limit", "slow-down", "overloaded"])
+def test_a_refusal_openai_documents_as_not_taken_is_sent_again(tmp_path, api, capsys, refused, slept):
+ """429 (a rate limit) and 503 (overloaded) are the two the error-codes guide and the SDKs retry
+ (gen.retry, read 2026-10-13): the image is asked for again after the answer's retry-after or the
+ doubling wait, and published once."""
+ api["script"] = [refused, (200, {"data": [{"b64_json": encoded_image()}]}, {"x-ratelimit-remaining-requests": "9"})]
+ result = gen.generate_image("openai", "x", tmp_path / "out.png")
+ assert len(api["calls"]) == 2 and api["slept"] == slept and result.out.is_file()
+ assert result.extra["rate_limit"] == {"x-ratelimit-remaining-requests": "9"}
+ assert f"[gen] openai refused the request ({refused[0]} {refused[1]['error']['code']}); nothing was made" in capsys.readouterr().err
+
+
[email protected]("code", ["credit_balance_exhausted", "organization_spend_limit_exceeded",
+ "project_spend_limit_exceeded", "organization_usage_limit_exceeded", "insufficient_quota"])
+def test_a_billing_429_asks_the_caller_to_act_and_is_not_sent_again(tmp_path, api, code):
+ api.update(status=429, body={"error": {"type": "insufficient_quota", "code": code}})
+ with pytest.raises(SystemExit, match=f"HTTP 429.*code={code}; no retry or provider fallback"):
+ gen.generate_image("openai", "x", tmp_path / "out.png")
+ assert len(api["calls"]) == 1 and api["slept"] == []
+
+
+def test_a_refusal_still_there_after_two_more_sends_ends_the_call(tmp_path, api):
+ api.update(status=503, body={"error": {"code": "server_is_overloaded"}})
+ with pytest.raises(SystemExit) as error:
+ gen.generate_image("openai", "x", tmp_path / "out.png")
+ assert "(HTTP 503) code=server_is_overloaded; sent 3 times, no provider fallback" in str(error.value)
+ assert len(api["calls"]) == 3 and api["slept"] == [8.0, 16.0]
+
+
@pytest.mark.parametrize("body", [{}, {"data": []}, {"data": [None]}, {"data": [{}, {}]},
{"data": [{"b64_json": "???"}]},
{"data": [{"b64_json": base64.b64encode(b"invalid image").decode()}]},
diff --git a/tests/gen/test_pixel_draw.py b/tests/gen/test_pixel_draw.py
index 010459a..ed0a5df 100644
--- a/tests/gen/test_pixel_draw.py
+++ b/tests/gen/test_pixel_draw.py
@@ -454,8 +454,6 @@ def test_a_spec_file_holds_the_drawing(tmp_path, claude):
spec.write_text(json.dumps({"subject": "a slime", "size": 16, "frames": ["front"], "palette": ["#112233", "#445566"]}),
encoding="utf-8")
claude({})
- with pytest.raises(SystemExit, match=r"--size given both as a flag and in --spec"):
- draw(tmp_path / "a", "--spec", str(spec), "--size", "16")
bad = tmp_path / "bad.json"
bad.write_text(json.dumps({"subject": "x", "effort": "high"}), encoding="utf-8")
with pytest.raises(SystemExit, match=r"unknown key\(s\) effort"):
diff --git a/tests/gen/test_pixel_gates.py b/tests/gen/test_pixel_gates.py
index b101fe8..6a3fbd7 100644
--- a/tests/gen/test_pixel_gates.py
+++ b/tests/gen/test_pixel_gates.py
@@ -320,3 +320,25 @@ def test_recorded_answers_from_the_full_canvas_prompt_pass_g8_with_warnings():
assert gates["ok"] and gates["failed"] == [] and gates["info"] == []
assert gates["warnings"] == ["G8: frames exceed the physical cap 16x15 (reroll candidates): front:14x16",
"G8 the feet are not on the floor row (the safe area's bottom row): front 1 px below it"]
+
+
+def test_g8_reads_a_frames_opaque_box_off_the_image_paths_judgment(monkeypatch):
+ """The opaque box G8 sizes a frame by is `frames.extract.solid_alpha_bbox` (alpha at least 128), the
+ box the image path crops a sprite to — one measure, not a second count of opaque rows here."""
+ from sprite_gen.frames import extract
+
+ real, seen = extract.solid_alpha_bbox, []
+
+ def recording(image, threshold=128):
+ seen.append((image.getchannel("A").tobytes(), threshold))
+ return real(image, threshold)
+
+ monkeypatch.setattr(extract, "solid_alpha_bbox", recording)
+ frame = blob(size=16, top=3, bottom=12)
+ g8 = evaluate({"f": frame}, kind="sprite", rule=FREE16, walk_cycle=False)["G8"]
+ assert seen == [(pg.image_of(frame).getchannel("A").tobytes(), pixel_gates.OPAQUE_MIN)]
+ assert g8["frames"]["f"]["bbox"] == [2, 3, 13, 12] and g8["frames"]["f"]["size"] == [12, 10]
+ # What it answers is what G8 measures: a box it says is wider is a wider frame.
+ monkeypatch.setattr(extract, "solid_alpha_bbox", lambda image, threshold=128: (0, 3, 16, 13))
+ g8 = evaluate({"f": frame}, kind="sprite", rule=FREE16, walk_cycle=False)["G8"]
+ assert g8["frames"]["f"]["bbox"] == [0, 3, 15, 12] and g8["frames"]["f"]["size"] == [16, 10]
diff --git a/tests/gen/test_retry.py b/tests/gen/test_retry.py
new file mode 100644
index 0000000..8fc6cd0
--- /dev/null
+++ b/tests/gen/test_retry.py
@@ -0,0 +1,222 @@
+# SPDX-License-Identifier: Apache-2.0
+"""When an answered provider request is sent again is one rule, `gen.retry`: a POST only when its
+provider documents the answer as a request not taken (Anthropic 429 but its spend cap, 500, 529;
+OpenAI 429 but its billing codes, 503; xAI 429), a GET on any of 429/5xx it may be answered with;
+the wait is the answer's retry-after when this run waits that long, else the doubling `backoff` the
+video polls wait by; twice at most. Every direct provider call asks it — the Anthropic transport, the
+OpenAI and Grok image calls, the facing check and the clip request."""
+from __future__ import annotations
+
+import io
+import json
+import urllib.error
+
+import pytest
+from PIL import Image
+
+from sprite_gen.gen import anthropic_api, facing_vision, grok_provider, openai_provider, retry, video, xai
+from sprite_gen.gen.base import GenRequest
+
+
+def test_the_wait_doubles_to_a_ceiling():
+ assert [retry.backoff(n) for n in (1, 2, 3, 4, 5)] == [8.0, 16.0, 32.0, 60.0, 60.0]
+
+
[email protected](("headers", "seconds"), [
+ ({"retry-after": "3"}, 3.0), ({"retry-after": "0"}, 0.0), ({"retry-after": "soon"}, None),
+ ({"retry-after": "-1"}, None), ({}, None), (None, None),
+])
+def test_retry_after_is_read_when_it_is_a_number(headers, seconds):
+ assert retry.retry_after(headers) == seconds
+
+
+SPEND_CAP = {"type": "error", "error": {"type": "rate_limit_error", "message": "usage limits",
+ "details": {"error_code": "enforced_spend_limit_reached"}}}
+
+
[email protected](("provider", "status", "body", "again"), [
+ ("anthropic", 429, {"error": {"type": "rate_limit_error"}}, True),
+ ("anthropic", 529, {"error": {"type": "overloaded_error"}}, True),
+ ("anthropic", 500, {"error": {"type": "api_error"}}, True),
+ ("anthropic", 504, {"error": {"type": "timeout_error"}}, False), # "timed out while processing"
+ ("anthropic", 502, {}, False),
+ ("anthropic", 503, {}, False),
+ ("anthropic", 429, SPEND_CAP, False),
+ ("anthropic", 400, {"error": {"type": "invalid_request_error"}}, False),
+ ("openai", 429, {"error": {"code": "rate_limit_exceeded"}}, True),
+ ("openai", 429, {"error": {"type": "rate_limit_error", "code": "slow_down"}}, True),
+ ("openai", 503, {"error": {"code": "server_is_overloaded"}}, True),
+ ("openai", 500, {}, False), # "The server had an error while processing your request"
+ ("openai", 429, {"error": {"code": "credit_balance_exhausted"}}, False),
+ ("openai", 429, {"error": {"code": "organization_spend_limit_exceeded"}}, False),
+ ("openai", 429, {"error": {"code": "project_spend_limit_exceeded"}}, False),
+ ("openai", 429, {"error": {"code": "organization_usage_limit_exceeded"}}, False),
+ ("openai", 429, {"error": {"type": "insufficient_quota"}}, False),
+ ("xai", 429, {"code": "resource-exhausted"}, True),
+ ("xai", 500, {}, False),
+ ("xai", 503, {}, False),
+])
+def test_a_post_is_sent_again_only_when_its_provider_documents_the_answer_as_not_taken(provider, status, body, again):
+ wait = retry.again_after(provider, "POST", status, body, None, 1)
+ assert (wait == 8.0) if again else wait is None
+
+
[email protected]("status", [429, 500, 502, 503, 504, 529])
+def test_a_get_buys_nothing_and_is_asked_again(status):
+ assert retry.again_after("anthropic", "GET", status, {}, None, 1) == 8.0
+ assert retry.again_after("anthropic", "GET", 404, {}, None, 1) is None
+
+
+def test_twice_at_most_and_the_answers_own_wait_when_this_run_waits_that_long():
+ assert retry.again_after("xai", "POST", 429, {}, None, 2) == 16.0
+ assert retry.again_after("xai", "POST", 429, {}, None, 3) is None
+ assert retry.again_after("openai", "POST", 429, {}, {"retry-after": "2"}, 1) == 2.0
+ # A longer wait than the run takes is not cut short: the request is not sent again.
+ assert retry.again_after("openai", "POST", 429, {}, {"retry-after": "600"}, 1) is None
+
+
+def test_ask_sends_again_says_so_and_returns_the_last_answer(capsys):
+ answers = [(429, {"error": {"code": "rate_limit_exceeded"}}, {}), (503, {}, {"retry-after": "1"}), (200, {"ok": 1}, {})]
+ slept = []
+ status, body, _headers, asks = retry.ask(lambda: answers.pop(0), provider="openai", who="openai", label="gen",
+ sleep=slept.append, kind=lambda b: (b.get("error") or {}).get("code"))
+ assert (status, body, asks, slept) == (200, {"ok": 1}, 3, [8.0, 1.0])
+ err = capsys.readouterr().err.splitlines()
+ assert err == ["[gen] openai refused the request (429 rate_limit_exceeded); nothing was made — asking again in 8s (1 of 2)",
+ "[gen] openai refused the request (503); nothing was made — asking again in 1s (2 of 2)"]
+
+
+# --- every direct provider call asks it -------------------------------------------------------------
+
+
+def asked(monkeypatch):
+ """Every `retry.ask`: the provider and method it was asked for; the answer is the real one's."""
+ real, seen = retry.ask, []
+
+ def recording(send, **kwargs):
+ seen.append((kwargs["provider"], kwargs.get("method", "POST")))
+ return real(send, **kwargs)
+
+ monkeypatch.setattr(retry, "ask", recording)
+ return seen
+
+
+class _Answer:
+ status = 200
+ headers: dict = {}
+
+ def __init__(self, body: dict):
+ self.body = body
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ pass
+
+ def read(self):
+ return json.dumps(self.body).encode()
+
+
+def _png_b64() -> str:
+ import base64
+
+ buffer = io.BytesIO()
+ Image.new("RGB", (4, 4), (20, 90, 200)).save(buffer, format="PNG")
+ return base64.b64encode(buffer.getvalue()).decode()
+
+
+def test_the_openai_image_call_asks_it(monkeypatch, tmp_path, asked):
+ monkeypatch.setenv("OPENAI_API_KEY", "synthetic")
+ monkeypatch.setattr(openai_provider.urllib.request, "urlopen",
+ lambda request, timeout: _Answer({"data": [{"b64_json": _png_b64()}]}))
+ openai_provider.OpenAIProvider().generate(GenRequest("x", tmp_path / "raw.png"), tmp_path)
+ assert asked == [("openai", "POST")]
+
+
+def test_the_grok_image_call_and_the_facing_check_ask_it(monkeypatch, tmp_path, asked):
+ monkeypatch.setenv("XAI_API_KEY", "synthetic")
+ monkeypatch.setenv("GROK_HOME", str(tmp_path / "no-login"))
+ monkeypatch.setattr(xai.urllib.request, "urlopen", lambda request, timeout: _Answer({"data": [{"b64_json": _png_b64()}]}))
+ grok_provider.GrokProvider().generate(GenRequest("x", tmp_path / "raw.png"), tmp_path)
+ facing_vision.grok_inspect(tmp_path / "raw.png", credential=xai.Credential("t", xai.AUTH_SOURCE_GROK_LOGIN),
+ call=lambda *a, **k: (200, {"output": []}))
+ assert asked == [("xai", "POST"), ("xai", "POST")]
+
+
+def test_the_clip_request_asks_it(tmp_path, asked):
+ still = tmp_path / "still.png"
+ Image.new("RGB", (8, 8), (1, 2, 3)).save(still)
+ calls = []
+
+ def call(method, url, token, body, *, deadline=None):
+ calls.append(method)
+ return (200, {"request_id": "r"}) if method == "POST" else (
+ 200, {"status": "done", "video": {"url": "https://vidgen.x.ai/v/1.mp4"}})
+
+ video.generate_video(video.VideoRequest(image=still, prompt="sway", out=tmp_path / "c.mp4"),
+ credential=video.Credential("t", video.AUTH_SOURCE_GROK_LOGIN), call=call,
+ download=lambda url, token, **_: b"\x00\x00\x00\x18ftypisom" + b"\x00" * 64,
+ sleep=lambda s: None)
+ assert asked == [("xai", "POST")] and calls == ["POST", "GET"]
+
+
+def test_the_anthropic_transport_asks_it_for_its_posts_and_its_reads(monkeypatch, asked):
+ answers = iter([{"id": "msgbatch_1"}, {"id": "msgbatch_1", "processing_status": "in_progress"}])
+ monkeypatch.setattr(anthropic_api.urllib.request, "urlopen", lambda request, timeout: _Answer(next(answers)))
+ anthropic_api.submit_batch("k", [("c1", {})], sleep=lambda s: None)
+ anthropic_api.get_batch("k", "msgbatch_1", sleep=lambda s: None)
+ assert asked == [("anthropic", "POST"), ("anthropic", "GET")]
+
+
+# --- a refusal's body is read by one function ---------------------------------------------------------
+
+
+class _Cut(io.RawIOBase):
+ """A refusal body that breaks on the way."""
+
+ def readinto(self, buffer):
+ import http.client
+
+ raise http.client.IncompleteRead(b'{"error": ', 40)
+
+
+def _refused_cut(request, timeout=None):
+ raise urllib.error.HTTPError(request.full_url, 429, "Too Many Requests", {}, io.BufferedReader(_Cut()))
+
+
+def test_a_refusal_whose_body_broke_is_no_answer_on_every_transport(monkeypatch, tmp_path):
+ """Read whole or not at all (`xai.error_body`): its status alone is not an answer read whole, so none
+ of the three takes it as a refusal to read or to send again."""
+ monkeypatch.setattr(xai.urllib.request, "urlopen", _refused_cut)
+ with pytest.raises(xai.TransportError):
+ xai.http_json("POST", "https://api.x.ai/v1/images/generations", "t", {})
+ monkeypatch.setattr(openai_provider.urllib.request, "urlopen", _refused_cut)
+ with pytest.raises(SystemExit, match="request failed or timed out; no automatic retry"):
+ openai_provider.http_image("https://api.openai.com/v1/images/generations", "t", b"{}", "application/json", timeout=5)
+ monkeypatch.setattr(anthropic_api.urllib.request, "urlopen", _refused_cut)
+ with pytest.raises(anthropic_api.ApiError, match="got no answer") as caught:
+ anthropic_api.submit_batch("k", [("c1", {})], sleep=lambda s: pytest.fail("no answer is never asked again"))
+ assert caught.value.status is None
+
+
+def test_every_transport_reads_a_refusals_body_through_it(monkeypatch):
+ seen = []
+ real = xai.error_body
+
+ def recording(refused, *args, **kwargs):
+ seen.append(refused.code)
+ return real(refused, *args, **kwargs)
+
+ def refused(request, timeout=None):
+ raise urllib.error.HTTPError(request.full_url, 400, "Bad Request", {}, io.BytesIO(b'{"error": "no"}'))
+
+ for module in (xai, openai_provider, anthropic_api):
+ monkeypatch.setattr(module, "error_body", recording)
+ monkeypatch.setattr(module.urllib.request, "urlopen", refused)
+ assert xai.http_json("POST", "https://api.x.ai/v1/x", "t", {}) == (400, {"error": "no"})
+ assert openai_provider.http_image("https://api.openai.com/v1/x", "t", b"{}", "application/json", timeout=5)[:2] == (400, {"error": "no"})
+ with pytest.raises(anthropic_api.ApiError, match=r"\(HTTP 400\)"):
+ anthropic_api.submit_batch("k", [("c1", {})], sleep=lambda s: None)
+ assert seen == [400, 400, 400]
diff --git a/tests/gen/test_video.py b/tests/gen/test_video.py
index f31655d..f139ace 100644
--- a/tests/gen/test_video.py
+++ b/tests/gen/test_video.py
@@ -310,7 +310,7 @@ def test_uninspectable_login_never_permits_api_credit(tmp_path, monkeypatch):
video.resolve_credential(env={"XAI_API_KEY": "console-key"}, now=NOW)
[email protected]("status", [200, 403, 429])
[email protected]("status", [200, 403, 503])
def test_video_uses_subscription_with_api_key_present(tmp_path, monkeypatch, status):
monkeypatch.setenv("GROK_HOME", str(_login_file(tmp_path, key="subscription-token", expires_at="2100-01-01T00:00:00Z")))
monkeypatch.setenv("XAI_API_KEY", "console-key")
@@ -623,11 +623,45 @@ def test_a_poll_refused_for_good_ends_at_once_with_its_status(tmp_path: Path, st
assert HTTP_STATUS.search(message).group(1) == str(status)
-def test_a_refused_submission_is_never_sent_again(tmp_path: Path) -> None:
- """The POST stays unretried (the provider may have taken it); its 429 keeps `(HTTP 429)` for the caller."""
- api = _FakeApi(post=(429, {"error": "slow down"}))
[email protected]("status", [400, 500, 503])
+def test_a_refused_submission_is_never_sent_again(tmp_path: Path, status) -> None:
+ """A POST is sent again only on an answer xAI documents as a request not taken, 429 (gen.retry):
+ any other refusal may have been worked on, and it keeps `(HTTP n)` for the caller."""
+ api = _FakeApi(post=(status, {"error": "refused"}))
message, _ = _refused(tmp_path, api)
assert [call[0] for call in api.calls] == ["POST"]
+ assert HTTP_STATUS.search(message).group(1) == str(status)
+
+
+def test_a_rate_limited_submission_is_sent_again_and_the_poll_timeout_counts_from_the_send_it_answered(
+ tmp_path: Path, monkeypatch, capsys) -> None:
+ """xAI's 429 ("reached the rate limit") made nothing: the POST goes again after the doubling wait the
+ polls wait by, and the poll timeout starts at the send that was accepted, not the first one."""
+ clock, slept, sleep = _clock(monkeypatch)
+ answers = [(429, {"code": "resource-exhausted", "error": "slow down"}), (200, {"request_id": "req-1"})]
+ api = _FakeApi()
+ api.post = None
+ real_call = api.call
+
+ def call(method, url, token, body, *, deadline=None):
+ if method == "POST":
+ api.calls.append((method, url, token, body))
+ return answers.pop(0)
+ assert deadline == 8.0 + 30 # the accepted send came after the 8 s wait
+ return real_call(method, url, token, body, deadline=deadline)
+
+ result = video.generate_video(_request(tmp_path), credential=video.Credential("t", video.AUTH_SOURCE_GROK_LOGIN),
+ call=call, download=api.download, sleep=sleep, poll_timeout=30)
+ assert [c[0] for c in api.calls] == ["POST", "POST", "GET"] and slept == [8.0]
+ assert result.out.read_bytes() == MP4
+ assert "[video] xai refused the request (429 resource-exhausted); nothing was made — asking again in 8s (1 of 2)" \
+ in capsys.readouterr().err
+
+
+def test_a_rate_limit_still_there_after_two_more_sends_keeps_its_status_for_the_caller(tmp_path: Path) -> None:
+ api = _FakeApi(post=(429, {"error": "slow down"}))
+ message, _ = _refused(tmp_path, api)
+ assert [call[0] for call in api.calls] == ["POST"] * 3
assert HTTP_STATUS.search(message).group(1) == "429"
diff --git a/tests/test_cli_kwargs.py b/tests/test_cli_kwargs.py
new file mode 100644
index 0000000..aad1c7f
--- /dev/null
+++ b/tests/test_cli_kwargs.py
@@ -0,0 +1,128 @@
+# SPDX-License-Identifier: Apache-2.0
+"""A verb's `run(**kwargs)` reads its keyword arguments through one function,
+`sprite_gen.util.cli_kwargs.namespace_from_kwargs`: a flag left out takes the parser's default, a
+required one left out or a keyword the parser does not know is a TypeError naming it. Every verb whose
+`run` takes the flags of its parser calls it, with that parser — a second copy of the reading, or a
+reading that drops the required check, is what this file catches."""
+from __future__ import annotations
+
+import argparse
+import ast
+import importlib
+from pathlib import Path
+
+import pytest
+
+from sprite_gen.util.cli_kwargs import namespace_from_kwargs
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--out", required=True)
+ parser.add_argument("--names", nargs="*")
+ parser.add_argument("--hidden", default=argparse.SUPPRESS)
+ parser.add_argument("--ref", action="append", default=[])
+ parser.add_argument("--size", type=int, default=7)
+ return parser
+
+
+def test_a_flag_left_out_takes_the_parsers_default():
+ args = namespace_from_kwargs(parser(), {"out": "x"})
+ assert vars(args) == {"out": "x", "names": [], "hidden": None, "ref": [], "size": 7}
+
+
+def test_a_required_flag_left_out_and_an_unknown_keyword_are_type_errors():
+ with pytest.raises(TypeError, match="missing required argument: out"):
+ namespace_from_kwargs(parser(), {"size": 3})
+ with pytest.raises(TypeError, match=r"unexpected keyword argument\(s\): colour, shade"):
+ namespace_from_kwargs(parser(), {"out": "x", "shade": 1, "colour": 2})
+
+
+# (module, run function, the parser it reads its keywords by)
+VERBS = [
+ ("sprite_gen.compose.compose_atlas", "run", "_build_parser"),
+ ("sprite_gen.compose.compose_cycle", "run", "_build_parser"),
+ ("sprite_gen.compose.compose_gif", "run", "_build_parser"),
+ ("sprite_gen.compose.export_pngs", "run", "_build_parser"),
+ ("sprite_gen.frames.check_visible_magenta", "run", "_build_parser"),
+ ("sprite_gen.frames.extract", "run", "_build_parser"),
+ ("sprite_gen.frames.unpack_atlas", "run", "_build_parser"),
+ ("sprite_gen.gen", "run", "_build_parser"),
+ ("sprite_gen.gen.prepare", "run", "_build_parser"),
+ ("sprite_gen.gen.video", "run", "_build_parser"),
+ ("sprite_gen.gen.video", "run_extend", "_build_extend_parser"),
+ ("sprite_gen.gen.video", "run_edit", "_build_edit_parser"),
+ ("sprite_gen.gen.video", "run_resume", "_build_resume_parser"),
+ ("sprite_gen.gen.pixel_draw", "run", None),
+ ("sprite_gen.qa.correction_loop", "run", "_build_parser"),
+ ("sprite_gen.qa.inspect", "run", "_build_parser"),
+ ("sprite_gen.qa.motion", "run", None),
+ ("sprite_gen.qa.preview", "run", "_build_parser"),
+ ("sprite_gen.qa.score", "run", "_build_parser"),
+]
+
+
+class Asked(Exception):
+ pass
+
+
[email protected](("module", "run", "build"), VERBS, ids=[f"{m.rsplit('.', 1)[-1]}.{r}" for m, r, _ in VERBS])
+def test_every_verb_reads_its_keywords_through_it(monkeypatch, module, run, build):
+ mod = importlib.import_module(module)
+ seen = []
+
+ def spy(parser, kwargs):
+ seen.append((parser, dict(kwargs)))
+ raise Asked
+
+ monkeypatch.setattr(mod, "namespace_from_kwargs", spy)
+ with pytest.raises(Asked):
+ getattr(mod, run)(some_flag=1)
+ ((asked_parser, kwargs),) = seen
+ assert kwargs == {"some_flag": 1}
+ wanted = getattr(mod, build)() if build else None
+ if wanted is not None:
+ assert [a.dest for a in asked_parser._actions] == [a.dest for a in wanted._actions]
+
+
+def test_inspect_run_reads_its_keywords_through_it(monkeypatch, tmp_path):
+ from sprite_gen.qa import inspect
+
+ seen = []
+
+ def spy(parser, kwargs):
+ seen.append(dict(kwargs))
+ raise Asked
+
+ monkeypatch.setattr(inspect, "namespace_from_kwargs", spy)
+ with pytest.raises(Asked):
+ inspect._inspect_run_impl(tmp_path, states="idle")
+ assert seen == [{"run_dir": tmp_path, "states": "idle", "no_write": True}]
+
+
[email protected](("module", "run", "required"), [
+ ("sprite_gen.gen", "run", "out"),
+ ("sprite_gen.gen.video", "run", "out"),
+ ("sprite_gen.gen.pixel_draw", "run", "out_dir"),
+ ("sprite_gen.qa.motion", "run", "source"),
+])
+def test_a_verb_called_without_a_required_flag_names_it(module, run, required):
+ """These four read their keywords by hand before: a required flag left out went on as None."""
+ with pytest.raises(TypeError, match=f"missing required argument: {required}"):
+ getattr(importlib.import_module(module), run)()
+
+
+def test_no_function_reads_a_parsers_actions_but_these():
+ """`parser._actions` read anywhere else in the engine is a second reading of keyword arguments,
+ the copy this file exists to keep out. `extract._nondefault_args` asks another question of its
+ parser: which flags a run set off their defaults, for the manifest."""
+ readers = set()
+ for path in sorted((ROOT / "sprite_gen").rglob("*.py")):
+ for function in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
+ if isinstance(function, (ast.FunctionDef, ast.AsyncFunctionDef)) and any(
+ isinstance(node, ast.Attribute) and node.attr == "_actions" for node in ast.walk(function)):
+ readers.add((path.relative_to(ROOT).as_posix(), function.name))
+ assert readers == {("sprite_gen/util/cli_kwargs.py", "namespace_from_kwargs"),
+ ("sprite_gen/frames/extract.py", "_nondefault_args")}
diff --git a/tests/test_hexcolor.py b/tests/test_hexcolor.py
new file mode 100644
index 0000000..facc30a
--- /dev/null
+++ b/tests/test_hexcolor.py
@@ -0,0 +1,83 @@
+# SPDX-License-Identifier: Apache-2.0
+"""A colour written `#RRGGBB` is read by one function and written by one, `sprite_gen.util.hexcolor`:
+six hex digits, the `#` optional, blanks around them ignored — a sign, an underscore or a seventh
+character is not a colour. Every verb that takes a hex colour reads it there and words the error with
+its own flag; recolor writes lower case, everything else upper case."""
+from __future__ import annotations
+
+import argparse
+import importlib
+
+import pytest
+
+from sprite_gen.util.hexcolor import format_hex, parse_hex
+
+
[email protected](("text", "rgb"), [
+ ("#A1b2C3", (0xA1, 0xB2, 0xC3)), ("a1b2c3", (0xA1, 0xB2, 0xC3)), (" #00ff7f\n", (0, 255, 127)),
+])
+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", ""])
+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)."""
+ with pytest.raises(ValueError, match="expected #RRGGBB"):
+ parse_hex(text)
+
+
+def test_it_writes_upper_case_and_lower_case_for_recolor():
+ assert format_hex((10, 200, 255)) == "#0AC8FF"
+ assert format_hex((10, 200, 255, 128)) == "#0AC8FF"
+ assert format_hex((10, 200, 255), lower=True) == "#0ac8ff"
+
+
+# (module, how the verb reads a colour, what it says when it cannot)
+READERS = [
+ ("sprite_gen.effects.recolor", lambda m: m._resolve_map({"#-1-1-1": "#000000"}, "spec.json", "gold"), SystemExit),
+ ("sprite_gen.gen.prepare", lambda m: m.parse_hex_color("#-1-1-1"), SystemExit),
+ ("sprite_gen.frames.slice_sheet", lambda m: m.parse_chroma_key("#-1-1-1"), ValueError),
+ ("sprite_gen.qa.handed", lambda m: m.parse_marker("#-1-1-1"), SystemExit),
+ ("sprite_gen.effects.shadow", lambda m: m._parse_color("#-1-1-1"), argparse.ArgumentTypeError),
+]
+
+
[email protected](("module", "read", "refusal"), READERS, ids=[m.rsplit(".", 1)[-1] for m, _, _ in READERS])
+def test_every_verb_reads_a_colour_through_it(monkeypatch, module, read, refusal):
+ mod = importlib.import_module(module)
+ seen = []
+
+ def spy(text):
+ seen.append(text)
+ return parse_hex(text)
+
+ monkeypatch.setattr(mod, "parse_hex", spy)
+ with pytest.raises(refusal):
+ read(mod)
+ assert seen and seen[0].strip().lower() == "#-1-1-1"
+
+
+def test_the_pixel_grid_reads_and_the_gates_write_through_it(monkeypatch):
+ from sprite_gen.gen import pixel_gates, pixel_grid
+
+ read, written = [], []
+ monkeypatch.setattr(pixel_grid, "parse_hex", lambda text: read.append(text) or parse_hex(text))
+ monkeypatch.setattr(pixel_gates, "format_hex", lambda rgb: written.append(rgb) or format_hex(rgb))
+ pixel = pixel_grid.hex_pixel("#0AC8FF")
+ assert pixel == (10, 200, 255, 255) and read == ["#0AC8FF"]
+ assert pixel_gates.colors_used({"f": [[pixel, (0, 0, 0, 0)]]}) == ["#0AC8FF"] and written == [pixel]
+
+
+def test_recolor_writes_lower_case_through_it(monkeypatch, tmp_path):
+ from PIL import Image
+
+ from sprite_gen.effects import recolor
+
+ calls = []
+ monkeypatch.setattr(recolor, "format_hex", lambda rgb, **kw: calls.append(kw) or format_hex(rgb, **kw))
+ base = tmp_path / "base.png"
+ Image.new("RGBA", (2, 1), (10, 200, 255, 255)).save(base)
+ palette = recolor.extract_palette(base)
+ assert [color["hex"] for color in palette["colors"]] == ["#0ac8ff"] and calls == [{"lower": True}]
diff --git a/tests/video/test_video_pipeline.py b/tests/video/test_video_pipeline.py
index 2d115dd..ea92fd4 100644
--- a/tests/video/test_video_pipeline.py
+++ b/tests/video/test_video_pipeline.py
@@ -678,7 +678,9 @@ def test_motion_templates_do_not_assume_a_body_plan() -> None:
assert word not in text, (state, word)
-def test_run_set_staggers_retries_429_and_tables_failures(tmp_path: Path, monkeypatch) -> None:
+def test_run_set_runs_each_clip_once_and_tables_failures(tmp_path: Path, monkeypatch) -> None:
+ """A 429 is sent again inside `sprite-gen video` (gen.retry); the set does not run the clip a second
+ time on top of that, which would make every one of its POSTs a second retry loop."""
monkeypatch.setattr(batch_mod.facing_mod.vision, "grok_inspect", lambda *a, **kw: ("right", {}))
base = _still(tmp_path)
calls: list[tuple[str, float]] = []
@@ -687,18 +689,15 @@ def test_run_set_staggers_retries_429_and_tables_failures(tmp_path: Path, monkey
def fake_video(image, prompt, out, report, *, duration, resolution, log):
calls.append((out.parent.name, _time.monotonic()))
item = out.parent.name
- if item == "side-run" and sum(1 for c in calls if c[0] == item) == 1:
- log.write_text("video: generation request refused (HTTP 429): resource-exhausted")
- return 1
if item == "side-jump":
- log.write_text("video: generation failed for good")
+ log.write_text("video: generation request refused (HTTP 429): resource-exhausted")
return 1
out.write_bytes(b"\x00\x00\x00\x18ftypisom")
report.write_text("{}")
log.write_text("ok")
return 0
- monkeypatch.setattr(batch_mod.time, "sleep", lambda s: None) # no real backoff waits
+ monkeypatch.setattr(batch_mod.time, "sleep", lambda s: None) # no real stagger waits
monkeypatch.setattr(frames_mod, "run_frames", lambda clip, out_dir, **kw: {"fps": 24.0, "frames": 10, "alpha_zero_pct_min": 60.0, "alpha_zero_pct_max": 70.0, "keyed_dir": str(out_dir / "keyed")})
monkeypatch.setattr(batch_mod.frames_mod, "run_frames", frames_mod.run_frames)
monkeypatch.setattr(batch_mod.loop_mod, "run_loop", lambda frames_dir, out_dir, **kw: {"cycle": {"length": 12, "period_global": 12, "ratio": 0.3, "review_recommended": kw["state"] == "run"}, "resampled_seam_ratio": 0.5, "n_out": 12, "gif": {"file": "x.gif"}, "webp": {"file": "x.webp"}, "strip": {"path": "x.png"}})
@@ -707,8 +706,9 @@ def test_run_set_staggers_retries_429_and_tables_failures(tmp_path: Path, monkey
by = {r["item"]: r for r in payload["items"]}
assert by["side-walk"]["ok"] and by["side-walk"]["clip"]["attempts"] == [0]
- assert by["side-run"]["ok"] and by["side-run"]["clip"]["attempts"] == [1, 0] # one 429 retry
+ assert by["side-run"]["ok"] and by["side-run"]["clip"]["attempts"] == [0]
assert not by["side-jump"]["ok"] and "clip generation failed" in by["side-jump"]["error"]
+ assert by["side-jump"]["clip"]["attempts"] == [1] and [c[0] for c in calls].count("side-jump") == 1 # never run again by the set
assert by["side-run"]["loop"]["review_recommended"] is True
assert by["side-walk"]["loop"]["review_recommended"] is False
assert payload["failed"] == ["side-jump"]