"""Tests for the Fandom wiki faction resolver (offline: mocked HTTP).""" from __future__ import annotations from collections.abc import Mapping, Sequence from pathlib import Path import httpx import pytest from genshin_tcg import pipeline from genshin_tcg.config import Settings from genshin_tcg.constants import Faction from genshin_tcg.data.catalog import Catalog, save_catalog from genshin_tcg.data.fandom import ( FactionIconReport, FactionResolution, FandomError, FandomSource, faction_from_family, faction_from_region, parse_character_regions, parse_enemy_families, parse_region_emblems, resolve_factions, slug, sync_faction_icons, ) _CHARACTER_TABLE = """
| Icon | Name | Quality | Region | Version |
|---|---|---|---|---|
| Ganyu | 5 Stars |
Liyue |
1.2 | |
| Aloy | 5 Stars | None | 2.1 |
no table here
") def test_parse_character_regions_rejects_unexpected_header() -> None: with pytest.raises(FandomError): parse_character_regions('| Foo |
|---|
empty
") == {} # --- Resolution -------------------------------------------------------------- def test_resolve_factions_matches_playable_and_enemy(sample_catalog: Catalog) -> None: source = _FakeSource(regions={"test_pyro": "Mondstadt"}) resolution = resolve_factions(sample_catalog, source=source) assert isinstance(resolution, FactionResolution) assert resolution.assignments == {"test_pyro": "mondstadt"} assert resolution.playable == ("test_pyro",) assert resolution.matched == 1 def test_resolve_factions_falls_back_to_family(sample_catalog: Catalog) -> None: source = _FakeSource(families={"test_pyro": "Fatui"}) resolution = resolve_factions(sample_catalog, source=source) assert resolution.assignments == {"test_pyro": "fatui"} assert resolution.enemies == ("test_pyro",) def test_resolve_factions_ignores_unmappable_region(sample_catalog: Catalog) -> None: source = _FakeSource(regions={"test_pyro": "None"}) resolution = resolve_factions(sample_catalog, source=source) assert resolution.assignments == {} assert resolution.unmatched == ("test_pyro",) def test_resolve_factions_reports_unmatched(sample_catalog: Catalog) -> None: resolution = resolve_factions(sample_catalog, source=_FakeSource()) assert resolution.unmatched == ("test_pyro",) assert resolution.matched == 0 # --- Emblem sync ------------------------------------------------------------- def _resolution(assignments: Mapping[str, str]) -> FactionResolution: return FactionResolution(assignments=dict(assignments)) def test_sync_faction_icons_downloads_nation_emblems(tmp_path: Path) -> None: resolution = _resolution({"ganyu": "liyue", "diluc": "mondstadt", "rhodeia": "monster"}) source = _FakeIconSource( emblems={"Liyue": "Liyue Emblem Night.png", "Mondstadt": "Mondstadt Emblem Night.png"}, urls={ "Liyue Emblem Night.png": "https://wiki/liyue.png", "Mondstadt Emblem Night.png": "https://wiki/mondstadt.png", }, ) report = sync_faction_icons(resolution, source=source, assets_dir=tmp_path) assert isinstance(report, FactionIconReport) assert report.downloaded == ("liyue", "mondstadt") assert report.missing == ("monster",) assert report.ok assert (tmp_path / "liyue.png").is_file() assert (tmp_path / "mondstadt.png").is_file() def test_sync_faction_icons_reports_missing_url(tmp_path: Path) -> None: resolution = _resolution({"ganyu": "liyue"}) source = _FakeIconSource(emblems={"Liyue": "Liyue Emblem Night.png"}) report = sync_faction_icons(resolution, source=source, assets_dir=tmp_path) assert report.failed == {"liyue": "no image URL for 'Liyue Emblem Night.png'"} assert not report.ok # --- HTTP client ------------------------------------------------------------- def _ok_response(text: str) -> httpx.Response: return httpx.Response(200, json={"parse": {"title": "Page", "text": text}}) def test_fandom_source_caches_pages(tmp_path: Path) -> None: calls: list[str] = [] def handler(request: httpx.Request) -> httpx.Response: calls.append(str(request.url)) return _ok_response("ok") client = httpx.Client(transport=httpx.MockTransport(handler)) with FandomSource(cache_dir=tmp_path, client=client) as source: assert source.render_page("Character/List") == "ok" assert source.render_page("Character/List") == "ok" assert len(calls) == 1 assert (tmp_path / "character_list.html").is_file() def test_fandom_source_force_refetches(tmp_path: Path) -> None: calls: list[str] = [] def handler(request: httpx.Request) -> httpx.Response: calls.append(str(request.url)) return _ok_response("ok") client = httpx.Client(transport=httpx.MockTransport(handler)) with FandomSource(cache_dir=tmp_path, client=client) as source: source.render_page("Character/List") source.render_page("Character/List", force=True) assert len(calls) == 2 def test_fandom_source_builds_lookups(tmp_path: Path) -> None: bodies = {"Character/List": _CHARACTER_TABLE, "Enemy/List": _ENEMY_LIST} def handler(request: httpx.Request) -> httpx.Response: page = request.url.params["page"] return _ok_response(bodies[page]) client = httpx.Client(transport=httpx.MockTransport(handler)) with FandomSource(cache_dir=tmp_path, client=client) as source: assert source.character_regions() == {"ganyu": "Liyue", "aloy": "None"} assert source.enemy_families() == { "fatui_pyro_agent": "Fatui", "stonehide_lawachurl": "Hilichurls", } assert source.region_emblems() == {"Liyue": "Liyue Emblem Night.png"} def test_fandom_source_file_urls(tmp_path: Path) -> None: def handler(request: httpx.Request) -> httpx.Response: assert request.url.params["action"] == "query" return httpx.Response( 200, json={ "query": { "pages": [ { "title": "File:Liyue Emblem Night.png", "imageinfo": [{"url": "https://wiki/liyue.png"}], }, {"title": "File:Nope.png", "missing": True}, ] } }, ) client = httpx.Client(transport=httpx.MockTransport(handler)) with FandomSource(cache_dir=tmp_path, client=client) as source: assert source.file_urls(["Liyue Emblem Night.png", "Nope.png", ""]) == { "Liyue Emblem Night.png": "https://wiki/liyue.png" } def test_fandom_source_file_urls_empty(tmp_path: Path) -> None: client = httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(500))) with FandomSource(cache_dir=tmp_path, client=client) as source: assert source.file_urls([]) == {} def test_fandom_source_downloads_and_caches(tmp_path: Path) -> None: calls: list[str] = [] def handler(request: httpx.Request) -> httpx.Response: calls.append(str(request.url)) return httpx.Response(200, content=b"image-bytes") destination = tmp_path / "liyue.png" client = httpx.Client(transport=httpx.MockTransport(handler)) with FandomSource(cache_dir=tmp_path, client=client) as source: assert source.download("https://wiki/liyue.png", destination) is True assert source.download("https://wiki/liyue.png", destination) is False assert destination.read_bytes() == b"image-bytes" assert len(calls) == 1 def test_fandom_source_download_raises_on_error(tmp_path: Path) -> None: client = httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(404))) with FandomSource(cache_dir=tmp_path, client=client) as source, pytest.raises(FandomError): source.download("https://wiki/missing.png", tmp_path / "missing.png") def test_fandom_source_raises_on_bad_payload(tmp_path: Path) -> None: def handler(request: httpx.Request) -> httpx.Response: return httpx.Response(200, json={"error": "nope"}) client = httpx.Client(transport=httpx.MockTransport(handler)) with FandomSource(cache_dir=tmp_path, client=client) as source, pytest.raises(FandomError): source.render_page("Character/List") def test_fandom_source_raises_on_http_error(tmp_path: Path) -> None: def handler(request: httpx.Request) -> httpx.Response: return httpx.Response(500) client = httpx.Client(transport=httpx.MockTransport(handler)) with FandomSource(cache_dir=tmp_path, client=client) as source, pytest.raises(FandomError): source.render_page("Character/List") # --- Pipeline stage ---------------------------------------------------------- def test_pipeline_factions_writes_overrides( settings: Settings, sample_catalog: Catalog ) -> None: settings.ensure_directories() save_catalog(sample_catalog, settings.catalog_path) result = pipeline.factions(settings, source=_FakeSource(regions={"test_pyro": "Mondstadt"})) assert result.written is True assert result.added == ("test_pyro",) assert result.output.is_file() assert '"test_pyro": "mondstadt"' in result.output.read_text(encoding="utf-8") def test_pipeline_factions_preserves_hand_made_entries( settings: Settings, sample_catalog: Catalog ) -> None: settings.ensure_directories() save_catalog(sample_catalog, settings.catalog_path) settings.factions_override.parent.mkdir(parents=True, exist_ok=True) settings.factions_override.write_text( '{"test_pyro": "liyue", "manual_card": "fatui"}\n', encoding="utf-8" ) result = pipeline.factions(settings, source=_FakeSource(regions={"test_pyro": "Mondstadt"})) assert result.conflicts == ("test_pyro",) written = result.output.read_text(encoding="utf-8") assert '"test_pyro": "liyue"' in written assert '"manual_card": "fatui"' in written def test_pipeline_factions_overwrite_discards_hand_made_entries( settings: Settings, sample_catalog: Catalog ) -> None: settings.ensure_directories() save_catalog(sample_catalog, settings.catalog_path) settings.factions_override.parent.mkdir(parents=True, exist_ok=True) settings.factions_override.write_text('{"manual_card": "fatui"}\n', encoding="utf-8") result = pipeline.factions( settings, overwrite=True, source=_FakeSource(regions={"test_pyro": "Mondstadt"}) ) written = result.output.read_text(encoding="utf-8") assert '"test_pyro": "mondstadt"' in written assert "manual_card" not in written def test_pipeline_factions_dry_run_does_not_write( settings: Settings, sample_catalog: Catalog ) -> None: settings.ensure_directories() save_catalog(sample_catalog, settings.catalog_path) result = pipeline.factions( settings, write=False, source=_FakeSource(regions={"test_pyro": "Mondstadt"}) ) assert result.written is False assert not result.output.exists() def test_pipeline_factions_downloads_icons(settings: Settings, sample_catalog: Catalog) -> None: settings.ensure_directories() save_catalog(sample_catalog, settings.catalog_path) icon_source = _FakeIconSource( emblems={"Mondstadt": "Mondstadt Emblem Night.png"}, urls={"Mondstadt Emblem Night.png": "https://wiki/mondstadt.png"}, ) result = pipeline.factions( settings, source=_FakeSource(regions={"test_pyro": "Mondstadt"}), icon_source=icon_source, ) assert result.icons is not None assert result.icons.downloaded == ("mondstadt",) assert (settings.faction_icons_dir / "mondstadt.png").is_file() def test_pipeline_factions_can_skip_icons(settings: Settings, sample_catalog: Catalog) -> None: settings.ensure_directories() save_catalog(sample_catalog, settings.catalog_path) result = pipeline.factions( settings, icons=False, source=_FakeSource(regions={"test_pyro": "Mondstadt"}), ) assert result.icons is None assert not settings.faction_icons_dir.exists()