signal-bot/tests/test_cli.py
Krzysztof kuhy Rudnicki 6bde3493a4 feat: rewrite the bot so it runs, and gate it like the other repos
The bot did not work. `run.sh` started a FastAPI app whose
`@app.on_event("startup")` awaited `asyncio.gather()` on two infinite
tasks, so uvicorn never finished starting up and no HTTP was ever served;
the readme's `python main.py` was a no-op with no `__main__` block and no
`uvicorn.run()` call. All three CI workflows were red, one referencing an
`environment.yml` that does not exist.

Rewritten as a package behind an injectable transport seam, which is what
makes the offline environment possible.

Bugs fixed:
- startup deadlock: lifespan spawns the loops instead of awaiting them
- sticker filter read dataMessage.sticker even on syncMessage envelopes, so
  the account's own stickers were never filtered (e038772, 53028cc, 07fa90d,
  2416cef all fought this symptom)
- no websocket reconnect: a container restart killed the bot silently
- blocking `requests` inside async functions stalled the event loop
- every counted message DMed the whole tally to the bot itself
- images were written to CWD under a filename taken from the remote URL
- one global 10s cooldown shared across all users and commands
- dead code: RECEIVE_URL, get_attachments (no call site), USER_MESSAGE_COUNT
- .env.sample declared PRIMARY/SECONDARY_PHONE_NUMBER and MODE, none read

Scoping is now an enforced invariant. A linked device receives every DM and
every group on the account; GROUP_ID was the only thing narrowing that and
defaulted to "". Config refuses to start unscoped, direct messages are
dropped explicitly rather than by a falsy check, and a scenario asserts that
DMs and other groups produce zero outbound messages.

Offline environment: fake_signal/ serves the real protocol surface, so the
unmodified bot connects to it by pointing API_BASE_URL at it. scripts/e2e.sh
boots both, replays 7 scenarios and exits non-zero on mismatch. A local
Signal server is not achievable (signal-cli compiles its endpoints and trust
store in; Signal-Server needs FoundationDB), so faking this boundary is the
only way to test every feature without an account.

Transport pinned to bbernhard/signal-cli-rest-api:0.100 with
MODE=json-rpc-native. The readme pinned 0.167-dev; the dev tag series counts
separately, so that was older than 0.100, not newer. /v1/receive is only a
WebSocket in a json-rpc mode, so the mode is verified at startup.

Repo standards: ruff select=ALL, mypy --strict, 189 tests at 100% branch
coverage, 250-line cap, exact pins at newest stable, shared gates delegated
to ~/utils, one CI workflow replacing three red ones. No noqa, no
type: ignore, no coverage omits anywhere.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013yaBT45KhHqxTKVCTA87iy
2026-08-29 13:05:42 +02:00

119 lines
4.3 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The scenario injector CLI, including its exit codes."""
from __future__ import annotations
import runpy
import sys
from pathlib import Path
import httpx
import pytest
from fake_signal import cli
from fake_signal.scenario import Expectation, Injection, Scenario
GROUPS = {"watched": "W==", "reply": "R==", "other": "O=="}
class Recorder:
"""Stands in for the fake server's control plane."""
def __init__(self, sent: list[dict]) -> None:
self.sent = sent
self.injected: list[str] = []
def __call__(self, request: httpx.Request) -> httpx.Response:
path = request.url.path
if path == "/_control/inject":
self.injected.append(request.content.decode())
return httpx.Response(200, json={"delivered": 1})
if path == "/_control/sent":
return httpx.Response(200, json=self.sent)
return httpx.Response(200, json={"status": "ok"})
def _patch_client(monkeypatch: pytest.MonkeyPatch, recorder: Recorder) -> None:
real = httpx.AsyncClient
def factory(**kwargs: object) -> httpx.AsyncClient:
# base_url must survive: run_scenario uses relative paths.
return real(
transport=httpx.MockTransport(recorder),
base_url=str(kwargs.get("base_url", "http://x")),
)
monkeypatch.setattr(cli.httpx, "AsyncClient", factory)
async def test_run_scenario_injects_and_passes(monkeypatch: pytest.MonkeyPatch) -> None:
recorder = Recorder([{"base64_attachments": ["A"], "recipients": ["R=="]}])
_patch_client(monkeypatch, recorder)
scenario = Scenario("s", inject=[Injection(text="!cat")], expect=[Expectation(kind="image")])
failures = await cli.run_scenario("http://x", scenario, GROUPS, settle=0)
assert failures == []
assert "!cat" in recorder.injected[0]
async def test_run_scenario_reports_a_mismatch(monkeypatch: pytest.MonkeyPatch) -> None:
_patch_client(monkeypatch, Recorder([]))
scenario = Scenario("s", expect=[Expectation(kind="image")])
assert await cli.run_scenario("http://x", scenario, GROUPS, settle=0)
def test_parse_args_requires_the_group_ids() -> None:
args = cli.parse_args(["a.yaml", "--group-id", "W==", "--group-id-send", "R=="])
assert args.scenarios == [Path("a.yaml")]
assert args.group_id == "W=="
def test_parse_args_rejects_missing_groups() -> None:
with pytest.raises(SystemExit):
cli.parse_args(["a.yaml"])
def _scenario_file(tmp_path: Path, expect: str) -> Path:
path = tmp_path / "s.yaml"
path.write_text(f"name: demo\ninject:\n - {{text: '!cat'}}\n{expect}", encoding="utf-8")
return path
def test_main_exits_zero_when_every_scenario_passes(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
_patch_client(monkeypatch, Recorder([{"base64_attachments": ["A"], "recipients": ["R=="]}]))
path = _scenario_file(tmp_path, "expect:\n - {kind: image}\n")
code = cli.main([str(path), "--group-id", "W==", "--group-id-send", "R==", "--settle", "0"])
assert code == 0
assert "ok demo" in capsys.readouterr().out
def test_main_exits_non_zero_on_a_mismatch(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
"""The e2e script is a gate only because this returns 1."""
_patch_client(monkeypatch, Recorder([]))
path = _scenario_file(tmp_path, "expect:\n - {kind: image}\n")
code = cli.main([str(path), "--group-id", "W==", "--group-id-send", "R==", "--settle", "0"])
assert code == 1
out = capsys.readouterr().out
assert "FAIL demo" in out
def test_module_runs_as_a_script(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""`python -m fake_signal.cli` must exit with the adjudication code.
runpy re-imports into a fresh namespace, so the patch has to land on the
shared httpx module rather than on fake_signal.cli.
"""
_patch_client(monkeypatch, Recorder([]))
path = _scenario_file(tmp_path, "expect:\n - {kind: image}\n")
monkeypatch.setattr(
sys,
"argv",
["cli", str(path), "--group-id", "W==", "--group-id-send", "R==", "--settle", "0"],
)
with pytest.raises(SystemExit) as exit_info:
runpy.run_module("fake_signal.cli", run_name="__main__", alter_sys=True)
assert exit_info.value.code == 1