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 codex login reading, metered calls announced on the terminal

Soohong Kim6299458056e4
diff --git a/tests/audio/test_sound.py b/tests/audio/test_sound.py
index d431678..060e761 100644
--- a/tests/audio/test_sound.py
+++ b/tests/audio/test_sound.py
@@ -223,8 +223,16 @@ def test_provider_contract_and_safe_retry(monkeypatch, capsys):
assert requests[0].full_url.endswith('/sound-generation?output_format=mp3_44100_128')
assert json.loads(requests[0].data) == {'text':'Impact', 'duration_seconds':3.0,
'loop':True, 'model_id':'eleven_text_to_sound_v2', 'prompt_influence':.3}
- assert meta['character_cost'] == 120
- assert 'secret-key' not in capsys.readouterr().err
+ assert meta['character_cost'] == 120 and meta['auth_source'] == 'ELEVENLABS_API_KEY'
+ err = capsys.readouterr().err
+ assert 'secret-key' not in err
+ assert '[gen] elevenlabs: running on ELEVENLABS_API_KEY — this is a per-call API charge' in err
+ monkeypatch.setenv('ELEVENLABS_API_KEY', ' ')
+ with pytest.raises(ValueError, match='sound: ELEVENLABS_API_KEY is set but empty'):
+ provider.generate(req)
+ monkeypatch.delenv('ELEVENLABS_API_KEY')
+ with pytest.raises(ValueError, match='ELEVENLABS_API_KEY is required for a new sound request'):
+ provider.generate(req)
bgm = provider.request('bgm', 'Adventure', 8, True)
assert bgm['body'] == {'prompt':'Adventure', 'music_length_ms':8000,
'model_id':'music_v1', 'force_instrumental':True}
diff --git a/tests/gen/test_codex_login.py b/tests/gen/test_codex_login.py
new file mode 100644
index 0000000..70398dd
--- /dev/null
+++ b/tests/gen/test_codex_login.py
@@ -0,0 +1,107 @@
+# SPDX-License-Identifier: Apache-2.0
+"""How codex is signed in is one question (`codex_provider.codex_login`) for the default provider
+resolution, `generate`, the facing check and the guided workflow: ChatGPT is the subscription, an
+API key is billed per call and said on stderr before the request leaves, and a codex that is not
+signed in is not usable, with its reason. No codex binary: a fake `subprocess.run`."""
+from __future__ import annotations
+
+import base64
+import io
+import subprocess
+from types import SimpleNamespace
+
+import pytest
+from PIL import Image
+
+from sprite_gen import gen
+from sprite_gen.gen import codex_provider
+from sprite_gen.gen.base import GenRequest
+from sprite_gen.workflow.access import probe_access
+
+
+def status(code: int, said: str):
+ return lambda cmd, **kw: SimpleNamespace(returncode=code, stdout=said, stderr="")
+
+
[email protected]("run, expected", [
+ (status(0, "Logged in using ChatGPT\n"), codex_provider.CodexLogin("codex-login")),
+ (status(0, "Logged in using an API key - sk-proj-***\n"), codex_provider.CodexLogin("codex-api-key")),
+ (status(1, "Not logged in\n"), codex_provider.CodexLogin(None, "codex not logged in (codex login status exit 1)")),
+])
+def test_the_login_is_chatgpt_an_api_key_or_not_usable(monkeypatch, run, expected):
+ monkeypatch.setattr(codex_provider.subprocess, "run", run)
+ assert codex_provider.codex_login() == expected
+
+
+def test_no_cli_and_a_failed_probe_are_not_usable_with_the_reason(monkeypatch):
+ def missing(cmd, **kw):
+ raise FileNotFoundError(cmd[0])
+
+ def stuck(cmd, **kw):
+ raise subprocess.TimeoutExpired(cmd, 15)
+
+ monkeypatch.setattr(codex_provider.subprocess, "run", missing)
+ assert codex_provider.codex_login() == codex_provider.CodexLogin(None, "codex CLI not found on PATH")
+ monkeypatch.setattr(codex_provider.subprocess, "run", stuck)
+ assert codex_provider.codex_login() == codex_provider.CodexLogin(None, "codex login-status probe failed: TimeoutExpired")
+
+
+def test_the_default_resolution_asks_the_same_question(monkeypatch):
+ monkeypatch.delenv(gen.DEFAULT_PROVIDER_ENV, raising=False)
+ monkeypatch.setattr(codex_provider, "codex_login", lambda: codex_provider.CodexLogin(None, "codex CLI not found on PATH"))
+ assert gen.resolve_default_provider() == ("grok", {"from": "codex", "to": "grok", "default_source": "hard-default",
+ "reason": "codex CLI not found on PATH"})
+ monkeypatch.setattr(codex_provider, "codex_login", lambda: codex_provider.CodexLogin("codex-api-key"))
+ assert gen.resolve_default_provider() == ("codex", None)
+
+
+def _png() -> str:
+ buffer = io.BytesIO()
+ Image.new("RGBA", (4, 4), (255, 0, 0, 255)).save(buffer, format="PNG")
+ return base64.b64encode(buffer.getvalue()).decode()
+
+
+def _generate(monkeypatch, tmp_path, login):
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path))
+ monkeypatch.setattr(codex_provider, "codex_login", lambda: login)
+ asked = []
+
+ def run(cmd, **kw):
+ asked.append(cmd)
+ return SimpleNamespace(returncode=0, stdout='{"type":"thread.started","thread_id":"aaaa-bbbb"}\n', stderr="")
+
+ monkeypatch.setattr(codex_provider.subprocess, "run", run)
+ monkeypatch.setattr(codex_provider, "_resolve_rollout", lambda *a, **k: tmp_path / "rollout.jsonl")
+ monkeypatch.setattr(codex_provider, "_collect_inline_results", lambda _p: [codex_provider.InlineResult(_png())])
+ result = codex_provider.CodexProvider(keep_session=True).generate(GenRequest(prompt="a slime", raw=tmp_path / "raw.png"),
+ tmp_path)
+ return result, asked
+
+
+def test_generate_on_the_subscription_says_nothing_and_records_it(monkeypatch, tmp_path, capsys):
+ result, asked = _generate(monkeypatch, tmp_path, codex_provider.CodexLogin("codex-login"))
+ assert result.extra["auth_source"] == "codex-login" and len(asked) == 1
+ assert "per-call API charge" not in capsys.readouterr().err
+
+
+def test_generate_on_an_api_key_login_announces_the_charge_and_records_it(monkeypatch, tmp_path, capsys):
+ result, _ = _generate(monkeypatch, tmp_path, codex_provider.CodexLogin("codex-api-key"))
+ assert result.extra["auth_source"] == "codex-api-key"
+ assert ("[gen] codex: running on the API key codex is signed in with — this is a per-call API charge, not a "
+ "subscription — `codex login` signs your ChatGPT subscription in.") in capsys.readouterr().err
+
+
+def test_generate_without_a_login_is_refused_before_codex_runs(monkeypatch, tmp_path):
+ with pytest.raises(SystemExit, match=r"codex-gen: codex not logged in \(codex login status exit 1\); `codex login`"):
+ _generate(monkeypatch, tmp_path, codex_provider.CodexLogin(None, "codex not logged in (codex login status exit 1)"))
+
+
[email protected]("login, expected", [
+ (codex_provider.CodexLogin("codex-login"), {"login": "ready", "billing": "subscription"}),
+ (codex_provider.CodexLogin("codex-api-key"), {"login": "ready", "billing": "api-credit"}),
+ (codex_provider.CodexLogin(None, "codex CLI not found on PATH"), {"login": "unavailable", "billing": "subscription"}),
+])
+def test_the_workflow_reads_the_same_login(monkeypatch, login, expected):
+ monkeypatch.setattr(codex_provider, "codex_login", lambda: login)
+ state = probe_access("codex")
+ assert {k: state[k] for k in expected} == expected
diff --git a/tests/gen/test_codex_rollout_resolution.py b/tests/gen/test_codex_rollout_resolution.py
index 4e48e1f..1673dd5 100644
--- a/tests/gen/test_codex_rollout_resolution.py
+++ b/tests/gen/test_codex_rollout_resolution.py
@@ -143,6 +143,7 @@ def test_generate_reads_rollout_from_nondefault_codex_home(tmp_path: Path, monke
return _Completed()
monkeypatch.setattr(codex_provider.subprocess, "run", _fake_run)
+ monkeypatch.setattr(codex_provider, "codex_login", lambda: codex_provider.CodexLogin(codex_provider.AUTH_SOURCE_LOGIN))
workdir = tmp_path / "work"
workdir.mkdir()
raw = workdir / "raw.png"
@@ -181,6 +182,7 @@ def test_generate_reads_rollout_from_default_codex_home(tmp_path: Path, monkeypa
return _Completed()
monkeypatch.setattr(codex_provider.subprocess, "run", _fake_run)
+ monkeypatch.setattr(codex_provider, "codex_login", lambda: codex_provider.CodexLogin(codex_provider.AUTH_SOURCE_LOGIN))
workdir = tmp_path / "work"
workdir.mkdir()
raw = workdir / "raw.png"
diff --git a/tests/gen/test_facing.py b/tests/gen/test_facing.py
index 89c1b8e..5659250 100644
--- a/tests/gen/test_facing.py
+++ b/tests/gen/test_facing.py
@@ -9,7 +9,7 @@ import pytest
from PIL import Image, ImageOps
from sprite_gen import gen
-from sprite_gen.gen import facing, facing_vision, openai_provider, grok_provider, xai
+from sprite_gen.gen import codex_provider, facing, facing_vision, openai_provider, grok_provider, xai
from sprite_gen.gen.base import ProviderRun
FIXTURES = Path(__file__).parents[1] / "fixtures" / "facing"
@@ -224,6 +224,7 @@ def test_codex_vision_reads_new_answer_and_scrubs_identity(monkeypatch, tmp_path
Path(command[command.index("-o") + 1]).write_text('right')
return SimpleNamespace(returncode=0)
monkeypatch.setattr(facing_vision.subprocess, "run", run)
+ monkeypatch.setattr(codex_provider, "codex_login", lambda: codex_provider.CodexLogin(codex_provider.AUTH_SOURCE_LOGIN))
text, metadata = facing_vision.codex_inspect(FIXTURES / "left.png", tmp_path)
assert text == "right" and metadata["auth_source"] == "codex-login"
assert len(seen) == 1 and "--ephemeral" in seen[0][0] and "read-only" in seen[0][0]
@@ -271,15 +272,12 @@ def test_gen_cli_preserve_default_leaves_reference_prompt_unchanged(tmp_path, mo
def test_gen_set_reference_row_keeps_its_prompt(tmp_path, monkeypatch):
- import subprocess
from sprite_gen.gen import gen_set
backend = Backend()
monkeypatch.setattr(gen, "_make_provider", lambda *a, **kw: backend)
prompt = tmp_path / "prompt.txt"
prompt.write_text("a front-facing robot animation row")
- def run(command, **kwargs):
- return SimpleNamespace(returncode=gen.main(command[4:]))
- monkeypatch.setattr(subprocess, "run", run)
+ monkeypatch.setattr(gen_set, "run_logged", lambda command, log: gen.main(command[4:]))
assert gen_set.run_gen_cli(prompt, tmp_path / "out.png", [FIXTURES / "front.png"],
tmp_path / "report.json", provider="openai", model=None,
log=tmp_path / "log.txt") == 0
diff --git a/tests/gen/test_gen.py b/tests/gen/test_gen.py
index 8cc70d1..753422f 100644
--- a/tests/gen/test_gen.py
+++ b/tests/gen/test_gen.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import base64
import json
+import sys
from pathlib import Path
import pytest
@@ -75,6 +76,17 @@ def test_env_api_key_is_the_key_none_or_a_refusal_of_an_empty_one() -> None:
gen_base.env_api_key("SOME_API_KEY", {"SOME_API_KEY": " "}, who="v")
+def test_run_logged_keeps_everything_in_the_log_and_shows_the_charge_and_the_switch(tmp_path, capsys) -> None:
+ lines = ["working", f"[gen] grok: running on XAI_API_KEY — {gen_base.API_CHARGE_WORDS} (q).",
+ f"sprite-gen gen: default provider 'codex' unavailable (x) {gen_base.PROVIDER_SWITCH_WORDS} 'grok'.", "done"]
+ script = "import sys\n" + "".join(f"print({line!r}, file=sys.stderr if {i} % 2 else sys.stdout)\n"
+ for i, line in enumerate(lines))
+ log = tmp_path / "child.log"
+ assert gen_base.run_logged([sys.executable, "-c", script + "raise SystemExit(3)"], log) == 3
+ assert sorted(log.read_text(encoding="utf-8").splitlines()) == sorted(lines)
+ assert sorted(capsys.readouterr().err.splitlines()) == sorted(lines[1:3])
+
+
def test_provider_binary_resolves_windows_style_path_shims(monkeypatch) -> None:
monkeypatch.setattr(gen_base.shutil, "which", lambda name: f"C:/tools/{name}.CMD")
assert gen_base.provider_binary("codex") == "C:/tools/codex.CMD"
@@ -101,6 +113,7 @@ def test_provider_run_uses_scrubbed_env(tmp_path: Path, monkeypatch) -> None:
# Short-circuit codex's post-run rollout parsing — we only assert the env.
monkeypatch.setattr(codex_provider.subprocess, "run", _fake_codex_run)
+ monkeypatch.setattr(codex_provider, "codex_login", lambda: codex_provider.CodexLogin(codex_provider.AUTH_SOURCE_LOGIN))
monkeypatch.setattr(
codex_provider,
"_resolve_rollout",
@@ -134,6 +147,7 @@ def test_provider_commands_use_the_single_resolved_binary(tmp_path: Path, monkey
return _CodexCompleted()
monkeypatch.setattr(codex_provider.subprocess, "run", fake_codex)
+ monkeypatch.setattr(codex_provider, "codex_login", lambda: codex_provider.CodexLogin(codex_provider.AUTH_SOURCE_LOGIN))
monkeypatch.setattr(codex_provider, "_resolve_rollout", lambda *_args, **_kwargs: tmp_path / "rollout.jsonl")
monkeypatch.setattr(
codex_provider,
diff --git a/tests/gen/test_gen_set.py b/tests/gen/test_gen_set.py
index 242ebf8..284e8f3 100644
--- a/tests/gen/test_gen_set.py
+++ b/tests/gen/test_gen_set.py
@@ -124,17 +124,13 @@ def test_gen_set_direction_run_generates_anchors_first_and_stops_on_anchor_failu
def test_run_gen_cli_invokes_the_cli_gen_verb(tmp_path: Path, monkeypatch) -> None:
"""The row call is `python -m sprite_gen.cli gen …` — the package has no __main__, so
`-m sprite_gen.gen` is not a runnable module (2026-09-09 real-run regression)."""
- import subprocess
-
captured: dict = {}
- def fake_run(cmd, **kw):
+ def fake_run(cmd, log):
captured["cmd"] = cmd
- class R: # noqa: D401 — minimal CompletedProcess stand-in
- returncode = 0
- return R()
+ return 0
- monkeypatch.setattr(subprocess, "run", fake_run)
+ monkeypatch.setattr(gen_set, "run_logged", fake_run)
log = tmp_path / "x.log"
rc = gen_set.run_gen_cli(tmp_path / "p.txt", tmp_path / "o.png", [tmp_path / "a.png", tmp_path / "b.png"], tmp_path / "r.json", provider="codex", model=None, log=log)
assert rc == 0
diff --git a/tests/gen/test_grok_provider.py b/tests/gen/test_grok_provider.py
index 9201ce3..b3a9642 100644
--- a/tests/gen/test_grok_provider.py
+++ b/tests/gen/test_grok_provider.py
@@ -182,10 +182,8 @@ def test_timeout_does_not_repeat_billable_request(tmp_path, api, monkeypatch):
assert len(calls) == 1
[email protected]("video", [False, True])
-def test_access_uses_api_key_without_grok_binary(api, monkeypatch, video):
- monkeypatch.setattr(access.shutil, "which", lambda _: None)
- result = access.probe_access("grok", video=video)
+def test_access_uses_api_key_without_grok_binary(api, monkeypatch):
+ result = access.probe_access("grok")
assert result["login"] == "ready" and result["billing"] == "api-credit"
@@ -359,7 +357,7 @@ def test_a_rejected_credential_names_the_code_too(tmp_path, api):
with pytest.raises(SystemExit) as error:
gen.generate_image("grok", "x", tmp_path / "out.png")
assert str(error.value) == ("grok-gen: credential XAI_API_KEY rejected (HTTP 401) code=unauthenticated:bad-credentials; "
- 'check XAI_API_KEY: {"code": "unauthenticated:bad-credentials", "error": "[redacted]"}')
+ 'check the XAI_API_KEY value: {"code": "unauthenticated:bad-credentials", "error": "[redacted]"}')
def test_an_xai_key_and_a_signed_url_in_the_body_are_masked(tmp_path, api):
diff --git a/tests/video/test_attack_motion.py b/tests/video/test_attack_motion.py
index 4d97435..0a11c29 100644
--- a/tests/video/test_attack_motion.py
+++ b/tests/video/test_attack_motion.py
@@ -57,11 +57,11 @@ def test_a_callers_motion_replaces_the_built_in_sentence() -> None:
def test_video_cli_pins_the_last_frame_only_when_asked(tmp_path: Path, monkeypatch) -> None:
seen: list[list[str]] = []
- def fake_run(cmd, **kw):
+ def fake_run(cmd, log):
seen.append(cmd)
- return subprocess.CompletedProcess(cmd, 0)
+ return 0
- monkeypatch.setattr(batch_mod.subprocess, "run", fake_run)
+ monkeypatch.setattr(batch_mod, "run_logged", fake_run)
common = dict(duration=4, resolution="480p", log=tmp_path / "log")
batch_mod.run_video_cli(tmp_path / "canvas.png", "p", tmp_path / "c.mp4", tmp_path / "r.json", **common)
batch_mod.run_video_cli(tmp_path / "canvas.png", "p", tmp_path / "c.mp4", tmp_path / "r.json", last_frame=tmp_path / "canvas.png", **common)
diff --git a/tests/workflow/test_workflow.py b/tests/workflow/test_workflow.py
index ac0cbc9..2620465 100644
--- a/tests/workflow/test_workflow.py
+++ b/tests/workflow/test_workflow.py
@@ -10,6 +10,7 @@ from types import SimpleNamespace
import pytest
+from sprite_gen.gen import codex_provider
from sprite_gen.workflow import access, guide, preferences
from sprite_gen.workflow.catalog import FIELDS, FLOWS, MOTION_METHODS
from sprite_gen.gen.video import AUTH_SOURCE_API_KEY
@@ -23,8 +24,8 @@ def isolated_settings(tmp_path, monkeypatch):
@pytest.fixture
def ready_login(monkeypatch):
seen = []
- def probe(provider, *, video=False):
- seen.append((provider, video))
+ def probe(provider):
+ seen.append(provider)
return {"provider": provider, "login": "ready", "subscription": "unknown", "quota": "unknown",
"billing": "subscription", "reason": "unverified media access"}
monkeypatch.setattr(guide, "probe_access", probe)
@@ -105,7 +106,7 @@ def test_first_sprite_request_and_existing_base(ready_login, tmp_path):
ready_login.clear()
view = guide.guide("sprite", base_image=base, choices={"motion_method": "gpt-rows"}, confirmed_access=("codex",))
assert view["status"] == "ready" and view["pipeline"]["image_provider"] is None
- assert ready_login == [("codex", False)]
+ assert ready_login == ["codex"]
assert "extract" in view["pipeline"]["steps"]
@@ -157,18 +158,19 @@ def test_finish_requires_result_and_generation_choices(tmp_path):
def test_access_probe_redacts_output_and_separates_auth_from_subscription(monkeypatch):
- monkeypatch.setattr(access.shutil, "which", lambda _: "/fake/codex")
- monkeypatch.setattr(access.subprocess, "run", lambda *a, **k: SimpleNamespace(returncode=0, stdout="Logged in using ChatGPT", stderr="synthetic-secret"))
+ monkeypatch.setattr(codex_provider.subprocess, "run", lambda *a, **k: SimpleNamespace(returncode=0, stdout="Logged in using ChatGPT", stderr="synthetic-secret"))
result = access.probe_access("codex")
- assert result["login"] == "ready" and result["subscription"] == "unknown"
+ assert result["login"] == "ready" and result["subscription"] == "unknown" and result["billing"] == "subscription"
+ assert "synthetic-secret" not in json.dumps(result)
+ monkeypatch.setattr(codex_provider.subprocess, "run", lambda *a, **k: SimpleNamespace(returncode=0, stdout="Logged in using an API key - synthetic-secret", stderr=""))
+ result = access.probe_access("codex")
+ assert result["login"] == "ready" and result["billing"] == "api-credit"
assert "synthetic-secret" not in json.dumps(result)
- monkeypatch.setattr(access.subprocess, "run", lambda *a, **k: SimpleNamespace(returncode=0, stdout="API key authentication", stderr=""))
- assert access.probe_access("codex")["login"] == "unknown"
def test_video_api_key_requires_own_confirmation(monkeypatch, tmp_path):
monkeypatch.setattr(access, "resolve_credential", lambda **kw: SimpleNamespace(source=AUTH_SOURCE_API_KEY))
- actual = access.probe_access("grok", video=True)
+ actual = access.probe_access("grok")
assert actual["billing"] == "api-credit"
monkeypatch.setattr(guide, "probe_access", lambda *a, **k: actual)
base = tmp_path / "base.png"