signal-bot/tests/test_pack_custom.py
Krzysztof kuhy Rudnicki aefffb2fd9
Some checks are pending
CI / check (push) Waiting to run
feat: add a photo to the album from the chat, tagged, stripped and verified
Send a photo captioned "!add_photo alfa wakacje" in one of the album's own
groups and it lands in the pack tagged with both, retrievable through !alfa
and the new !losowe immediately -- no restart, and no tagger session on the PC.
A label matching nobody becomes a custom tag, and !losowe is the only door to
one, which is what keeps a live swap a *data* swap: it can never register a
trigger or widen a command's groups.

No typed label travels. Labels become pseudonym keys in a new registry
arg_resolver, at the dispatcher, before the line that logs the command name --
so no handler, journal entry, command_uses row or reply body ever holds a word
somebody typed. The reply is counts and pseudonyms: "dodano · p1: 4 · t1: 1".

Stripping is exiftool with a *positive* check on the output, never an exit
code. ffmpeg was tried first and fails silently on photos: given a JPEG with a
real APP1 Exif segment it returned a byte-identical file, GPS intact, exit 0.
The surviving-tag allowlist is per tag *name* rather than per group, because
measurement showed a group-level "must be empty" rule rejects every format
except JPEG -- a valid PNG always reports its IHDR, an MP4 some fifty QuickTime
tags that are the container itself. Codec configuration (CompressorName,
VendorID, the HEVC parameter set) is on the list by decision: CompressorName
lives in the avc1 sample description and exiftool cannot write it at all, so
the alternative was refusing every video and every iPhone HEIC. Location and
identity tags are still refused, and the e2e run re-reads the stored files to
prove a QuickTime geotag did not survive.

.webm and .svg stay on the format allowlist and are stored *unstripped*:
exiftool 13.55 can write neither, and its SVG reader does not even surface
<metadata>. That is a deliberate, documented hole, not an oversight.

Two things this had to defuse along the way:
- personal_data_sources now reads custom.json, so "!add_photo kot <photo>"
  would have outlawed the word "kot" and refused every future commit, fixable
  only by hand-editing an album the committer cannot see. Minting now refuses
  a word that is already a command, and the gate subtracts the repo's own
  alias vocabulary from custom labels only -- curated people.json names are
  never excused.
- signal_bot/external.py is now the single subprocess site in the repository,
  so ruff's S603 needs exactly one scoped per-file-ignore instead of one per
  module that shells out. A test asserts nothing else imports subprocess.

A failed add changes nothing: media and the three manifests are written, the
album is reloaded, and only a load that succeeds is published; a load that
fails rolls all four back and keeps serving the pack that was already working,
without raising -- Restart=always would turn a ConfigError into a loop.

977 tests, 100% branch coverage, no omits and no suppressions. scripts/e2e.sh
gains 8 scenarios driven against the real exiftool on media generated at run
time, and asserts the invariants a reply cannot: that a refused upload is not
stored, that a message with no attachment leaves custom.json byte-identical,
and that signal-cli's own copy of every ingested attachment is gone.

Closes TODO-add-photo.md.

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

123 lines
4.7 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""custom.json: labels the album learned from the chat, and what refuses one."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
import pytest
from signal_bot.groups import ConfigError
from signal_bot.pack_custom import CUSTOM_FILE, CustomTags, load, write
if TYPE_CHECKING:
from pathlib import Path
NO_TRIGGERS: frozenset[str] = frozenset()
def _write(directory: Path, document: object) -> Path:
directory.mkdir(parents=True, exist_ok=True)
(directory / CUSTOM_FILE).write_text(json.dumps(document), encoding="utf-8")
return directory
def test_an_album_with_no_custom_file_has_no_custom_tags(tmp_path: Path) -> None:
"""The normal state of an album nobody has run !add_photo on."""
tags = load(tmp_path, NO_TRIGGERS)
assert tags.keys == frozenset()
assert tags.resolve("anything") is None
def test_labels_resolve_to_their_key(tmp_path: Path) -> None:
tags = load(_write(tmp_path, {"t1": ["wakacje"], "t2": ["gory", "gorki"]}), NO_TRIGGERS)
assert tags.resolve("wakacje") == "t1"
assert tags.resolve("gorki") == "t2"
assert tags.keys == {"t1", "t2"}
def test_a_label_resolves_through_folding(tmp_path: Path) -> None:
"""The same folding a trigger gets, so a Cyrillic "o" still resolves."""
tags = load(_write(tmp_path, {"t1": ["Wakacje"]}), NO_TRIGGERS)
assert tags.resolve("WAKACJE") == "t1"
assert tags.resolve("wakacje") == "t1"
def test_the_next_key_is_one_past_the_highest_in_use() -> None:
"""Not the count: deleting t2 by hand must not make a mint reuse it.
Reusing it would silently inherit every photo the old t2 was tagged with.
"""
tags = CustomTags(by_key={"t1": ("a",), "t5": ("b",)}, by_label={"a": "t1", "b": "t5"})
assert tags.next_key() == "t6"
assert CustomTags().next_key() == "t1"
def test_a_key_that_is_not_a_pseudonym_fails_the_load(tmp_path: Path) -> None:
"""The key reaches the log and tags.json, so it may not look like a name."""
with pytest.raises(ConfigError, match="must be 't' followed by a number"):
load(_write(tmp_path, {"wakacje": ["x"]}), NO_TRIGGERS)
@pytest.mark.parametrize("document", [{"t1": []}, {"t1": "wakacje"}, {"t1": None}])
def test_an_entry_without_labels_fails_the_load(tmp_path: Path, document: object) -> None:
with pytest.raises(ConfigError, match="non-empty list of labels"):
load(_write(tmp_path, document), NO_TRIGGERS)
def test_a_label_that_folds_away_to_nothing_fails_the_load(tmp_path: Path) -> None:
with pytest.raises(ConfigError, match="folds away to nothing"):
load(_write(tmp_path, {"t1": ["!!!"]}), NO_TRIGGERS)
def test_a_label_that_shadows_a_person_fails_the_load(tmp_path: Path) -> None:
"""Otherwise the label quietly hides the command that person is reached by."""
with pytest.raises(ConfigError, match="already a person's trigger"):
load(_write(tmp_path, {"t1": ["alfa"]}), frozenset({"!alfa"}))
def test_two_keys_claiming_one_label_fails_the_load(tmp_path: Path) -> None:
"""!random would otherwise pick between them arbitrarily."""
with pytest.raises(ConfigError, match="is claimed by"):
load(_write(tmp_path, {"t1": ["wakacje"], "t2": ["wakacje"]}), NO_TRIGGERS)
def test_malformed_json_fails_the_load(tmp_path: Path) -> None:
(tmp_path / CUSTOM_FILE).write_text("{not json", encoding="utf-8")
with pytest.raises(ConfigError, match="not valid JSON"):
load(tmp_path, NO_TRIGGERS)
def test_a_document_that_is_not_an_object_fails_the_load(tmp_path: Path) -> None:
with pytest.raises(ConfigError, match="must be an object"):
load(_write(tmp_path, ["t1"]), NO_TRIGGERS)
def test_an_unreadable_file_fails_the_load(tmp_path: Path) -> None:
"""A directory where the manifest should be: read_text raises OSError."""
(tmp_path / CUSTOM_FILE).mkdir(parents=True)
with pytest.raises(ConfigError, match="cannot be read"):
load(tmp_path, NO_TRIGGERS)
def test_writing_then_loading_round_trips(tmp_path: Path) -> None:
tags = CustomTags().with_label("t1", "wakacje").with_label("t1", "wakacje2019")
write(tmp_path, tags)
again = load(tmp_path, NO_TRIGGERS)
assert again.by_key == {"t1": ("wakacje", "wakacje2019")}
assert again.resolve("wakacje2019") == "t1"
def test_the_written_file_is_not_world_readable(tmp_path: Path) -> None:
write(tmp_path, CustomTags().with_label("t1", "wakacje"))
assert (tmp_path / CUSTOM_FILE).stat().st_mode & 0o077 == 0
def test_with_label_does_not_mutate_the_original() -> None:
"""The pending mint must be discardable, which needs a value type."""
original = CustomTags()
extended = original.with_label("t1", "wakacje")
assert original.keys == frozenset()
assert extended.keys == {"t1"}