From 95d3b87610abff41a0f89a6e507017d5ef3719a9 Mon Sep 17 00:00:00 2001 From: Ziad Arafat Date: Tue, 10 Nov 2026 09:42:47 -0700 Subject: [PATCH] Test the watch cog over real HTTP; test-container installs like Red; TDD rules - tests/test_watch_cog.py + watch_helpers.py: the watch cog against a fake media-preload on a real socket (spec-shaped JSON, bearer token), so the generated client, httpx, httpcore and anyio all run. 21 tests; checked against six mutations of watch.py, each caught. - scripts/test-container.sh installs cog requirements the way Red's Downloader does (pip -t lib, image's PIP_CONSTRAINT, lib appended after the venv via DOGE_COGS_LIB). On the pre-constraint image 20 watch tests fail with the 2026-11-09 production error; on the current image all pass. - test_alignment_isolation: discover every core module instead of a hand list that had missed guess, render, baseline, sampling and others. - TESTING.md (the loop, good tests, layers) and CLAUDE.md for agents. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 7 + README.md | 7 +- TESTING.md | 65 +++++ scripts/test-container.sh | 24 +- tests/conftest.py | 12 +- tests/test_alignment_isolation.py | 26 +- tests/test_watch_cog.py | 385 ++++++++++++++++++++++++++++++ tests/watch_helpers.py | 251 +++++++++++++++++++ 8 files changed, 758 insertions(+), 19 deletions(-) create mode 100644 CLAUDE.md create mode 100644 TESTING.md create mode 100644 tests/test_watch_cog.py create mode 100644 tests/watch_helpers.py diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..2839d77 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,7 @@ +# doge_cogs: notes for AI agents + +- Work test first. Read `TESTING.md` before changing code or tests, and use the superpowers + `test-driven-development` skill: failing test, watch it fail, minimal code, whole suite green. +- Existing code without tests: add tests, then run a mutation check (break the code, see a test fail, undo). +- `mise run check` before pushing; it includes the run inside dogebot's Red image on yveltal. +- Never edit cogs inside the running bot. Push here; dogebot's dogesetup installs the new version. diff --git a/README.md b/README.md index 3a824fe..776efd0 100644 --- a/README.md +++ b/README.md @@ -154,11 +154,14 @@ The cog's `info.json` installs it from this repo with pip. To regenerate it afte ```sh mise run generate-client # fetches the live spec into clients/media-preload.openapi.json and regenerates -mise run check # ruff, ty and pytest for the watch cog +mise run check # ruff, ty and pytest, here and inside the bot's image ``` ## Development +Everything here is built test first: see [TESTING.md](TESTING.md) for the loop, what makes a good test, and +the test layers (core, cog glue, real HTTP, the bot's image, and the live self-test). + mise installs uv, and uv installs Python 3.11 (what Red 3.5 needs) and the dependencies, including the generated client in editable mode. ruff (the lptn settings), ty and pytest cover both cogs. Each cog folder is self-contained, so Red's Downloader installs it without installing this repo as a package. @@ -170,7 +173,7 @@ mise run fmt && mise run check `mise run check` includes `mise run test-container`, which copies this checkout to yveltal and runs the tests inside dogebot's Red image (`localhost/dogebot-red:latest`), with the bot's Python, ImageMagick 6, fonts and -the exact requirements from each `info.json`. The dev machine has ImageMagick 7, and the two differ (an +the exact requirements from each `info.json`, installed the way Red's Downloader installs them. The dev machine has ImageMagick 7, and the two differ (an operator name broke pictures once), so run it before pushing anything that draws. Set `DOGEBOT_HOST` or `DOGEBOT_RED_IMAGE` to test elsewhere; extra arguments go to pytest. Keep `wand` in `pyproject.toml` equal to `doge_alignment/info.json`. ImageMagick itself is pinned in dogebot's `containers/red/Containerfile`. diff --git a/TESTING.md b/TESTING.md new file mode 100644 index 0000000..4dd876e --- /dev/null +++ b/TESTING.md @@ -0,0 +1,65 @@ +# Testing doge_cogs + +Every cog here is built test first. This page is the rulebook for people and for AI agents (`CLAUDE.md` points +here). It follows the superpowers `test-driven-development` skill and its `writing-good-tests.md`. + +## The loop + +1. **Red.** Write one test for one behaviour. Run it and **watch it fail**, for the reason you expect (the + feature is missing, not a typo or an import error). +2. **Green.** Write the least code that makes it pass. Run the whole suite (`mise run test`), not just the file. +3. **Refactor.** Clean up with the suite green. Don't add behaviour while refactoring. + +No production code without a failing test first. Bug fixes start with a test that reproduces the bug. + +When you add tests to code that already exists (it happens: `watch` got its cog tests after it shipped), they pass +straight away, which proves nothing. Do a **mutation check** instead: break the code on purpose (drop a branch, +change a constant, skip a side effect), confirm a test fails, then undo it. On 2026-11-10 the watch tests were +checked against six such mutations; each one failed at least one test. + +## What a good test looks like + +- **Name the break it catches.** Before writing the body, say which production change would make it fail. If you + can't, test something observable instead. +- **Literal expectations.** Write the expected value by hand (tables of `input -> want` are the preferred + shape). Never compute it with the code under test. +- **Behaviour, not text.** Don't grep source files or assert a constant's value; run the code and check what it + does. `test_alignment_isolation.py` imports the modules in a fresh interpreter rather than reading them. +- **Fakes only at the edge.** Fake what's external or slow (Discord, the media-preload API, Ollama) at the lowest + level you can, and keep everything above it real. Never assert on the fake itself. +- **Fakes mirror reality.** A fake API response has every field the real one has, in the real shape + (camelCase JSON for media-preload, straight from `clients/media-preload.openapi.json`). +- **Test utilities live in `tests/`**, never as methods on production classes. + +## Layers + +| Layer | Where | What it proves | +|---|---|---| +| Core (pure functions) | `tests/test_alignment_*.py` for `doge_alignment/core`, `tests/test_watch_spec.py` | the logic, with no Discord or Red at all | +| Cog glue | `tests/test_alignment_cog.py`, `tests/test_watch_cog.py` | commands and Config against Red's test Config backend (`config` fixture from Red's pytest plugin) and fakes at the edge | +| Real HTTP | `tests/watch_helpers.py` | the watch cog's calls go over a real socket to a fake media-preload, through the generated client, httpx, httpcore and anyio | +| The bot's environment | `mise run test-container` | the same tests inside dogebot's Red image, with cog requirements installed **the way Red installs them** | +| Live | dogebot's `selftest` cog | the real bot, after every cog update: commands in `#bot-testing`, music at volume 0 in an empty voice channel; failures turn the Kuma monitor "dogebot self-test" red | + +### Why test-container installs requirements like Red + +Red's Downloader runs `pip install -U -t ` and appends `lib` to `sys.path` *after* its own +venv. A package Red already has (like `typing_extensions`) always comes from the venv, whatever pip put in lib. +On 2026-11-09 pip put anyio 4.16 in lib, which needs typing_extensions 4.16; Red has 4.13.2, so `d!watch` broke. + +`scripts/test-container.sh` copies that exactly: requirements go to `/tmp/lib` with `pip -t` (under the image's +`PIP_CONSTRAINT`, which dogebot now sets to Red's own versions), and `tests/conftest.py` appends +`DOGE_COGS_LIB` to `sys.path`. Run against the old image +(`DOGEBOT_RED_IMAGE=localhost/dogebot-red:pre-constraint-2026-11-09`), 20 watch tests fail with the production +error; against the current image they pass. + +## Before you push + +```sh +mise run fmt +mise run check # ruff, ty, pytest here, and pytest inside the bot's image +``` + +After the bot picks up the new version (dogesetup updates cogs daily, or on restart), the self-test runs on its +own. `d!selftest run` runs it on demand. Never fix a cog by editing it inside the bot's container: the next +update overwrites it, and until then the bot runs code that isn't in git (that happened on 2026-11-09). diff --git a/scripts/test-container.sh b/scripts/test-container.sh index c65a16b..d5eb3fe 100755 --- a/scripts/test-container.sh +++ b/scripts/test-container.sh @@ -12,17 +12,19 @@ cd "$(dirname "$0")/.." host=${DOGEBOT_HOST:-yveltal_local} image=${DOGEBOT_RED_IMAGE:-localhost/dogebot-red:latest} -# The cogs' own requirements (what Red's Downloader installs), plus the -# locked test tools. The media-preload client comes from this checkout -# (editable, in the dev group) rather than from GitHub, so it's the code -# under test. +# The cogs' requirements are installed the way Red's Downloader installs them: +# `pip install -U -t ` (honouring the image's PIP_CONSTRAINT), with lib +# appended to sys.path after Red's venv (DOGE_COGS_LIB, see tests/conftest.py). +# The media-preload client comes from this checkout instead of GitHub, so it's +# the code under test. Only the test runner goes into the venv, constrained to +# Red's versions so it can't upgrade anything Red ships. cog_reqs=$(python3 -c 'import json, sys for f in sys.argv[1:]: for req in json.load(open(f))["requirements"]: if not req.startswith("media-preload-client"): print(req)' */info.json) test_reqs=$(uv export --frozen --only-group dev --no-hashes --no-emit-project \ - | grep -vE '^(ruff|ty)==|^#|^ *#') + | grep -E '^(pytest|pytest-asyncio)==') dir=$(ssh "$host" mktemp -d) trap 'ssh "$host" rm -rf "$dir"' EXIT @@ -34,10 +36,14 @@ printf '%s\n' "$test_reqs" | ssh "$host" "cat > $dir/.test-requirements.txt" # shellcheck disable=SC2029 # $dir and $image expand here on purpose ssh "$host" "podman run --rm --entrypoint sh -v $dir:/src:Z -w /src \ - -e PYTHONDONTWRITEBYTECODE=1 $image -c ' + -e PYTHONDONTWRITEBYTECODE=1 -e DOGE_COGS_LIB=/tmp/lib $image -c ' set -e - uv pip install --quiet --python /app/.venv/bin/python \ - -r .cog-requirements.txt -r .test-requirements.txt - python -c \"from wand.version import MAGICK_VERSION; print(MAGICK_VERSION)\" + constraint=\${PIP_CONSTRAINT:+--constraint \$PIP_CONSTRAINT} + uv pip install --quiet --python /app/.venv/bin/python \$constraint \\ + -r .test-requirements.txt + python -m pip install --quiet --disable-pip-version-check -U \\ + -t /tmp/lib -r .cog-requirements.txt ./clients/media-preload-client + echo PIP_CONSTRAINT=\${PIP_CONSTRAINT:-none} + ls /tmp/lib | grep -E \"^(anyio|typing_extensions|Wand|wand)-.*dist-info\" python -m pytest -q -p no:cacheprovider $* '" diff --git a/tests/conftest.py b/tests/conftest.py index 72afd58..1516f07 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,6 +1,16 @@ -"""Import the watch cog's modules the way Red does.""" +"""Import the cogs' modules the way Red does. +Red appends Downloader's lib folder (where it pip-installs cog requirements) +to sys.path, *after* its own venv. scripts/test-container.sh installs the +requirements the same way and passes the folder in ``DOGE_COGS_LIB``, so a +requirement that only works with lib's copy of a package Red already has +fails here too. +""" + +import os import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +if lib := os.environ.get("DOGE_COGS_LIB"): + sys.path.append(lib) diff --git a/tests/test_alignment_isolation.py b/tests/test_alignment_isolation.py index e39fde5..c87db74 100644 --- a/tests/test_alignment_isolation.py +++ b/tests/test_alignment_isolation.py @@ -6,19 +6,23 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[1] +# Every module of the core, found on disk so new ones are covered too, plus +# the package itself and the command line front end MODULES = ( "doge_alignment", "doge_alignment.cli", - "doge_alignment.core.alignments", - "doge_alignment.core.chart", - "doge_alignment.core.fetch", - "doge_alignment.core.layout", - "doge_alignment.core.storage", - "doge_alignment.core.view", + *sorted( + f"doge_alignment.core.{p.stem}" + for p in (ROOT / "doge_alignment/core").glob("*.py") + if p.stem != "__init__" + ), ) CHECK = f""" -import importlib, sys +import importlib, os, sys +# Cog requirements live in Red's lib folder in the bot image (see conftest) +if os.environ.get("DOGE_COGS_LIB"): + sys.path.append(os.environ["DOGE_COGS_LIB"]) for name in {MODULES!r}: importlib.import_module(name) banned = ("discord", "redbot") @@ -28,6 +32,14 @@ sys.exit(1 if leaked else 0) """ +def test_every_core_module_is_checked() -> None: + """The list really is discovered: modules added later are in it.""" + assert { + "doge_alignment.core.guess", + "doge_alignment.core.render", + } <= set(MODULES) + + def test_core_imports_neither_discord_nor_red() -> None: """Importing the core (and the CLI) never loads discord.py or Red.""" result = subprocess.run( # noqa: S603 diff --git a/tests/test_watch_cog.py b/tests/test_watch_cog.py new file mode 100644 index 0000000..eaa16bc --- /dev/null +++ b/tests/test_watch_cog.py @@ -0,0 +1,385 @@ +"""The watch cog against a fake media-preload on a real socket. + +Every test goes through the generated client, httpx, httpcore and anyio, so +a dependency mismatch in the bot's environment fails here (see +watch_helpers). +""" + +import asyncio +from collections.abc import AsyncIterator +from typing import Any, cast + +import pytest +from redbot.core import Config +from watch_helpers import ( + TOKEN, + FakeAuthor, + FakeContext, + FakePreload, + media_item, + preload_request, + serve, +) + +from watch.spec import EpisodeSpec +from watch.watch import PreloadError, Watch + + +class FakeBot: + """The bot calls the watch cog makes: tokens and permissions.""" + + def __init__(self, *, mod: bool = False) -> None: + """Answer is_mod with ``mod``; nobody is the owner.""" + self.mod = mod + + async def get_shared_api_tokens(self, _service: str) -> dict[str, str]: + """No tokens set with [p]set api (the env vars are used).""" + return {} + + async def is_mod(self, _member: object) -> bool: + """Whether the author is a moderator.""" + return self.mod + + async def is_owner(self, _user: object) -> bool: + """Nobody owns the test bot.""" + return False + + +@pytest.fixture +def fake() -> FakePreload: + """Return an empty fake media-preload.""" + return FakePreload() + + +@pytest.fixture +async def cog( + fake: FakePreload, config: Config, monkeypatch: pytest.MonkeyPatch +) -> AsyncIterator[Watch]: + """Return a Watch cog talking to ``fake`` over HTTP.""" + async with serve(fake) as url: + monkeypatch.setenv("PRELOAD_API_URL", url) + monkeypatch.setenv("PRELOAD_BOT_TOKEN", TOKEN) + cog = Watch.__new__(Watch) + cog.bot = cast("Any", FakeBot()) + config.register_user(jellyfin_user=None) + cog.config = config + cog._pollers = set() + yield cog + await asyncio.gather(*cog._pollers) + + +async def run_watch(cog: Watch, ctx: FakeContext, query: str) -> None: + """Run ``[p]watch `` and let its progress poller finish.""" + await Watch.watch.callback(cog, cast("Any", ctx), query=query) + await asyncio.gather(*cog._pollers) + + +# Library search ------------------------------------------------------- + + +async def test_search_lists_cacheable_items_first( + cog: Watch, fake: FakePreload +) -> None: + """Items that can't be cached go to the end, order otherwise kept.""" + fake.search_results = [ + media_item("a", "Alien", cacheable=False), + media_item("b", "Aliens"), + media_item("c", "Alien 3"), + ] + + items = await cog.search("alien", series_only=False) + + assert [i.id for i in items] == ["b", "c", "a"] + + +async def test_search_for_episodes_asks_for_series_only( + cog: Watch, fake: FakePreload +) -> None: + """With an episode spec only series are searched for.""" + fake.search_results = [ + media_item("m", "Dark Matter", kind="movie"), + media_item("s", "Dark Matter", kind="series", seasons=2), + ] + + items = await cog.search("Dark Matter", series_only=True) + + assert [i.id for i in items] == ["s"] + assert fake.calls_to("GET", "/v1/search") == [ + {"q": "Dark Matter", "type": "series", "limit": "10"} + ] + + +async def test_api_errors_carry_the_api_message(cog: Watch) -> None: + """A Problem response becomes a PreloadError with its message.""" + with pytest.raises(PreloadError, match="no such request"): + await cog.fetch(404) + + +async def test_wrong_token_is_reported( + cog: Watch, monkeypatch: pytest.MonkeyPatch +) -> None: + """A refused token shows the API's reason, not a crash.""" + monkeypatch.setenv("PRELOAD_BOT_TOKEN", "wrong") + with pytest.raises(PreloadError, match="missing or wrong token"): + await cog.search("alien", series_only=False) + + +# Creating requests ---------------------------------------------------- + + +@pytest.mark.parametrize( + ("kind", "spec", "jellyfin", "sent"), + [ + ( + "movie", + None, + None, + {"itemId": "x", "requestedBy": "discord:doge"}, + ), + # A movie ignores episode specs + ( + "movie", + EpisodeSpec(2, (8,)), + None, + {"itemId": "x", "requestedBy": "discord:doge"}, + ), + ( + "series", + EpisodeSpec(2, (8, 9, 10)), + None, + { + "itemId": "x", + "requestedBy": "discord:doge", + "season": 2, + "episodes": [8, 9, 10], + }, + ), + ( + "series", + EpisodeSpec(season=3), + None, + { + "itemId": "x", + "requestedBy": "discord:doge", + "season": 3, + }, + ), + ( + "series", + EpisodeSpec(next=4), + "doge_jf", + { + "itemId": "x", + "requestedBy": "discord:doge", + "next": 4, + "jellyfinUser": "doge_jf", + }, + ), + ], +) +async def test_create_sends_what_was_asked_for( # noqa: PLR0913 (table) + cog: Watch, + fake: FakePreload, + kind: str, + spec: EpisodeSpec | None, + jellyfin: str | None, + sent: dict[str, Any], +) -> None: + """The request body matches the item type and episode spec.""" + fake.search_results = [media_item("x", "X", kind=kind)] + (item,) = await cog.search("X", series_only=False) + + await cog.create(item, spec, cast("Any", FakeAuthor()), jellyfin) + + assert fake.calls_to("POST", "/v1/requests") == [sent] + + +# d!watch ---------------------------------------------------------------- + + +async def test_watch_starts_an_exact_match( + cog: Watch, fake: FakePreload +) -> None: + """One exact title match is requested without asking.""" + fake.search_results = [ + media_item("m1", "The Matrix", year=1999), + media_item("m2", "The Matrix Reloaded", year=2003), + ] + ctx = FakeContext() + + await run_watch(cog, ctx, "the matrix") + + assert fake.calls_to("POST", "/v1/requests") == [ + {"itemId": "m1", "requestedBy": "discord:doge"} + ] + assert ctx.texts == ["Preloading The Matrix"] + + +@pytest.mark.parametrize( + ("results", "reply"), + [ + ([], "I couldn't find **Nothing Here**."), + ( + [media_item("x", "Nothing Here", cacheable=False)], + "Nothing cacheable matches **Nothing Here**.", + ), + ], +) +async def test_watch_explains_when_there_is_nothing_to_preload( + cog: Watch, + fake: FakePreload, + results: list[dict[str, Any]], + reply: str, +) -> None: + """No match and no cacheable match get different answers.""" + fake.search_results = results + ctx = FakeContext() + + await run_watch(cog, ctx, "Nothing Here") + + assert ctx.texts == [reply] + assert fake.calls_to("POST", "/v1/requests") == [] + + +async def test_watch_next_needs_a_linked_jellyfin_user( + cog: Watch, fake: FakePreload +) -> None: + """Asking for "next" without `watch link` explains how to link.""" + fake.search_results = [ + media_item("s", "Dark Matter", kind="series", seasons=2) + ] + ctx = FakeContext() + + await run_watch(cog, ctx, "Dark Matter next") + + assert ctx.texts == [ + ( + "For **next**, tell me your Jellyfin name with " + "`d!watch link `." + ) + ] + assert fake.calls_to("POST", "/v1/requests") == [] + + +async def test_watch_next_uses_the_linked_jellyfin_user( + cog: Watch, fake: FakePreload +) -> None: + """After `watch link`, "next" requests with that Jellyfin name.""" + fake.search_results = [ + media_item("s", "Dark Matter", kind="series", seasons=2) + ] + ctx = FakeContext() + await Watch.watch_link.callback(cog, cast("Any", ctx), name=" doge_jf ") + + await run_watch(cog, ctx, "Dark Matter next 2") + + assert fake.calls_to("POST", "/v1/requests") == [ + { + "itemId": "s", + "requestedBy": "discord:doge", + "next": 2, + "jellyfinUser": "doge_jf", + } + ] + + +async def test_watch_reports_a_bad_episode_spec( + cog: Watch, fake: FakePreload +) -> None: + """A malformed spec is explained and nothing is searched.""" + ctx = FakeContext() + + await run_watch(cog, ctx, "Dark Matter s2e10-8") + + assert ctx.texts[0].startswith("I didn't get the episodes:") + assert fake.calls == [] + + +async def test_watch_reports_a_failed_search( + cog: Watch, monkeypatch: pytest.MonkeyPatch +) -> None: + """An API failure is shown to the user instead of raising.""" + monkeypatch.setenv("PRELOAD_BOT_TOKEN", "wrong") + ctx = FakeContext() + + await run_watch(cog, ctx, "The Matrix") + + assert ctx.texts == ["Search failed: missing or wrong token"] + + +# d!watch status / cancel ------------------------------------------------ + + +async def test_status_lists_the_latest_requests( + cog: Watch, fake: FakePreload +) -> None: + """Newest first, with id, title, status and requester.""" + fake.requests = { + 1: preload_request(1, "Alien", requested_by="discord:a"), + 2: preload_request( + 2, "Dune", status="fetching", requested_by="discord:b" + ), + } + ctx = FakeContext() + + await Watch.watch_status.callback(cog, cast("Any", ctx)) + + assert ctx.texts == [ + ( + "`#2` **Dune** · fetching · discord:b\n" + "`#1` **Alien** · done · discord:a" + ) + ] + + +async def test_status_with_no_requests(cog: Watch) -> None: + """An empty history says so.""" + ctx = FakeContext() + + await Watch.watch_status.callback(cog, cast("Any", ctx)) + + assert ctx.texts == ["No preloads yet."] + + +async def test_status_of_a_missing_request(cog: Watch) -> None: + """An unknown id shows the API's message.""" + ctx = FakeContext() + + await Watch.watch_status.callback(cog, cast("Any", ctx), request_id=9) + + assert ctx.texts == ["Couldn't get that: no such request"] + + +async def test_only_the_requester_can_cancel( + cog: Watch, fake: FakePreload +) -> None: + """Someone else's request is refused and never sent to the API.""" + fake.requests = { + 5: preload_request(5, "Dune", requested_by="discord:other") + } + ctx = FakeContext() + + await Watch.watch_cancel.callback(cog, cast("Any", ctx), request_id=5) + + assert ctx.texts == [ + "Only the requester or a moderator can cancel that." + ] + assert fake.calls_to("DELETE", "/v1/requests/5") == [] + + +async def test_requester_cancels_their_request( + cog: Watch, fake: FakePreload +) -> None: + """The requester's cancel reaches the API and shows the result.""" + fake.requests = { + 5: preload_request( + 5, "Dune", status="queued", requested_by="discord:doge" + ) + } + ctx = FakeContext() + + await Watch.watch_cancel.callback(cog, cast("Any", ctx), request_id=5) + + assert len(fake.calls_to("DELETE", "/v1/requests/5")) == 1 + assert ctx.sent[0].embed is not None + assert ctx.sent[0].embed.footer.text == "Request #5 · canceled" diff --git a/tests/watch_helpers.py b/tests/watch_helpers.py new file mode 100644 index 0000000..9e32eaa --- /dev/null +++ b/tests/watch_helpers.py @@ -0,0 +1,251 @@ +"""A fake media-preload API on a real socket, and a fake command context. + +The fake server speaks the media-preload OpenAPI spec (camelCase JSON, +bearer token), so the watch cog's tests run the real generated client, httpx, +httpcore and anyio. That path is what broke on 2026-11-09, when anyio and +typing_extensions disagreed inside the bot; test-container runs these tests +in the bot's image with requirements installed the way Red installs them. +""" + +from collections.abc import AsyncGenerator +from contextlib import asynccontextmanager +from dataclasses import dataclass, field +from typing import Any + +import discord +from aiohttp import web +from aiohttp.test_utils import TestServer + +TOKEN = "test-bot-token" # noqa: S105 (a fake server's token) + + +def media_item( # noqa: PLR0913 (mirrors the API's fields) + item_id: str, + name: str, + *, + kind: str = "movie", + cacheable: bool = True, + year: int | None = 2020, + seasons: int | None = None, +) -> dict[str, Any]: + """Return a MediaItem as the API sends it.""" + item: dict[str, Any] = { + "id": item_id, + "name": name, + "type": kind, + "cacheable": cacheable, + "library": "Movies" if kind == "movie" else "TV", + } + if year is not None: + item["year"] = year + if seasons is not None: + item["seasonCount"] = seasons + return item + + +def preload_request( + request_id: int, + title: str, + *, + status: str = "done", + requested_by: str = "discord:someone", + files: list[dict[str, Any]] | None = None, +) -> dict[str, Any]: + """Return a PreloadRequest as the API sends it.""" + return { + "id": request_id, + "itemId": f"item-{request_id}", + "title": title, + "requestedBy": requested_by, + "status": status, + "createdAt": "2026-11-10T12:00:00Z", + "files": files + if files is not None + else [ + { + "id": request_id * 10, + "path": f"/media/Videos/Movies/{title}.mkv", + "title": title, + "status": "cached", + "sizeBytes": 2_000_000_000, + "fetchedBytes": 2_000_000_000, + } + ], + } + + +@dataclass +class FakePreload: + """The parts of media-preload the bot uses, with what it was sent.""" + + search_results: list[dict[str, Any]] = field(default_factory=list) + requests: dict[int, dict[str, Any]] = field(default_factory=dict) + # Calls as (method, path, query, json body) + calls: list[tuple[str, str, dict[str, str], Any]] = field( + default_factory=list + ) + next_id: int = 100 + + def app(self) -> web.Application: + """Return the aiohttp app serving the API.""" + app = web.Application(middlewares=[self._auth]) + app.router.add_get("/v1/search", self._search) + app.router.add_get("/v1/requests", self._list) + app.router.add_post("/v1/requests", self._create) + app.router.add_get("/v1/requests/{id}", self._get) + app.router.add_delete("/v1/requests/{id}", self._cancel) + return app + + @web.middleware + async def _auth(self, request: web.Request, handler: Any) -> Any: # noqa: ANN401 + body = await request.json() if request.can_read_body else None + self.calls.append( + ( + request.method, + request.path, + dict(request.query), + body, + ) + ) + if request.headers.get("Authorization") != f"Bearer {TOKEN}": + return web.json_response( + {"error": "missing or wrong token"}, status=401 + ) + return await handler(request) + + async def _search(self, request: web.Request) -> web.Response: + kind = request.query.get("type") + found = [ + i + for i in self.search_results + if kind is None or i["type"] == kind + ] + return web.json_response(found) + + async def _list(self, request: web.Request) -> web.Response: + limit = int(request.query.get("limit", "20")) + latest = sorted(self.requests.values(), key=lambda r: -r["id"]) + return web.json_response(latest[:limit]) + + async def _create(self, request: web.Request) -> web.Response: + body = await request.json() + match = [ + i + for i in self.search_results + if i["id"] == body["itemId"] + ] + if not match: + return web.json_response( + {"error": "no such item"}, status=404 + ) + created = preload_request( + self.next_id, + match[0]["name"], + requested_by=body["requestedBy"], + ) + self.requests[self.next_id] = created + self.next_id += 1 + return web.json_response(created, status=201) + + def _find(self, request: web.Request) -> dict[str, Any] | None: + return self.requests.get(int(request.match_info["id"])) + + async def _get(self, request: web.Request) -> web.Response: + found = self._find(request) + if found is None: + return web.json_response( + {"error": "no such request"}, status=404 + ) + return web.json_response(found) + + async def _cancel(self, request: web.Request) -> web.Response: + found = self._find(request) + if found is None: + return web.json_response( + {"error": "no such request"}, status=404 + ) + found["status"] = "canceled" + return web.json_response(found) + + def calls_to(self, method: str, path: str) -> list[Any]: + """Return the bodies (queries for GETs) sent to an endpoint.""" + return [ + body if body is not None else query + for m, p, query, body in self.calls + if m == method and p == path + ] + + +@asynccontextmanager +async def serve(fake: FakePreload) -> AsyncGenerator[str]: + """Run ``fake`` on a free local port; yield its base URL.""" + server = TestServer(fake.app(), host="127.0.0.1") + await server.start_server() + try: + yield str(server.make_url("")).rstrip("/") + finally: + await server.close() + + +@dataclass +class FakeMessage: + """A sent message that records edits.""" + + content: str | None + embed: discord.Embed | None + edits: list[dict[str, Any]] = field(default_factory=list) + + async def edit(self, **changes: Any) -> None: # noqa: ANN401 + """Record an edit.""" + self.edits.append(changes) + + +@dataclass +class FakeAuthor: + """The person running the command.""" + + id: int = 1 + name: str = "doge" + + +class _Typing: + async def __aenter__(self) -> None: + return None + + async def __aexit__(self, *_exc: object) -> None: + return None + + +@dataclass +class FakeContext: + """Just enough of commands.Context for the watch commands.""" + + author: FakeAuthor = field(default_factory=FakeAuthor) + clean_prefix: str = "d!" + sent: list[FakeMessage] = field(default_factory=list) + + async def send( + self, + content: str | None = None, + *, + embed: discord.Embed | None = None, + **_kwargs: Any, # noqa: ANN401 (views, files) + ) -> FakeMessage: + """Record what the bot sends.""" + message = FakeMessage(content, embed) + self.sent.append(message) + return message + + def typing(self) -> _Typing: + """Pretend to type.""" + return _Typing() + + @property + def texts(self) -> list[str]: + """Message contents, or embed titles for embeds.""" + return [ + m.content + if m.content is not None + else str(m.embed.title if m.embed else "") + for m in self.sent + ]