signal-bot/tests/test_fake_server.py
Krzysztof kuhy Rudnicki e3c7bbfe23 !good bot: thank the asker with an emoji on their message, not a reply
A compliment gets a reaction drawn from a small warm set (❤️ 🥰 😊 👍 🎉 🙏
😸) put on the compliment itself, and nothing in the group -- the one
answer that adds no line. Same cooldown as every other command.

The transport learns reactions: send_reaction on the Protocol, POST
/v1/reactions/<number> on the REST adapter with the four fields
api.SendReactionRequest requires (204 back), a recorded list on the fake.
CommandContext.react() names the target the way a quote does, and falls
back to the emoji as text for an envelope with no timestamp, so a shape
this bot has never seen is visible rather than swallowed.

The fake container gains the endpoint, strict about the schema, and
records reactions in order with the sends; a scenario can now expect
{kind: reaction, quotes: true}. First two-word trigger: fold() keeps the
inner space and the registry matches whole text first, so "!good bot"
resolves and "!good" does not; one-word spellings cover a double space.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-04 21:48:03 +02:00

185 lines
7.8 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The fake Signal server's own behaviour."""
from __future__ import annotations
import base64
import pytest
from fastapi.testclient import TestClient
from fake_signal.server import create_app, default_state
from fake_signal.state import PIXEL_PNG, State
from signal_bot.wolnelektury import parse
@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"
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_a_reaction_is_captured_in_order_with_the_sends(client: TestClient, state: State) -> None:
reaction = {"reaction": "❤️", "recipient": "g", "target_author": "a", "timestamp": 17}
client.post("/v2/send", json={"message": "hi", "recipients": ["g"]})
response = client.post("/v1/reactions/+15550000000", json=reaction)
assert response.status_code == 204
assert state.sent[1] == {"number": "+15550000000", **reaction}
assert state.attachments == []
def test_a_reaction_missing_a_required_field_is_refused(client: TestClient, state: State) -> None:
"""The container's schema marks all four required; the fake must be as strict."""
response = client.post("/v1/reactions/+15550000000", json={"reaction": "❤️", "recipient": "g"})
assert response.status_code == 400
assert state.sent == []
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()
gecko = client.get("/_fixtures/gecko-api").json()
assert cat[0]["url"].endswith("/_fixtures/image.png")
assert dog["message"].endswith("/_fixtures/image.png")
assert gecko["results"][0]["photos"][0]["url"].endswith("/_fixtures/photos/square.png")
commons = client.get("/_fixtures/commons-api", params={"titles": "File:8-St.jpg"}).json()
page = commons["query"]["pages"][0]
# thumburl only, never url: the bot must ask for a bounded thumbnail.
# One committed portrait is 37 MB, which is not a Signal attachment.
assert page["imageinfo"][0]["thumburl"].endswith("/_fixtures/image.png")
assert "url" not in page["imageinfo"][0]
assert page["title"] == "File:8-St.jpg"
poem = client.get("/_fixtures/poem-text", params={"slug": "impas"})
# Wolne Lektury serves text/plain in a fixed shape, and poem_command
# refuses anything without the public-domain sentence -- so the fixture
# has to carry it or !wiersz answers nothing and the scenario would fail
# for a reason that looks like the bot's fault.
assert poem.headers["content-type"].startswith("text/plain")
parsed = parse(poem.text)
assert parsed is not None
# The slug is echoed back as the title, so a scenario proves the bot
# asked for the poem it drew rather than a hard-coded one.
assert parsed.title == "impas"
assert parsed.author == "Adam Testowy"
assert "linijka wiersza" in parsed.text
assert client.get("/_fixtures/image.png").content == PIXEL_PNG
# The square URL is deliberately absent: the bot must rewrite it.
assert client.get("/_fixtures/photos/large.png").content == PIXEL_PNG
assert client.get("/_fixtures/photos/square.png").status_code == 404
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=="]}]
def test_an_inbound_attachment_can_be_stored_and_fetched(client: TestClient) -> None:
"""Without this the fake could name an attachment but never hand it over."""
payload = b"\xff\xd8\xffphoto"
stored = client.post(
"/_control/attachment",
json={"id": "att-1", "base64": base64.b64encode(payload).decode("ascii")},
)
assert stored.status_code == 200
assert client.get("/_control/attachments").json() == ["att-1"]
assert client.get("/v1/attachments/att-1").content == payload
assert client.get("/v1/attachments").json() == ["att-1"]
def test_fetching_an_attachment_that_is_not_there_is_a_404(client: TestClient) -> None:
assert client.get("/v1/attachments/nope").status_code == 404
def test_deleting_an_attachment_takes_its_bytes_too(client: TestClient) -> None:
""" "The second copy is gone" has to be assertable, not assumed."""
client.post(
"/_control/attachment",
json={"id": "att-1", "base64": base64.b64encode(b"\xff\xd8\xffx").decode("ascii")},
)
assert client.delete("/v1/attachments/att-1").status_code == 204
assert client.get("/_control/attachments").json() == []
assert client.get("/v1/attachments/att-1").status_code == 404
def test_uploading_the_same_id_twice_does_not_duplicate_the_listing(
client: TestClient,
) -> None:
body = {"id": "att-1", "base64": base64.b64encode(b"\xff\xd8\xffx").decode("ascii")}
client.post("/_control/attachment", json=body)
client.post("/_control/attachment", json=body)
assert client.get("/v1/attachments").json() == ["att-1"]