signal-bot/tests/test_fake_server.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

103 lines
3.9 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The fake Signal server's own behaviour."""
from __future__ import annotations
import pytest
from fastapi.testclient import TestClient
from fake_signal.server import create_app, default_state
from fake_signal.state import PIXEL_PNG, State
@pytest.fixture
def state() -> State:
return State(base_url="http://testserver")
@pytest.fixture
def client(state: State) -> TestClient:
return TestClient(create_app(state))
def test_about_reports_a_websocket_mode(client: TestClient) -> None:
body = client.get("/v1/about").json()
assert body["mode"] == "json-rpc-native"
def test_qrcodelink_returns_a_png(client: TestClient) -> None:
"""The real endpoint returns an image, which is why the runbook opens it."""
response = client.get("/v1/qrcodelink", params={"device_name": "bot"})
assert response.headers["content-type"] == "image/png"
assert response.headers["X-Device-Name"] == "bot"
assert response.content == PIXEL_PNG
def test_send_is_captured_and_mints_attachment_ids(client: TestClient, state: State) -> None:
client.post("/v2/send", json={"message": "hi", "recipients": ["g"]})
client.post("/v2/send", json={"base64_attachments": ["A"], "recipients": ["g"]})
assert len(state.sent) == 2
assert state.attachments == ["attach-2-0"]
def test_attachments_can_be_listed_and_deleted(client: TestClient) -> None:
client.post("/v2/send", json={"base64_attachments": ["A"], "recipients": ["g"]})
listed = client.get("/v1/attachments").json()
assert listed == ["attach-1-0"]
assert client.delete(f"/v1/attachments/{listed[0]}").status_code == 204
assert client.get("/v1/attachments").json() == []
def test_deleting_an_unknown_attachment_is_a_noop(client: TestClient) -> None:
assert client.delete("/v1/attachments/nope").status_code == 204
def test_reset_clears_captured_state(client: TestClient, state: State) -> None:
client.post("/v2/send", json={"base64_attachments": ["A"], "recipients": ["g"]})
client.post("/_control/reset")
assert state.sent == []
assert state.attachments == []
def test_websocket_subscribes_and_receives_injected_frames(client: TestClient) -> None:
with client.websocket_connect("/v1/receive/+15550000000") as socket:
assert socket.receive_json()["envelope"]["subscribed"] == "+15550000000"
assert client.get("/_control/ready").json() == {"sockets": 1}
assert client.post("/_control/inject", json={"raw": "FRAME"}).json() == {"delivered": 1}
assert socket.receive_text() == "FRAME"
def test_socket_is_forgotten_after_disconnect(client: TestClient) -> None:
with client.websocket_connect("/v1/receive/+1") as socket:
socket.receive_json()
assert client.get("/_control/ready").json() == {"sockets": 0}
def test_inject_with_no_listeners_delivers_nothing(client: TestClient) -> None:
assert client.post("/_control/inject", json={"raw": "x"}).json() == {"delivered": 0}
def test_fixture_apis_mirror_the_real_response_shapes(client: TestClient) -> None:
cat = client.get("/_fixtures/cat-api").json()
dog = client.get("/_fixtures/dog-api").json()
assert cat[0]["url"].endswith("/_fixtures/image.png")
assert dog["message"].endswith("/_fixtures/image.png")
assert client.get("/_fixtures/image.png").content == PIXEL_PNG
def test_create_app_makes_its_own_state_when_none_given() -> None:
with TestClient(create_app()) as client:
assert client.get("/v1/about").status_code == 200
def test_default_state_reads_the_port_from_the_environment(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("FAKE_PORT", "9123")
assert default_state().base_url.endswith(":9123")
def test_control_sent_exposes_captured_payloads(client: TestClient) -> None:
client.post("/v2/send", json={"message": "hi", "recipients": ["R=="]})
assert client.get("/_control/sent").json() == [{"message": "hi", "recipients": ["R=="]}]