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

209 lines
6.6 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The bbernhard adapter: sends, attachments, mode check and reconnect."""
from __future__ import annotations
from collections.abc import AsyncIterator, Callable
from typing import TYPE_CHECKING
import httpx
import pytest
from websockets.exceptions import ConnectionClosedError
from signal_bot.transport_rest import RestTransport, TransportError
if TYPE_CHECKING:
from types import TracebackType
from signal_bot.config import Config
# The callable httpx.MockTransport expects -- not a bot command handler.
MockHandler = Callable[[httpx.Request], httpx.Response]
class FakeSocket:
"""Yields a canned list of frames, optionally failing partway through."""
def __init__(self, frames: list[str], *, fail_after: bool = False) -> None:
self._frames = frames
self._fail_after = fail_after
async def __aiter__(self) -> AsyncIterator[str]:
for frame in self._frames:
yield frame
if self._fail_after:
raise ConnectionClosedError(None, None)
class FakeConnect:
"""Stands in for websockets.connect, handing out sockets in order."""
def __init__(self, sockets: list[FakeSocket]) -> None:
self._sockets = sockets
self.urls: list[str] = []
def __call__(self, url: str) -> FakeConnect:
self.urls.append(url)
return self
async def __aenter__(self) -> FakeSocket:
if not self._sockets:
msg = "no more sockets"
raise OSError(msg)
return self._sockets.pop(0)
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
return None
def _transport(config: Config, handler: MockHandler, **kwargs: object) -> RestTransport:
client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
return RestTransport(config, client, **kwargs)
async def test_send_text_posts_expected_payload(config: Config) -> None:
seen: list[dict] = []
def handler(request: httpx.Request) -> httpx.Response:
seen.append(__import__("json").loads(request.content))
return httpx.Response(201)
await _transport(config, handler).send_text("hi", "group==")
assert seen[0] == {
"message": "hi",
"number": config.phone_number,
"recipients": ["group=="],
}
async def test_send_image_posts_base64_attachment(config: Config) -> None:
seen: list[dict] = []
def handler(request: httpx.Request) -> httpx.Response:
seen.append(__import__("json").loads(request.content))
return httpx.Response(200)
await _transport(config, handler).send_image("BASE64", "group==")
assert seen[0]["base64_attachments"] == ["BASE64"]
async def test_send_raises_on_rejection(config: Config) -> None:
transport = _transport(config, lambda r: httpx.Response(400, text="nope"))
with pytest.raises(TransportError, match="400"):
await transport.send_text("hi", "g")
async def test_verify_mode_accepts_json_rpc(config: Config) -> None:
transport = _transport(config, lambda r: httpx.Response(200, json={"mode": "json-rpc"}))
assert await transport.verify_mode() == "json-rpc"
async def test_verify_mode_accepts_json_rpc_native(config: Config) -> None:
transport = _transport(config, lambda r: httpx.Response(200, json={"mode": "json-rpc-native"}))
assert await transport.verify_mode() == "json-rpc-native"
@pytest.mark.parametrize("body", [{"mode": "normal"}, {"mode": "native"}, {}, ["nope"]])
async def test_verify_mode_rejects_non_websocket_modes(config: Config, body: object) -> None:
"""In normal/native mode /v1/receive silently degrades to a polling GET."""
transport = _transport(config, lambda r: httpx.Response(200, json=body))
with pytest.raises(TransportError, match="json-rpc-native"):
await transport.verify_mode()
async def test_list_attachments(config: Config) -> None:
transport = _transport(config, lambda r: httpx.Response(200, json=["a", "b"]))
assert await transport.list_attachments() == ["a", "b"]
async def test_list_attachments_tolerates_non_list(config: Config) -> None:
transport = _transport(config, lambda r: httpx.Response(200, json={"oops": 1}))
assert await transport.list_attachments() == []
async def test_delete_attachment(config: Config) -> None:
seen: list[str] = []
def handler(request: httpx.Request) -> httpx.Response:
seen.append(str(request.url))
return httpx.Response(204)
await _transport(config, handler).delete_attachment("abc")
assert seen[0].endswith("/v1/attachments/abc")
async def test_delete_attachment_raises_on_failure(config: Config) -> None:
transport = _transport(config, lambda r: httpx.Response(500))
with pytest.raises(TransportError, match="500"):
await transport.delete_attachment("abc")
async def test_receive_yields_frames(config: Config) -> None:
connector = FakeConnect([FakeSocket(["a", "b"])])
transport = _transport(
config,
lambda r: httpx.Response(200),
connector=connector,
sleeper=_no_sleep,
max_reconnects=0,
)
assert [f async for f in transport.receive()] == ["a", "b"]
async def test_receive_decodes_binary_frames(config: Config) -> None:
connector = FakeConnect([FakeSocket([b"bytes-frame"])])
transport = _transport(
config,
lambda r: httpx.Response(200),
connector=connector,
sleeper=_no_sleep,
max_reconnects=0,
)
assert [f async for f in transport.receive()] == ["bytes-frame"]
async def test_receive_reconnects_after_a_drop(config: Config) -> None:
"""A container restart used to kill the bot silently."""
slept: list[float] = []
async def sleeper(seconds: float) -> None:
slept.append(seconds)
connector = FakeConnect([FakeSocket(["a"], fail_after=True), FakeSocket(["b"])])
transport = _transport(
config,
lambda r: httpx.Response(200),
connector=connector,
sleeper=sleeper,
max_reconnects=1,
)
assert [f async for f in transport.receive()] == ["a", "b"]
assert slept == [1.0]
async def test_receive_backs_off_exponentially(config: Config) -> None:
slept: list[float] = []
async def sleeper(seconds: float) -> None:
slept.append(seconds)
connector = FakeConnect([])
transport = _transport(
config,
lambda r: httpx.Response(200),
connector=connector,
sleeper=sleeper,
max_reconnects=3,
)
assert [f async for f in transport.receive()] == []
assert slept == [1.0, 2.0, 4.0]
async def _no_sleep(seconds: float) -> None:
return None