mirror of
https://github.com/kuhyx/signal-bot.git
synced 2026-11-10 19:27:20 +01:00
Adds !papież / !papiez / !pope: a random pope as a photo, captioned with his Latin name, reign and pl.wikipedia link. popes.json already carried a Commons portrait filename for all 267 and nothing had ever consumed it. The Latin name comes from the Latin column of Poczet papieży, not from the la.wikipedia sitelink. The sitelink resolved for all 267 and was still wrong: la.wikipedia numbers several popes differently, so #154 came out as "Stefan IX — Stephanus X" in a single caption, which reads as an off-by-one. The table's own column says "Stephanus Nonus" and cannot disagree with the name beside it. LATIN_OVERRIDES ships empty; it is a tripwire, not a backlog. Portraits are cached on disk under CacheDirectory=signal-bot, named from the ordinal so no upstream string ever reaches a path, and bounded at 267 entries so nothing needs evicting. Verified that CacheDirectory wins against ProtectHome=read-only before relying on it. Also adds POST /_selftest and scripts/selftest.sh. Signal never delivers an account its own sends, so no command has ever been exercised end-to-end without asking a human to type it. This injects a real frame into the live dispatcher; it is loopback-only and refuses any group not in SELFTEST_GROUPS, which is empty by default. Verified against the real endpoints, not just the fake: 267/267 portraits resolve on Commons, regeneration is byte-identical on every previously shipped field, and !papież was driven 7 times through the live dispatcher in testbot, returning distinct popes. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015d48t4qsQLBJnDwDeo2Nom
153 lines
5.3 KiB
Python
153 lines
5.3 KiB
Python
# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
|
|
"""The on-disk papal portrait cache."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
from pathlib import Path
|
|
|
|
import httpx
|
|
import pytest
|
|
|
|
from signal_bot.http_client import ImageFetcher, ImageFetchError
|
|
from signal_bot.portraits import PortraitCache, default_cache_dir
|
|
from signal_bot.versioning import POPES, Pope
|
|
|
|
IMAGE = b"portrait-bytes"
|
|
PIUS = POPES[7]
|
|
|
|
|
|
def _names(directory: Path) -> list[str]:
|
|
"""List a directory. A helper so the async tests touch no pathlib."""
|
|
return sorted(entry.name for entry in directory.iterdir())
|
|
|
|
|
|
def _truncate(path: Path) -> None:
|
|
"""Leave behind what a crash between create and write would leave."""
|
|
path.write_bytes(b"")
|
|
|
|
|
|
def _mock_fetcher(seen: list[str] | None = None) -> ImageFetcher:
|
|
"""Build a fetcher whose Commons endpoint is a mock returning IMAGE."""
|
|
|
|
def handler(request: httpx.Request) -> httpx.Response:
|
|
if seen is not None:
|
|
seen.append(str(request.url))
|
|
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)
|
|
|
|
return ImageFetcher(httpx.AsyncClient(transport=httpx.MockTransport(handler)))
|
|
|
|
|
|
def _cache(tmp_path: Path, seen: list[str] | None = None) -> PortraitCache:
|
|
"""Build a cache writing into tmp_path."""
|
|
return PortraitCache(_mock_fetcher(seen), "https://commons.example/w/api.php", tmp_path)
|
|
|
|
|
|
async def test_a_miss_downloads_and_writes_the_file(tmp_path: Path) -> None:
|
|
seen: list[str] = []
|
|
cache = _cache(tmp_path, seen)
|
|
|
|
assert await cache.get_bytes(PIUS) == IMAGE
|
|
|
|
assert _names(tmp_path) == [f"{PIUS.ordinal:03d}.jpg"]
|
|
assert any("titles=File" in url for url in seen)
|
|
|
|
|
|
async def test_a_miss_leaves_no_temporary_file_behind(tmp_path: Path) -> None:
|
|
await _cache(tmp_path).get_bytes(PIUS)
|
|
assert [name for name in _names(tmp_path) if name.endswith(".tmp")] == []
|
|
|
|
|
|
async def test_a_hit_makes_no_http_request(tmp_path: Path) -> None:
|
|
seen: list[str] = []
|
|
cache = _cache(tmp_path, seen)
|
|
await cache.get_bytes(PIUS)
|
|
seen.clear()
|
|
|
|
assert await cache.get_bytes(PIUS) == IMAGE
|
|
assert seen == []
|
|
|
|
|
|
async def test_an_empty_cached_file_is_refetched(tmp_path: Path) -> None:
|
|
cache = _cache(tmp_path)
|
|
# Serving this would post a broken attachment for as long as it lived.
|
|
_truncate(cache.path_for(PIUS))
|
|
|
|
assert await cache.get_bytes(PIUS) == IMAGE
|
|
|
|
|
|
async def test_an_unwritable_cache_still_serves_the_photo(tmp_path: Path) -> None:
|
|
cache = PortraitCache(
|
|
_mock_fetcher(),
|
|
"https://commons.example/w/api.php",
|
|
tmp_path / "nested" / "file.txt" / "deeper",
|
|
)
|
|
(tmp_path / "nested").mkdir()
|
|
(tmp_path / "nested" / "file.txt").write_text("not a directory")
|
|
|
|
assert await cache.get_bytes(PIUS) == IMAGE
|
|
|
|
|
|
async def test_get_base64_encodes_what_get_bytes_returns(tmp_path: Path) -> None:
|
|
encoded = await _cache(tmp_path).get_base64(PIUS)
|
|
assert base64.b64decode(encoded) == IMAGE
|
|
|
|
|
|
def test_the_filename_comes_from_the_ordinal_not_from_commons(tmp_path: Path) -> None:
|
|
awkward = Pope(
|
|
ordinal=9,
|
|
name="Test",
|
|
title="Test",
|
|
reign="1-2",
|
|
portrait="../../etc/passwd, and a space (v2).PNG",
|
|
latin="Testus",
|
|
)
|
|
assert _cache(tmp_path).path_for(awkward) == tmp_path / "009.png"
|
|
|
|
|
|
def test_an_unknown_suffix_is_refused_rather_than_guessed(tmp_path: Path) -> None:
|
|
weird = Pope(ordinal=9, name="T", title="T", reign="1-2", portrait="x.svg", latin="T")
|
|
with pytest.raises(ImageFetchError, match="unusable suffix"):
|
|
_cache(tmp_path).path_for(weird)
|
|
|
|
|
|
def test_every_committed_portrait_has_a_suffix_the_cache_accepts(tmp_path: Path) -> None:
|
|
cache = _cache(tmp_path)
|
|
for pope in POPES:
|
|
assert cache.path_for(pope).parent == tmp_path
|
|
|
|
|
|
@pytest.fixture
|
|
def clean_env(monkeypatch: pytest.MonkeyPatch) -> pytest.MonkeyPatch:
|
|
"""A monkeypatch with every cache-directory variable removed."""
|
|
for key in ("PORTRAIT_CACHE_DIR", "CACHE_DIRECTORY", "XDG_CACHE_HOME"):
|
|
monkeypatch.delenv(key, raising=False)
|
|
return monkeypatch
|
|
|
|
|
|
def test_an_explicit_directory_wins(clean_env: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
|
clean_env.setenv("PORTRAIT_CACHE_DIR", str(tmp_path / "explicit"))
|
|
clean_env.setenv("CACHE_DIRECTORY", str(tmp_path / "systemd"))
|
|
assert default_cache_dir() == tmp_path / "explicit"
|
|
|
|
|
|
def test_systemd_cache_directory_is_used_when_set(
|
|
clean_env: pytest.MonkeyPatch, tmp_path: Path
|
|
) -> None:
|
|
"""Under the unit this is the only writable path: ProtectHome=read-only."""
|
|
clean_env.setenv("CACHE_DIRECTORY", str(tmp_path / "systemd"))
|
|
assert default_cache_dir() == tmp_path / "systemd" / "portraits"
|
|
|
|
|
|
def test_xdg_is_the_fallback_outside_systemd(clean_env: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
|
clean_env.setenv("XDG_CACHE_HOME", str(tmp_path / "xdg"))
|
|
assert default_cache_dir() == tmp_path / "xdg" / "signal-bot" / "portraits"
|
|
|
|
|
|
def test_home_is_the_last_resort(clean_env: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
|
clean_env.setattr(Path, "home", classmethod(lambda _: tmp_path / "home"))
|
|
assert default_cache_dir() == tmp_path / "home" / ".cache" / "signal-bot" / "portraits"
|