signal-bot/tests/test_main.py
Krzysztof kuhy Rudnicki b48c945d89 feat: make the bot actually reply on Signal, and gate every way it went silent
First live reply, as its own registered account. `!cat` and `!dog` from the
phone return images -- verified in the production shape (the bot *invited to
an already-existing group*) and under a systemd user unit.

Four failures, each of which left the bot looking perfectly healthy:

- Invited is not joined. Signal only adds an account outright if the adder
  holds its profile key; with no profile the add becomes a pending invite,
  and signal-cli cannot accept one addressed to a phone number ("Cannot find
  service ID for self"). Group listed, websocket up, /healthz OK, zero
  messages. register_bot.sh now sets the profile *before* the add, and
  startup refuses on `member: false`.
- MODE=json-rpc-native is a GraalVM build with no AWT: text sends work,
  every attachment 400s with "Can't load library: awt". Both mode guards now
  demand exactly json-rpc, and start_container replaces a wrong-mode
  container instead of reusing it.
- The API spells one group two ways -- /v1/groups returns `group.<base64>`,
  envelopes carry what that decodes to -- so the scoping gate rejected the
  bot's own group. e2e.sh now models both spellings; reverting the fix fails
  4 scenarios, which is why the offline suite missed it before.
- BIND_PORT in .env was dead: __main__ read os.getenv before anything loaded
  a .env. The bind address comes from Config now.

A taken port used to be uvicorn logging the collision and exiting 0, which
every supervisor reads as success. portcheck.py refuses to start, exits
non-zero, and names the holder by reading /proc directly -- no subprocess, no
PATH assumptions, testable against a fake proc tree. Default port is 8137:
not 8000, and below the ephemeral range so the kernel cannot take it.

The bot now runs as signal-bot.service (Restart=always, linger checked rather
than assumed, StartLimitBurst so a config error fails visibly instead of
looping). Verified by SIGKILL and by re-running a command under the unit.

100% branch coverage, 230 tests, all gates green.

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

93 lines
3.1 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The console entrypoint.
`python main.py` used to do literally nothing: there was no __main__ block
and no uvicorn.run() call anywhere in the project.
"""
from __future__ import annotations
import runpy
import pytest
import uvicorn
import signal_bot.__main__ as entrypoint
from signal_bot.portcheck import PortInUseError
BASE_ENV = {
"PHONE_NUMBER": "+15550000000",
"GROUP_ID": "watched==",
"GROUP_ID_SEND": "reply==",
}
@pytest.fixture(autouse=True)
def _isolated_env(monkeypatch: pytest.MonkeyPatch) -> None:
"""Keep the developer's own .env out of the entrypoint's decisions.
load_dotenv() does not overwrite variables that are already set, but it
happily *adds* ones that are not -- so a real .env carrying BIND_PORT
would silently decide the outcome of the default-port test.
"""
monkeypatch.setattr("signal_bot.config.load_dotenv", lambda *a, **k: None)
for key, value in BASE_ENV.items():
monkeypatch.setenv(key, value)
for key in ("BIND_HOST", "BIND_PORT"):
monkeypatch.delenv(key, raising=False)
@pytest.fixture
def captured(monkeypatch: pytest.MonkeyPatch) -> dict[str, object]:
seen: dict[str, object] = {}
def fake_run(target: str, **kwargs: object) -> None:
seen["target"] = target
seen.update(kwargs)
monkeypatch.setattr(entrypoint.uvicorn, "run", fake_run)
monkeypatch.setattr(entrypoint, "assert_port_free", lambda host, port: None)
return seen
def test_runs_the_asgi_app_on_loopback_by_default(captured: dict[str, object]) -> None:
entrypoint.main()
assert captured["target"] == "signal_bot.app:app"
assert captured["host"] == "127.0.0.1"
assert captured["port"] == 8137
def test_bind_overrides_are_honoured(
captured: dict[str, object], monkeypatch: pytest.MonkeyPatch
) -> None:
# TEST-NET-1: proves the override without a bind-all literal.
monkeypatch.setenv("BIND_HOST", "192.0.2.10")
monkeypatch.setenv("BIND_PORT", "9001")
entrypoint.main()
assert captured["host"] == "192.0.2.10"
assert captured["port"] == 9001
def test_a_taken_port_exits_non_zero_instead_of_starting(
captured: dict[str, object], monkeypatch: pytest.MonkeyPatch
) -> None:
"""uvicorn would log the collision and exit 0; the bot must not."""
def refuse(host: str, port: int) -> None:
msg = "cannot bind 127.0.0.1:8137 -- held by pid 1: /sbin/init"
raise PortInUseError(msg)
monkeypatch.setattr(entrypoint, "assert_port_free", refuse)
with pytest.raises(SystemExit, match="held by pid 1"):
entrypoint.main()
assert "target" not in captured
def test_module_runs_as_a_script(monkeypatch: pytest.MonkeyPatch) -> None:
"""`python -m signal_bot` must actually start the server."""
seen: dict[str, object] = {}
monkeypatch.setattr(uvicorn, "run", lambda target, **kw: seen.update(target=target))
monkeypatch.setattr("signal_bot.portcheck.assert_port_free", lambda host, port: None)
runpy.run_module("signal_bot", run_name="__main__", alter_sys=True)
assert seen["target"] == "signal_bot.app:app"