Spaces:
Running
Running
Download tests/interface/test_web.py from Ya-Alex/anki-addons-catalog: direct link, hf CLI and curl.
- Browser
- Download file 38.1 kB
-
https://huggingface.co/spaces/Ya-Alex/anki-addons-catalog/resolve/main/tests/interface/test_web.py
- Command line
-
hf download hf://spaces/Ya-Alex/anki-addons-catalog/tests/interface/test_web.py
-
curl -L -o test_web.py https://huggingface.co/spaces/Ya-Alex/anki-addons-catalog/resolve/main/tests/interface/test_web.py
38.1 kB
| 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) | |
| 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"), | |
| ]) | |
| 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 | |
| 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'<span class="beta" title="The site is new: expect rough edges">v{__version__} BETA</span>' in response.text | |
| assert 'class="dataset-date"' in response.text and ">1 Sep 2026</a>" 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.") | |
| 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'<meta name="description" content="{description}">' in html | |
| assert f'<meta property="og:description" content="{description}">' in html | |
| def test_home_link_preview_title(make_client: Any) -> None: | |
| assert '<meta property="og:title" content="Anki Addons Catalog">' 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'<meta property="og:description" content="{DEFAULT_DESCRIPTION.format("every addon")}">' in html | |
| def test_addon_link_preview_uses_addon_summary(make_client: Any) -> None: | |
| html = make_client().get(f"/addon/{OCCLUSION}").text | |
| assert '<meta property="og:title" content="Image Occlusion Plus – Anki addon' in html | |
| assert '<meta property="og:description" content="Find Anki addons' not in html | |
| def test_cards_show_votes_and_approval(make_client: Any) -> None: | |
| html = make_client().get("/").text | |
| assert "300 votes" in html and "98% approval" in html # Image Occlusion Plus: 298 likes, 2 dislikes | |
| assert "<dt>Votes</dt><dd>300 (👍 298 · 👎 2)</dd>" in make_client().get(f"/addon/{OCCLUSION}").text | |
| def _versions(html: str) -> str: | |
| return html.split('<section id="versions">', 1)[1].split("</section>", 1)[0] | |
| def test_fork_page_links_its_parent(make_client: Any) -> None: | |
| html = make_client().get(f"/addon/{FORK}").text | |
| assert f'<p class="fork-of">Fork of <a href="/addon/{HEATMAP}">Review Heatmap</a></p>' in html | |
| assert '<a href="https://github.com/glutanimate/review-heatmap" target="_blank" rel="noopener">' in html | |
| assert '<strong>2</strong> other versions of this addon exist. <a href="#versions">' in html | |
| 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 '<tr class="current">' in versions and "<small>this addon</small>" 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 "<th>Works on Anki 25.09.2</th>" in versions and "<small>original</small>" in versions | |
| assert versions.count("(AI-detected; may be wrong)") == 1 # Heatmap Plus; Heatmap Revived is a GitHub fork | |
| assert "<td>obsolete</td>" in versions # Review Heatmap: it gets no best mark, though it has the most votes | |
| assert '<td class="best">👍 8 · 👎 2</td>' in versions and '<td class="best">👍 78 · 👎 2</td>' 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 "<th>Works on Anki 2.1.66</th>" in versions | |
| assert '<mark class="verdict-unsupported">unsupported</mark>' in versions # Heatmap Revived needs 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 "<title>Alternatives to Review Heatmap – Anki Addons Catalog</title>" in html | |
| assert f'data-query="Alternatives to Review Heatmap (addon {HEATMAP})"' in html and 'data-filters=""' in html | |
| assert '<meta name="robots" content="noindex">' in html and '>Ask the AI for alternatives</button>' in html | |
| assert f'<link rel="canonical" href="https://example.org/addon/{HEATMAP}/alternatives">' in html | |
| assert "Similar addons" in html and f'<a href="/addon/{FORK}" target="_blank">' 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 | |
| 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"<dt>Languages</dt><dd>{languages}</dd>" in html | |
| def test_addon_page_shows_github_languages(make_client: Any) -> None: | |
| assert "<dt>Languages</dt><dd>Python, CSS</dd>" in make_client().get(f"/addon/{FORK}").text | |
| def test_addon_page_shows_license_with_source(make_client: Any, addon_id: int, license_text: str) -> None: | |
| assert f"<dt>License</dt><dd>{license_text}</dd>" 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 "<dd>A license file that GitHub does not recognize</dd>" in html | |
| assert "NOASSERTION" not in html | |
| 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"<dt>Virus scan</dt><dd>{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'<a href="/addon/{KANJI}" target="_blank">' in client.get("/search", params={"q": "kanji"}).text | |
| home = client.get("/").text | |
| assert f'<a href="/addon/{OCCLUSION}">' in home and 'target="_blank"><strong>' 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'<a class="badge" href="/addon/{FORK}#versions" target="_blank" title="Compare the versions of this addon">' | |
| '<mark>fork</mark></a>') in html | |
| assert (f'<a class="badge" href="/addon/{HEATMAP}#versions" target="_blank" title="Compare the versions of this addon">' | |
| '<mark>has 1 fork →</mark></a>') 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'<a class="badge" href="/addon/{KANJI}" target="_blank" title="Open the original addon">' | |
| '<mark>copy</mark></a>') 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."} | |
| 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("</hgroup>")[0] | |
| assert f'<mark title="{reason}">Built with AI</mark>' 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("</hgroup>")[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 <a href="/addon/{KANJI}">Kanji Helper</a>' 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: <a href="/addon/{KANJI_COPY}">Stroke Order Reupload</a></p>' in html | |
| assert f'<dt>Same repository</dt><dd><a href="/addon/{KANJI_COPY}">Stroke Order Reupload</a></dd>' in html | |
| assert "<small>(for the whole repository)</small>" 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 "<h1>Kanji Helper</h1>" in html | |
| assert "<script>alert(1)</script>" not in html | |
| assert 'href="https://x.org" target="_blank" rel="nofollow noopener noreferrer"' in html | |
| for hostile in ("alert(2)", "alert(3)", "javascript:", "<iframe", "evil.org", "display:none"): | |
| assert hostile not in html | |
| def test_addon_page_renders_readme_raw_html(make_client: Any) -> None: | |
| html = make_client().get(f"/addon/{KANJI}").text | |
| assert ('<p align="center"><a href="https://y.org" target="_blank" rel="nofollow noopener noreferrer">' | |
| '<img src="https://github.com/alice/kanji-helper/raw/HEAD/img/b.png"></a></p>') in html | |
| def test_addon_page_renders_description_html_safely(make_client: Any) -> None: | |
| html = make_client().get(f"/addon/{OCCLUSION}").text | |
| assert '<article class="description-html" data-collapsible><h2>Occlusion</h2>' in html | |
| assert '<img src="https://example.com/o.png" width="900">' 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 '<article class="description-html pre-wrap" data-collapsible>Line one\nLine two</article>' 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 '<article class="description" data-collapsible>Hide parts of an image.</article>' 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("<h2>Description</h2>") < html.index("<h2>README</h2>") | |
| assert '<article class="description" data-collapsible>Kanji stroke order and readings.</article>' in html | |
| assert '<article class="readme" data-collapsible>' 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 <b>1 Sep 2026</b>" 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</a> (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</a> 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 | |
| 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 ('<datalist id="anki-versions"><option value="25.09.2"><option value="25.09">' | |
| '<option value="2.1.66"></datalist>') 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 "<datalist" not in response.text and "e.g. 25.0" in response.text | |
| def test_missing_addon_is_404(make_client: Any) -> 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</button>' 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 '<input type="hidden" name="tag" value="image-occlusion">' in html # a new question keeps the filters | |
| assert 'href="/search?q=image&rating=200"' in html # the chip that removes the tag | |
| assert '<input type="search" class="filter-find" placeholder="Find a category"' in html # no name: not sent | |
| assert 'name="sort"' not in html # a query ranks by relevance | |
| assert f'href="/addon/{KANJI}"' not in client.get("/search", params={"q": "kanji", "anki": "2.1.50"}).text | |
| def test_search_without_query_browses_the_catalog(make_client: Any) -> None: | |
| client = make_client() | |
| html = client.get("/search").text | |
| assert "All addons <small>(5)</small>" 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 '<input type="hidden" name="kw"' not in html # a question does not take the keywords | |
| html = client.get("/search", params={"q": "kanji", "kw": "heatmap"}).text | |
| assert f'href="/addon/{KANJI}"' in html and 'name="kw"' not in html and "Keywords:" not in html | |
| def test_search_url_keeps_filters() -> 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 '<input type="checkbox" name="lang" value="Python" checked>' 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 '<span class="count">4</span>' in html | |
| assert '<input type="search" class="filter-find" placeholder="Find a language"' in html # no name: not sent | |
| assert f'href="/addon/{FORK_OF_FORK}"' in client.get("/search", params={"lang": "Python"}).text | |
| html = client.get("/search", params={"q": "kanji", "lang": "Rust"}).text | |
| assert f'href="/addon/{KANJI}"' not in html | |
| assert '<input type="checkbox" name="lang" value="Rust" checked>' in html # unknown, but can be cleared | |
| assert '<input type="hidden" name="lang" value="Rust">' 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"<loc>https://example.org/addon/{KANJI}</loc>" in sitemap | |
| assert "<loc>https://example.org/tags</loc>" in sitemap | |
| assert "<loc>https://example.org/tag/dictionary</loc>" 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'<strong><a href="/addon/{KANJI}" target="_blank">Kanji Helper</a></strong>' in answer_html | |
| assert events[-2][1]["count"] == 1 and f'<a href="/addon/{KANJI}" target="_blank">' 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 '<textarea name="q"' in home and 'maxlength="10"' in home | |
| def test_ask_rate_limited(make_client: Any) -> None: | |
| client = make_client(rate_limit_per_hour=1) | |
| client.get("/api/ask", params={"q": "kanji"}) | |
| events = sse_events(client.get("/api/ask", params={"q": "kanji"}).text) | |
| assert events[0][0] == "error" and "many questions" in events[0][1] | |
| def test_ask_budget_exhausted(make_client: Any) -> None: | |
| events = sse_events(make_client(daily_budget_usd=0).get("/api/ask", params={"q": "kanji"}).text) | |
| assert events[0][0] == "error" and "AI search is paused until" in events[0][1] | |
| def test_turnstile_gate(make_client: Any, monkeypatch: pytest.MonkeyPatch) -> None: | |
| client = make_client(turnstile_site_key="site", turnstile_secret="secret", session_secret="s") | |
| assert sse_events(client.get("/api/ask", params={"q": "kanji"}).text) == [("verify", None)] | |
| assert 'data-site-key="site"' in client.get("/search?q=kanji").text | |
| from anki_addons_catalog.interface.web import security | |
| async def fake_verify(self: Any, token: str, ip: str) -> bool: | |
| return token == "good" | |
| monkeypatch.setattr(security.HumanCheck, "verify", fake_verify) | |
| assert client.post("/api/verify", data={"token": "bad"}).status_code == 403 | |
| response = client.post("/api/verify", data={"token": "good"}) | |
| assert response.status_code == 200 and PASS_COOKIE in response.cookies | |
| events = sse_events(client.get("/api/ask", params={"q": "kanji"}).text) | |
| assert events[-1][0] == "done" | |
| client.cookies.clear() # set() alone adds a second cookie beside the issued one, and both are sent | |
| client.cookies.set(PASS_COOKIE, "9999999999.forged") | |
| assert sse_events(client.get("/api/ask", params={"q": "kanji"}).text) == [("verify", None)] | |
| def test_cached_answers_need_no_turnstile_or_rate_limit(make_client: Any) -> None: | |
| client = make_client(turnstile_site_key="site", turnstile_secret="secret", session_secret="s", | |
| admin_token="secret", rate_limit_per_hour=1) | |
| assert sse_events(client.get("/api/ask", params={"q": "kanji", "cached": "1"}).text) == [("not_cached", None)] | |
| assert sse_events(client.get("/api/ask", params={"q": "kanji"}, auth=("admin", "secret")).text)[-1][0] == "done" | |
| for _ in range(2): # beyond the rate limit, without a pass | |
| events = sse_events(client.get("/api/ask", params={"q": "kanji", "cached": "1"}).text) | |
| assert [name for name, _ in events] == ["answer", "addons", "done"] | |
| assert sse_events(client.get("/api/ask", params={"q": "kanji"}).text) == [("verify", None)] | |
| def test_ask_rate_limited_per_pass(make_client: Any, monkeypatch: pytest.MonkeyPatch) -> None: | |
| client = make_client(turnstile_site_key="site", turnstile_secret="secret", session_secret="s", | |
| rate_limit_per_hour=1) | |
| from anki_addons_catalog.interface.web import security | |
| async def fake_verify(self: Any, token: str, ip: str) -> bool: | |
| return True | |
| monkeypatch.setattr(security.HumanCheck, "verify", fake_verify) | |
| def ask(ip: str) -> list[tuple[str, Any]]: | |
| return sse_events(client.get("/api/ask", params={"q": "kanji"}, headers={"X-Forwarded-For": ip}).text) | |
| client.post("/api/verify", data={"token": "t"}) | |
| assert ask("1.1.1.1")[-1][0] == "done" | |
| events = ask("2.2.2.2") # the same pass from another IP | |
| assert events[0][0] == "error" and "many questions" in events[0][1] | |
| client.cookies.clear() | |
| client.post("/api/verify", data={"token": "t"}) | |
| assert ask("3.3.3.3")[-1][0] == "done" # 2.2.2.2 used its own token on the denied question | |
| def test_pass_ids_are_unique_and_old_cookies_invalid() -> None: | |
| from starlette.requests import Request | |
| from anki_addons_catalog.interface.web.security import HumanCheck | |
| human = HumanCheck("site", "secret", "s", 3600) | |
| def request(cookie: str) -> Request: | |
| return Request({"type": "http", "headers": [(b"cookie", f"{PASS_COOKIE}={cookie}".encode())]}) | |
| first, second = human.issue_pass(now=1000), human.issue_pass(now=1000) | |
| assert human.pass_id(request(first), now=1000) != human.pass_id(request(second), now=1000) | |
| assert human.pass_id(request(first), now=1000) and human.pass_id(request(first), now=5000) is None | |
| expires = "9999999999" | |
| assert human.pass_id(request(f"{expires}.{human._sign(expires)}")) is None # the format before pass ids | |
| assert HumanCheck("site", None, "s", 3600).pass_id(request(first), now=1000) is None # check disabled | |
| def siteverify(*answers: httpx.Response | Exception) -> tuple[HumanCheck, list[dict[str, str]]]: | |
| """A HumanCheck whose siteverify calls get `answers` in turn, and the form data of each call.""" | |
| sent: list[dict[str, str]] = [] | |
| queue = list(answers) | |
| def handler(request: httpx.Request) -> httpx.Response: | |
| sent.append(dict(parse_qsl(request.content.decode()))) | |
| answer = queue.pop(0) | |
| if isinstance(answer, Exception): | |
| raise answer | |
| return answer | |
| return HumanCheck("site", "the-secret", "s", 3600, transport=httpx.MockTransport(handler)), sent | |
| async def test_siteverify_accepts_a_valid_token() -> None: | |
| human, sent = siteverify(httpx.Response(200, json={"success": True})) | |
| assert await human.verify("the-token", "1.2.3.4") | |
| assert sent[0]["secret"] == "the-secret" and sent[0]["response"] == "the-token" | |
| assert sent[0]["remoteip"] == "1.2.3.4" and sent[0]["idempotency_key"] | |
| async def test_siteverify_logs_the_error_codes(caplog: pytest.LogCaptureFixture) -> None: | |
| human, _ = siteverify(httpx.Response(200, json={"success": False, "error-codes": ["invalid-input-secret"]})) | |
| assert not await human.verify("the-token", "1.2.3.4") | |
| assert "invalid-input-secret" in caplog.text | |
| assert "the-secret" not in caplog.text and "the-token" not in caplog.text | |
| async def test_siteverify_retries_a_network_error_once(caplog: pytest.LogCaptureFixture) -> None: | |
| human, sent = siteverify(httpx.ConnectTimeout(""), httpx.Response(200, json={"success": True})) | |
| assert await human.verify("the-token", "1.2.3.4") | |
| assert len(sent) == 2 and sent[0]["idempotency_key"] == sent[1]["idempotency_key"] | |
| assert "ConnectTimeout" in caplog.text and "attempt 1 of 2" in caplog.text | |
| async def test_siteverify_fails_after_two_network_errors(caplog: pytest.LogCaptureFixture) -> None: | |
| human, sent = siteverify(httpx.ConnectTimeout(""), httpx.ReadTimeout("")) | |
| assert not await human.verify("the-token", "1.2.3.4") | |
| assert len(sent) == 2 and "ConnectTimeout" in caplog.text and "ReadTimeout" in caplog.text | |
| async def test_siteverify_logs_a_non_json_answer(caplog: pytest.LogCaptureFixture) -> None: | |
| human, _ = siteverify(httpx.Response(500, text="<html>Server error</html>")) | |
| assert not await human.verify("the-token", "1.2.3.4") | |
| assert "HTTP 500" in caplog.text and "Server error" in caplog.text | |
| def test_admin_asks_without_turnstile_and_rate_limit(make_client: Any) -> None: | |
| client = make_client(turnstile_site_key="site", turnstile_secret="secret", session_secret="s", | |
| admin_token="secret", rate_limit_per_hour=1) | |
| for _ in range(2): | |
| assert sse_events(client.get("/api/ask", params={"q": "kanji"}, auth=("admin", "secret")).text)[-1][0] == "done" | |
| assert sse_events(client.get("/api/ask", params={"q": "kanji"}, auth=("admin", "wrong")).text) == [("verify", None)] | |
| def test_admin_usage_needs_a_configured_token(make_client: Any) -> None: | |
| assert make_client().get("/admin/usage", auth=("admin", "")).status_code == 404 | |
| def test_admin_usage_rejects_wrong_credentials(make_client: Any) -> None: | |
| client = make_client(admin_token="secret") | |
| response = client.get("/admin/usage") | |
| assert response.status_code == 401 and response.headers["www-authenticate"].startswith("Basic") | |
| assert client.get("/admin/usage", auth=("admin", "wrong")).status_code == 401 | |
| def test_admin_usage_counts_searches_and_views(make_client: Any) -> None: | |
| client = make_client(admin_token="secret") | |
| client.get("/search", params={"q": "kanji"}) | |
| client.get("/search") | |
| client.get(f"/addon/{KANJI}") | |
| client.get("/api/ask", params={"q": "kanji"}) | |
| html = client.get("/admin/usage", auth=("admin", "secret")).text | |
| assert '<small>Keyword searches</small><p class="kpi">1</p>' in html | |
| assert '<small>AI questions</small><p class="kpi">1</p>' in html | |
| assert '<small>Page views</small><p class="kpi">3</p>' in html | |
| assert '<tr><td>search</td><td class="num">2</td></tr>' in html | |
| assert "This month: $" in html and "paused until" not in html | |
| assert '<meta name="robots" content="noindex">' in html | |
| def test_admin_questions(make_client: Any) -> None: | |
| client = make_client(admin_token="secret") | |
| assert client.get("/admin/questions").status_code == 401 | |
| assert client.get("/admin/questions.jsonl").status_code == 401 | |
| client.get("/api/ask", params={"q": "kanji"}) | |
| auth = ("admin", "secret") | |
| assert 'href="/admin/questions"' in client.get("/admin/usage", auth=auth).text | |
| html = client.get("/admin/questions", auth=auth).text | |
| assert '<a href="/admin/questions/1">kanji</a>' in html and "<td>answered</td><td>haiku-5-5</td>" in html | |
| detail = client.get("/admin/questions/1", auth=auth).text | |
| assert "· claude-haiku-5-5" in detail and "search_addons" in detail and f'<a href="/addon/{KANJI}">Kanji Helper</a>' in detail | |
| assert client.get("/admin/questions/2", auth=auth).status_code == 404 | |
| export = client.get("/admin/questions.jsonl", auth=auth) | |
| assert export.headers["content-type"].startswith("application/x-ndjson") | |
| (row,) = [json.loads(line) for line in export.text.splitlines()] | |
| assert row["query"] == "kanji" and row["trace"][0]["tools"][0]["name"] == "search_addons" | |
| def test_human_date() -> None: | |
| from anki_addons_catalog.interface.web.rendering import human_date | |
| assert human_date("2026-10-01") == "1 Oct 2026" | |
| assert human_date("2026-09-03T04:05:00+00:00") == "3 Sep 2026" | |
| assert human_date("soon") == "soon" | |