signal-bot/tests/test_popes_command.py
Krzysztof kuhy Rudnicki 48957a105d
Some checks are pending
CI / check (push) Waiting to run
feat: serve several photo albums at once, each scoped to its own groups
You asked for !add_photo in testbot without the real album being reachable
there. One album cannot do that: its people.json "groups" list *is* the
privacy guarantee, so making the commands exist in a second group necessarily
makes the real photos postable there. So the bot now loads several albums.

PHOTO_PACK_DIR takes a comma-separated list, the spelling GROUP_IDS and
TRUSTED_INVITERS already use. Each album carries its own group scope, its own
people, its own tags and its own custom labels; they share nothing but the
process they run in.

That makes trigger collisions between albums legal for the first time, and the
registry had to learn it. Two albums are two different sets of people and both
may reasonably call somebody "!alfa" -- no message can ever mean both, because
a command a group is not scoped to is not a command there at all. So a trigger
may be claimed more than once, and DuplicateTriggerError now fires only where
the group sets *overlap*. Overlapping albums are refused at startup rather than
resolved by registration order: a coin toss about which private album receives
a photo is the outcome this whole design exists to prevent.

Two consequences worth naming:

- registry.resolve() takes an optional group. Without one it still answers
  "does anything claim this word", which is what pack_add's mint check wants;
  with one it answers "what runs here", which is what the dispatcher wants.
  resolve_with_args no longer resolves-then-checks, because with two claimants
  the first one found may be the wrong group's.
- CommandContext moved to signal_bot/context.py to keep registry.py under the
  250-line cap. A filing change: that file is "which word runs what", this one
  is "what the thing that runs may do".

DOCS-add-photo.md is likewise a split, not new prose -- DOCS-photo-pack.md had
grown past the cap and the ingest path is its own subject now.

Verified live: the unit serves both albums, the real group resolves its 13
album commands and testbot its 7, and !losowe / !alfa / !dodaj all fire in
testbot through the live dispatcher. 997 tests, 100% branch coverage, 28 e2e
scenarios.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JqqE22jp94B1ypwxppdr1o
2026-08-31 11:58:50 +02:00

154 lines
5.5 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The !papież command: a random pope, captioned and linked."""
from __future__ import annotations
import base64
from pathlib import Path
from typing import TYPE_CHECKING
import httpx
import pytest
from signal_bot.context import CommandContext
from signal_bot.decorators import DISPLAY_MARGIN_SECONDS, cooldown
from signal_bot.http_client import ImageFetcher
from signal_bot.models import parse_envelope
from signal_bot.popes_command import (
COMMAND_NAME,
article_url,
caption_for,
random_pope,
register_pope_command,
)
from signal_bot.portraits import PortraitCache
from signal_bot.registry import CommandRefusedError, CommandRegistry
from signal_bot.versioning import POPES
from tests.conftest import WATCHED_GROUP, envelope
if TYPE_CHECKING:
from signal_bot.config import Config
from signal_bot.store import Store
from signal_bot.transport_fake import FakeTransport
IMAGE = b"portrait-bytes"
ALIASES = {COMMAND_NAME: ["!papież", "!papiez", "!pope"]}
def _cache(tmp_path: Path) -> PortraitCache:
def handler(request: httpx.Request) -> httpx.Response:
if "commons" in str(request.url):
page = {"imageinfo": [{"thumburl": "https://cdn/portrait.jpg"}]}
return httpx.Response(200, json={"query": {"pages": [page]}})
return httpx.Response(200, content=IMAGE)
fetcher = ImageFetcher(httpx.AsyncClient(transport=httpx.MockTransport(handler)))
return PortraitCache(fetcher, "https://commons.example/w/api.php", tmp_path)
def _ctx(transport: FakeTransport, store: Store, config: Config, text: str) -> CommandContext:
message = parse_envelope(envelope(text=text))
assert message is not None
return CommandContext(
message=message,
group_id=WATCHED_GROUP,
transport=transport,
store=store,
config=config,
command_name=COMMAND_NAME,
now=100.0,
day="2026-08-30",
)
@pytest.mark.parametrize("trigger", ["!papież", "!papiez", "!pope"])
def test_every_alias_resolves(trigger: str) -> None:
registry = CommandRegistry()
register_pope_command(registry, _cache(Path("/nonexistent")), aliases=ALIASES)
command = registry.resolve(trigger)
assert command is not None
assert command.name == COMMAND_NAME
def test_the_real_alias_file_carries_the_command() -> None:
registry = CommandRegistry()
register_pope_command(registry, _cache(Path("/nonexistent")))
# The Polish spelling is the one kuhy asked for; folding makes the rest
# of the keyboard layouts work, but this one must be listed outright.
assert registry.resolve("!papież") is not None
async def test_it_posts_a_portrait_with_the_caption_attached(
tmp_path: Path, transport: FakeTransport, store: Store, config: Config
) -> None:
registry = CommandRegistry()
register_pope_command(registry, _cache(tmp_path), aliases=ALIASES)
command = registry.resolve("!papież")
assert command is not None
await command.handler(_ctx(transport, store, config, "!papież"))
sent = transport.sent[0]
assert sent.recipient == WATCHED_GROUP
assert sent.image_base64 is not None
assert base64.b64decode(sent.image_base64) == IMAGE
# One message, not two: the caption rides in the same payload.
assert len(transport.sent) == 1
assert "papież nr " in sent.caption
assert "https://pl.wikipedia.org/wiki/" in sent.caption
async def test_the_cooldown_decorator_applies(
tmp_path: Path, transport: FakeTransport, store: Store, config: Config
) -> None:
registry = CommandRegistry()
register_pope_command(
registry, _cache(tmp_path), decorate=cooldown(10, "WAIT {seconds}"), aliases=ALIASES
)
store.record_use(WATCHED_GROUP, "uuid-alice", COMMAND_NAME, 100.0, "2026-08-30")
command = registry.resolve("!pope")
assert command is not None
with pytest.raises(CommandRefusedError):
await command.handler(_ctx(transport, store, config, "!pope"))
assert transport.texts == [f"WAIT {10 + DISPLAY_MARGIN_SECONDS}"]
def test_the_caption_names_the_pope_in_both_languages() -> None:
pope = POPES[263]
assert pope.name == "Jan Paweł II"
assert caption_for(pope) == (
"Jan Paweł II — Ioannes Paulus Secundus\n"
"papież nr 264 z 267, pontyfikat 1978-2005\n"
"https://pl.wikipedia.org/wiki/Jan_Pawe%C5%82_II"
)
def test_the_latin_name_never_contradicts_the_polish_number() -> None:
"""Both names come from the same table row, so they cannot disagree.
la.wikipedia titles #154 "Stephanus X" while every other source calls
him the ninth, and "Stefan IX — Stephanus X" in one caption reads as a
bug. The Latin column of Poczet papieży says "Stephanus Nonus".
"""
assert POPES[153].name == "Stefan IX"
assert POPES[153].latin == "Stephanus Nonus"
assert POPES[266].latin == "Leo Decimus Quartus"
def test_the_url_uses_the_title_so_disambiguated_popes_still_resolve() -> None:
telesfor = POPES[7]
assert telesfor.name == "Telesfor"
# Half the early popes live at "<name> (papież)"; name alone 404s.
assert article_url(telesfor) == "https://pl.wikipedia.org/wiki/Telesfor_%28papie%C5%BC%29"
def test_the_draw_actually_varies() -> None:
# 0.0.3 shipped a !gekon that posted one identical photo forever because
# nobody drew twice. Twenty draws from 267 popes repeating is a 1-in-267^19
# event; anything that pins the choice fails here immediately.
drawn = {random_pope().ordinal for _ in range(20)}
assert len(drawn) > 1