"""整合測試:用已下載的真實資料完整產生桃園市資料包。 需要 data/raw 中的快取(第一次執行 election-data pack 時下載);沒有快取就略過。 """ import json from pathlib import Path import pytest from election_data import cli from election_data.config import RAW_DIR from election_data.pack import build_pack pytestmark = pytest.mark.integration needs_data = pytest.mark.skipif( not (RAW_DIR / "cec" / "votedata.zip").exists() or not (RAW_DIR / "census2020" / "68000").exists(), reason="沒有下載過的原始資料", ) @needs_data def test_taoyuan_pack(tmp_path: Path) -> None: out = build_pack("68000", out_root=tmp_path) manifest = json.loads((out / "manifest.json").read_text(encoding="utf-8")) villages = json.loads((out / "villages.json").read_text(encoding="utf-8"))["villages"] history = json.loads((out / "history.json").read_text(encoding="utf-8"))["history"] assert manifest["counts"]["villages"] == len(villages) > 500 assert all(v["lean"] and v["baseTurnout"] for v in villages) assert [r for r in history["reconciliation"] if r["diff"] != 0] == [] report = (out / "report.md").read_text(encoding="utf-8") assert "與中選會總數核對" in report and "孤兒代碼" in report def test_cli_dispatches_to_build_pack(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: called: list[str] = [] monkeypatch.setattr( cli, "build_pack", lambda county, exclude=(), name=None, older=False: called.append((county, exclude, name)) or tmp_path, ) assert cli.main(["pack", "--county", "68000", "--exclude", "2022-mayor"]) == 0 assert called == [("68000", ("2022-mayor",), None)] def test_cli_before_excludes_later_elections(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: called: list[tuple] = [] monkeypatch.setattr( cli, "build_pack", lambda county, exclude=(), name=None, older=False: called.append((county, exclude, name)) or tmp_path, ) assert cli.main(["pack", "--county", "68000", "--before", "2022-11-26"]) == 0 county, exclude, name = called[0] assert name == "68000-before-2022-11-26" assert set(exclude) == {"2022-mayor", "2022-councilor", "2024-president", "2024-party-list"} def test_cli_older_before_2020_uses_2016_and_2018(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: called: list[tuple] = [] monkeypatch.setattr( cli, "build_pack", lambda county, exclude=(), name=None, older=False: ( called.append((county, exclude, name, older)) or tmp_path ), ) assert cli.main(["pack", "--county", "63000,00000", "--before", "2020-01-11", "--older"]) == 0 assert [c[0] for c in called] == ["63000", "00000"] county, exclude, name, older = called[0] assert name == "63000-before-2020-01-11" and older # 2020 年以後的都排除,2016、2018 年的留著 assert "2020-president" in exclude and "2018-mayor" not in exclude and "2016-president" not in exclude