import json from collections.abc import Iterator from typing import Any from urllib.parse import parse_qsl import httpx import pytest from fastapi.testclient import TestClient from mcp.server.mcpserver import MCPServer from anki_addons_catalog import __version__ from anki_addons_catalog.adapters.mcp.catalog import McpCatalog from anki_addons_catalog.application.catalog import CatalogService from anki_addons_catalog.bootstrap import create_app from anki_addons_catalog.config import Settings from anki_addons_catalog.domain.models import LlmTurn, SearchFilters, ToolCall, Usage from anki_addons_catalog.interface.web.app import search_url from anki_addons_catalog.interface.web.security import PASS_COOKIE, HumanCheck from tests.conftest import FakeLlm from tests.fixtures import FORK, FORK_OF_FORK, HEATMAP, KANJI, KANJI_COPY, OCCLUSION def settings(**overrides: Any) -> Settings: overrides.setdefault("usage_db", ":memory:") return Settings(_env_file=None, mcp_keepalive_seconds=0, public_url="https://example.org", # type: ignore[call-arg] **overrides) @pytest.fixture(autouse=True) def no_probe(monkeypatch: pytest.MonkeyPatch) -> None: """The app starts the Turnstile probe when Turnstile is on; it would reach the real Cloudflare.""" async def probe(self: HumanCheck) -> None: pass monkeypatch.setattr(HumanCheck, "probe", probe) def scripted_llm() -> FakeLlm: return FakeLlm([ LlmTurn(assistant_content=[], text="", stop_reason="tool_use", usage=Usage(input_tokens=10), tool_calls=[ToolCall("t1", "search_addons", {"query": "kanji"})]), LlmTurn(assistant_content=[], text=f"Try **[Kanji Helper](/addon/{KANJI})**.", tool_calls=[], stop_reason="end_turn", usage=Usage(output_tokens=10), model="claude-haiku-5-5"), ]) @pytest.fixture def make_client(server: MCPServer) -> Iterator[Any]: clients: list[TestClient] = [] def make(llm: FakeLlm | None = None, **overrides: Any) -> TestClient: catalog = McpCatalog(server, timeout_seconds=10) client = TestClient(create_app(settings(**overrides), catalog=catalog, llm=llm or scripted_llm())) client.__enter__() clients.append(client) return client yield make for client in clients: client.__exit__(None, None, None) def sse_events(text: str) -> list[tuple[str, Any]]: events = [] for chunk in text.strip().split("\n\n"): lines = dict(line.split(": ", 1) for line in chunk.splitlines()) events.append((lines["event"], json.loads(lines["data"]))) return events @pytest.mark.parametrize("path", ["/", "/search?q=kanji", f"/addon/{KANJI}", f"/addon/{OCCLUSION}?anki=25.02", "/top/rating", "/top/recently_updated", "/author/alice", "/stats", "/changes", "/about", "/tags", "/tag/dictionary", "/tag/obsolete"]) def test_pages_render(make_client: Any, path: str) -> None: response = make_client().get(path) assert response.status_code == 200, response.text assert "Anki Addons Catalog" in response.text assert f'v{__version__} BETA' in response.text assert 'class="dataset-date"' in response.text and ">1 Sep 2026" in response.text def test_index_lists_top_addons(make_client: Any) -> None: assert f'href="/addon/{OCCLUSION}"' in make_client().get("/").text def test_index_shows_addon_count(make_client: Any) -> None: assert "Ask in plain words across 6 addons." in make_client().get("/").text DEFAULT_DESCRIPTION = ("Find Anki addons by asking in plain words. AI-powered search over {} on AnkiWeb, with forks, " "ratings, compatibility, maintenance data and more.") @pytest.mark.parametrize("path", ["/", "/about"]) def test_link_preview_shows_addon_count(make_client: Any, path: str) -> None: html = make_client().get(path).text description = DEFAULT_DESCRIPTION.format("6 addons") assert f'' in html assert f'' in html def test_home_link_preview_title(make_client: Any) -> None: assert '' in make_client().get("/").text def test_link_preview_without_addon_count(make_client: Any, monkeypatch: pytest.MonkeyPatch) -> None: from anki_addons_catalog.domain.errors import ToolFailed async def failing(self: CatalogService) -> int: raise ToolFailed("get_statistics", "Unavailable") monkeypatch.setattr(CatalogService, "addon_count", failing) html = make_client().get("/about").text assert f'' in html def test_addon_link_preview_uses_addon_summary(make_client: Any) -> None: html = make_client().get(f"/addon/{OCCLUSION}").text assert 'Votes
300 (๐Ÿ‘ 298 ยท ๐Ÿ‘Ž 2)
" in make_client().get(f"/addon/{OCCLUSION}").text def _versions(html: str) -> str: return html.split('
', 1)[1].split("
", 1)[0] def test_fork_page_links_its_parent(make_client: Any) -> None: html = make_client().get(f"/addon/{FORK}").text assert f'

Fork of Review Heatmap

' in html assert '' in html assert '2 other versions of this addon exist. ' in html @pytest.mark.parametrize("addon_id", [HEATMAP, FORK, FORK_OF_FORK]) def test_every_version_compares_the_whole_family(make_client: Any, addon_id: int) -> None: versions = _versions(make_client().get(f"/addon/{addon_id}").text) others = {HEATMAP, FORK, FORK_OF_FORK} - {addon_id} assert all(f'href="/addon/{other}"' in versions for other in others) assert f'href="/addon/{addon_id}"' not in versions assert '' in versions and "this addon" in versions assert versions.index("Review Heatmap") < versions.index("Heatmap Revived") < versions.index("Heatmap Plus") def test_versions_mark_the_best_values(make_client: Any) -> None: versions = _versions(make_client().get(f"/addon/{HEATMAP}").text) assert "Works on Anki 25.09.2" in versions and "original" in versions assert versions.count("(AI-detected; may be wrong)") == 1 # Heatmap Plus; Heatmap Revived is a GitHub fork assert "obsolete" in versions # Review Heatmap: it gets no best mark, though it has the most votes assert '๐Ÿ‘ 8 ยท ๐Ÿ‘Ž 2' in versions and '๐Ÿ‘ 78 ยท ๐Ÿ‘Ž 2' not in versions def test_versions_use_the_anki_version_of_the_visitor(make_client: Any) -> None: versions = _versions(make_client().get(f"/addon/{FORK}", params={"anki": "2.1.66"}).text) assert "Works on Anki 2.1.66" in versions assert 'unsupported' in versions # Heatmap Revived needs 25.02 @pytest.mark.parametrize(("params", "suffix"), [({}, ""), ({"anki": "25.02"}, "?anki=25.02")]) def test_alternatives_link_keeps_the_anki_version(make_client: Any, params: dict[str, str], suffix: str) -> None: html = make_client().get(f"/addon/{HEATMAP}", params=params).text assert f'href="/addon/{HEATMAP}/alternatives{suffix}"' in html def test_alternatives_page_asks_about_the_addon(make_client: Any) -> None: html = make_client().get(f"/addon/{HEATMAP}/alternatives").text assert "Alternatives to Review Heatmap โ€“ Anki Addons Catalog" in html assert f'data-query="Alternatives to Review Heatmap (addon {HEATMAP})"' in html and 'data-filters=""' in html assert '' in html and '>Ask the AI for alternatives' in html assert f'' in html assert "Similar addons" in html and f'' in html def test_alternatives_page_passes_the_anki_version_to_the_ai(make_client: Any) -> None: html = make_client().get(f"/addon/{HEATMAP}/alternatives", params={"anki": "25.02"}).text assert 'data-filters="anki=25.02"' in html and "for Anki 25.02" in html def test_alternatives_of_missing_addon_is_404(make_client: Any) -> None: assert make_client().get("/addon/42/alternatives").status_code == 404 def test_addon_page_shows_github_fork_count(make_client: Any) -> None: assert "forks 1" in make_client().get(f"/addon/{KANJI}").text @pytest.mark.parametrize(("addon_id", "languages"), [(KANJI, "Python, JavaScript"), (FORK_OF_FORK, "Python")]) def test_addon_page_shows_package_languages(make_client: Any, addon_id: int, languages: str) -> None: html = make_client().get(f"/addon/{addon_id}").text assert f"
Languages
{languages}
" in html def test_addon_page_shows_github_languages(make_client: Any) -> None: assert "
Languages
Python, CSS
" in make_client().get(f"/addon/{FORK}").text @pytest.mark.parametrize(("addon_id", "license_text"), [ (KANJI, "MIT (from the license file in the package)"), (OCCLUSION, "GPL-3.0 (from the README)"), (HEATMAP, "Not found (this does not mean that the addon has no license)"), ]) def test_addon_page_shows_license_with_source(make_client: Any, addon_id: int, license_text: str) -> None: assert f"
License
{license_text}
" in make_client().get(f"/addon/{addon_id}").text def test_addon_page_explains_unrecognized_github_license(make_client: Any) -> None: html = make_client().get(f"/addon/{OCCLUSION}").text assert "
A license file that GitHub does not recognize
" in html assert "NOASSERTION" not in html @pytest.mark.parametrize(("addon_id", "scan"), [(KANJI, "No ClamAV match"), (FORK_OF_FORK, "ClamAV matched: PUA.Win.Packer.Upx-1")]) def test_addon_page_shows_virus_scan(make_client: Any, addon_id: int, scan: str) -> None: html = make_client().get(f"/addon/{addon_id}").text assert f"
Virus scan
{scan}" in html assert "No match does not prove that the code is safe." in html def test_addon_page_without_package_has_no_virus_scan(make_client: Any) -> None: assert "Virus scan" not in make_client().get(f"/addon/{HEATMAP}").text def test_addon_without_forks_has_no_versions(make_client: Any) -> None: html = make_client().get(f"/addon/{KANJI}").text assert 'id="versions"' not in html and "versions-hint" not in html and 'class="fork-of"' not in html def test_search_cards_open_addon_in_new_tab(make_client: Any) -> None: client = make_client() assert f'' in client.get("/search", params={"q": "kanji"}).text home = client.get("/").text assert f'' in home and 'target="_blank">' not in home def test_cards_mark_forks(make_client: Any) -> None: html = make_client().get("/search", params={"obsolete": "1", "tag": "statistics"}).text assert (f'' 'fork') in html assert (f'' 'has 1 fork โ†’') in html assert f'href="/addon/{FORK}"' not in make_client().get("/search", params={"nofork": "1"}).text def test_cards_mark_copies(make_client: Any) -> None: html = make_client().get("/search", params={"tag": "dictionary"}).text assert (f'' 'copy') in html AI_REASONS = {KANJI: "The GitHub repository has files of AI coding tools: claude-code, cursor.", OCCLUSION: "The description says that AI was used: vibe-coded.", FORK_OF_FORK: "The addon has AI features."} @pytest.mark.parametrize(("addon_id", "reason"), AI_REASONS.items()) def test_addon_page_marks_addons_built_with_ai(make_client: Any, addon_id: int, reason: str) -> None: header = make_client().get(f"/addon/{addon_id}").text.split("")[0] assert f'Built with AI' in header def test_addon_page_without_ai_signal_has_no_ai_mark(make_client: Any) -> None: assert "Built with AI" not in make_client().get(f"/addon/{HEATMAP}").text.split("")[0] def test_cards_do_not_mark_addons_built_with_ai(make_client: Any) -> None: assert "Built with AI" not in make_client().get("/search", params={"obsolete": "1"}).text def test_copy_page_links_its_original(make_client: Any) -> None: html = make_client().get(f"/addon/{KANJI_COPY}").text assert f'Copy of Kanji Helper' in html assert 'class="copies"' not in html def test_original_page_lists_its_copies_and_repo_addons(make_client: Any) -> None: html = make_client().get(f"/addon/{KANJI}").text assert f'Copies of this addon: Stroke Order Reupload

' in html assert f'
Same repository
Stroke Order Reupload
' in html assert "(for the whole repository)" in html and 'class="copy-of"' not in html def test_addon_page_without_copies_or_shared_repo(make_client: Any) -> None: html = make_client().get(f"/addon/{OCCLUSION}").text assert 'class="copy-of"' not in html and 'class="copies"' not in html assert "Same repository" not in html and "for the whole repository" not in html def test_addon_page_renders_readme_safely(make_client: Any) -> None: html = make_client().get(f"/addon/{KANJI}").text assert "

Kanji Helper

" in html assert "" not in html assert 'href="https://x.org" target="_blank" rel="nofollow noopener noreferrer"' in html for hostile in ("alert(2)", "alert(3)", "javascript:", " None: html = make_client().get(f"/addon/{KANJI}").text assert ('

' '

') in html def test_addon_page_renders_description_html_safely(make_client: Any) -> None: html = make_client().get(f"/addon/{OCCLUSION}").text assert '

Occlusion

' in html assert '' in html assert 'href="https://example.com/docs" target="_blank" rel="nofollow noopener noreferrer"' in html for hostile in ("alert(4)", "alert(5)", "alert(6)", "javascript:"): assert hostile not in html assert "Hide parts of an image." not in html def test_addon_page_keeps_line_breaks_of_pre_wrap_description(make_client: Any) -> None: html = make_client().get(f"/addon/{HEATMAP}").text assert '
Line one\nLine two
' in html def test_addon_page_falls_back_to_plain_description(make_client: Any, monkeypatch: pytest.MonkeyPatch) -> None: async def no_html(self: CatalogService, addon_id: int) -> None: return None monkeypatch.setattr(CatalogService, "description_html", no_html) html = make_client().get(f"/addon/{OCCLUSION}").text assert '
Hide parts of an image.
' in html def test_addon_page_shows_description_before_readme(make_client: Any) -> None: html = make_client().get(f"/addon/{KANJI}").text assert html.index("

Description

") < html.index("

README

") assert '
Kanji stroke order and readings.
' in html assert '
' in html def test_addon_page_resolves_relative_readme_links_against_github(make_client: Any) -> None: html = make_client().get(f"/addon/{KANJI}").text assert 'href="https://github.com/alice/kanji-helper/blob/HEAD/docs/manual.md"' in html assert 'src="https://github.com/alice/kanji-helper/raw/HEAD/img/a.png"' in html assert 'href="#usage"' in html def test_about_shows_dataset_date(make_client: Any) -> None: text = make_client().get("/about").text assert "collected on 1 Sep 2026" in text assert "stored for 90 days" in text def test_about_shows_contacts(make_client: Any) -> None: text = make_client().get("/about").text assert 'href="https://forums.ankiweb.net/t/anki-addons-dataset-a-detailed-list-of-addons/63090"' in text assert 'href="https://github.com/Aleks-Ya/anki-addons-catalog/issues"' in text def test_about_shows_mcp_version(make_client: Any) -> None: from anki_addons_mcp import __version__ assert f"Anki Addons MCP server (v{__version__})" in make_client().get("/about").text def test_about_without_mcp_version_when_catalog_is_down(make_client: Any, monkeypatch: pytest.MonkeyPatch) -> None: from anki_addons_catalog.domain.errors import CatalogUnavailable async def down(self: Any) -> None: raise CatalogUnavailable("down") monkeypatch.setattr(McpCatalog, "server_version", down) response = make_client().get("/about") assert response.status_code == 200 and "Anki Addons MCP server gives" in response.text def test_compatibility_verdict(make_client: Any) -> None: assert "verdict-supported" in make_client().get(f"/addon/{KANJI}?anki=25.02").text def test_header_has_no_dataset_date_when_catalog_is_down(make_client: Any, monkeypatch: pytest.MonkeyPatch) -> None: from anki_addons_catalog.application.catalog import CatalogService from anki_addons_catalog.domain.errors import CatalogUnavailable async def down(self: Any) -> None: raise CatalogUnavailable("down") monkeypatch.setattr(CatalogService, "latest_snapshot_info", down) response = make_client().get("/about") assert response.status_code == 200 and 'class="dataset-date"' not in response.text @pytest.mark.parametrize("path", ["/search", "/search?q=kanji", f"/addon/{KANJI}"]) def test_anki_version_inputs_suggest_releases(make_client: Any, path: str) -> None: text = make_client().get(path).text assert 'list="anki-versions"' in text and "e.g. 25.09.2" in text assert ('') in text def test_anki_version_inputs_without_suggestions_when_tool_fails(make_client: Any, monkeypatch: pytest.MonkeyPatch) -> None: from anki_addons_catalog.domain.errors import ToolFailed async def failing(self: Any) -> None: raise ToolFailed("list_anki_versions", "Unknown tool") monkeypatch.setattr(CatalogService, "anki_versions", failing) client = make_client() for path in ["/search", f"/addon/{KANJI}"]: response = client.get(path) assert response.status_code == 200 and " None: assert make_client().get("/addon/42").status_code == 404 def test_unknown_top_metric_is_404(make_client: Any) -> None: assert make_client().get("/top/nope").status_code == 404 def test_history_json(make_client: Any) -> None: assert len(make_client().get(f"/addon/{OCCLUSION}/history").json()["points"]) == 2 def test_search_page_has_keyword_results_and_ai_section(make_client: Any) -> None: html = make_client().get("/search?q=kanji").text assert 'data-query="kanji"' in html and '>Ask the AI' in html assert f'href="/addon/{KANJI}"' in html def test_search_filters_narrow_results_and_keep_in_links(make_client: Any) -> None: client = make_client() html = client.get("/search", params={"q": "image", "rating": "200", "tag": "image-occlusion"}).text assert f'href="/addon/{OCCLUSION}"' in html assert 'data-filters="tag=image-occlusion&rating=200"' in html assert '' in html # a new question keeps the filters assert 'href="/search?q=image&rating=200"' in html # the chip that removes the tag assert ' None: client = make_client() html = client.get("/search").text assert "All addons (5)" in html and 'id="ai"' not in html and 'name="sort"' in html assert f'href="/addon/{HEATMAP}"' in client.get("/search", params={"obsolete": "1", "tag": "statistics"}).text assert client.get("/search", params={"tag": "nope", "q": "kanji"}).status_code == 200 def test_browse_keywords_narrow_the_list_and_keep_the_sort_order(make_client: Any) -> None: client = make_client() html = client.get("/search", params={"kw": "heatmap", "obsolete": "1", "sort": "update_date"}).text assert 'name="kw" value="heatmap"' in html and 'id="ai"' not in html assert html.index(f'href="/addon/{FORK_OF_FORK}"') < html.index(f'href="/addon/{HEATMAP}"') assert f'href="/addon/{KANJI}"' not in html assert 'href="/search?obsolete=1&sort=update_date"' in html # the chip that removes the keywords assert ' None: assert search_url("a b", SearchFilters(tags=["cloze"], sort="likes"), 30) == "/search?q=a+b&tag=cloze&offset=30" assert search_url("", SearchFilters(sort="likes")) == "/search?sort=likes" assert search_url("", SearchFilters(keywords="a b"), 30) == "/search?kw=a+b&offset=30" assert search_url("q", SearchFilters(keywords="a b")) == "/search?q=q" assert search_url() == "/search" def test_ask_applies_filters(make_client: Any) -> None: llm = scripted_llm() make_client(llm).get("/api/ask", params={"q": "kanji", "anki": "25.09", "tag": "dictionary", "lang": "Python"}) assert "Visitor filters" in llm.requests[0][0]["content"] assert "Anki 25.09, dictionary, Language: Python" in llm.requests[0][0]["content"] def test_search_filters_by_all_chosen_languages(make_client: Any) -> None: client = make_client() html = client.get("/search", params={"lang": ["python", "JavaScript"]}).text assert f'href="/addon/{KANJI}"' in html and f'href="/addon/{FORK_OF_FORK}"' not in html assert '' in html # the catalog's spelling assert 'href="/search?lang=JavaScript"' in html # the chip that removes Python assert 'name="lang" value="CSS" >' in html and '4' in html assert '' in html # unknown, but can be cleared assert '' in html # a new question keeps the filter def test_tags_page_lists_categories(make_client: Any) -> None: html = make_client().get("/tags").text assert 'href="/tag/dictionary"' in html assert 'href="/tag/paid"' in html assert "Lookup, definitions, translation" in html def test_tag_page_lists_addons_and_hides_obsolete_ones(make_client: Any) -> None: client = make_client() assert f'href="/addon/{KANJI}"' in client.get("/tag/dictionary").text statistics = client.get("/tag/statistics").text assert f'href="/addon/{HEATMAP}"' not in statistics assert "obsolete addons are hidden" in statistics assert f'href="/addon/{HEATMAP}"' in client.get("/tag/obsolete").text assert 'href="/search?tag=statistics"' in statistics def test_unknown_tag_is_404(make_client: Any) -> None: assert make_client().get("/tag/nope").status_code == 404 def test_cards_and_addon_page_link_tags(make_client: Any) -> None: client = make_client() assert 'href="/tag/image-occlusion"' in client.get("/").text assert 'href="/tag/dictionary"' in client.get(f"/addon/{KANJI}").text def test_static_links_are_root_relative(make_client: Any) -> None: # The custom-domain proxy reports http, so absolute links would be blocked as mixed content html = make_client().get("/").text assert 'href="/static/app.css?v=' in html assert "http://testserver/static" not in html def test_stats_has_ai_tags(make_client: Any) -> None: html = make_client().get("/stats").text assert "AI tag" in html assert 'href="/tags"' in html def test_stats_has_github_and_package_languages(make_client: Any) -> None: html = make_client().get("/stats").text assert "Language on GitHub" in html assert "Language in the package" in html def test_sitemap_and_robots(make_client: Any) -> None: client = make_client() sitemap = client.get("/sitemap.xml").text assert f"https://example.org/addon/{KANJI}" in sitemap assert "https://example.org/tags" in sitemap assert "https://example.org/tag/dictionary" in sitemap robots = client.get("/robots.txt").text assert "Sitemap: https://example.org/sitemap.xml" in robots assert "Disallow: /admin/" in robots and "Disallow: /addon/*/alternatives" in robots def test_healthz(make_client: Any) -> None: assert make_client().get("/healthz").json()["status"] == "ok" def test_ask_streams_answer(make_client: Any) -> None: response = make_client().get("/api/ask", params={"q": "kanji"}) assert response.headers["content-type"].startswith("text/event-stream") events = sse_events(response.text) names = [name for name, _ in events] assert names[-3:] == ["answer", "addons", "done"] answer_html = events[-3][1]["html"] assert f'Kanji Helper' in answer_html assert events[-2][1]["count"] == 1 and f'' in events[-2][1]["html"] def test_ask_validates_query(make_client: Any) -> None: client = make_client(max_query_chars=10) assert sse_events(client.get("/api/ask", params={"q": " "}).text)[0][0] == "error" assert sse_events(client.get("/api/ask", params={"q": "x" * 11}).text)[0][0] == "error" home = client.get("/").text assert '