election-game/backend/data/pipeline/tests/test_races2024.py

128 lines
5.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import json
import pytest
from election_data.races2024 import (
OUT_LEGISLATOR,
OUT_PRESIDENT,
district_towns,
legislator_cap,
president_cap,
)
def test_president_cap_matches_published_2020_figure() -> None:
# 2019-07-31 人口 23,592,598 → 中選會公告 2020 總統選舉上限 430,297,000
assert president_cap(23_592_598) == 430_297_000
def test_legislator_cap_formula() -> None:
assert legislator_cap(14_005) == 10_295_000
@pytest.mark.skipif(not (OUT_PRESIDENT / "00000.json").exists(), reason="需要先執行 election-data races2024")
def test_president_totals_match_cec() -> None:
data = json.loads((OUT_PRESIDENT / "00000.json").read_text(encoding="utf-8"))
total = sum(sum(v["votes"].values()) for v in data["byVillage"].values())
assert total == data["cecValid"] == 13_947_506
assert [c["name"] for c in data["candidates"]] == ["柯文哲", "賴清德", "侯友宜"]
assert all(c["finance"] for c in data["candidates"])
@pytest.mark.skipif(not OUT_LEGISLATOR.exists(), reason="需要先執行 election-data races2024")
def test_legislator_districts() -> None:
# calibration.json 是校準結果,不是選區
files = sorted(OUT_LEGISLATOR.glob("[0-9]*-[0-9]*.json"))
assert len(files) == 73
seen: set[str] = set()
for path in files:
data = json.loads(path.read_text(encoding="utf-8"))
villages = set(data["byVillage"])
assert not villages & seen, path.name # 每個里只屬於一個選區
seen |= villages
numbers = {f"#{c['number']}" for c in data["candidates"]}
for v in data["byVillage"].values():
assert set(v["votes"]) <= numbers
def test_district_towns_marks_partial_towns() -> None:
sites = {
"63000110001": "臺北市士林區",
"63000110002": "臺北市士林區",
"63000120001": "臺北市北投區",
}
towns = district_towns({"63000110001", "63000120001"}, sites, "臺北市")
assert towns == [
{"code": "63000110", "name": "士林區", "partial": True},
{"code": "63000120", "name": "北投區", "partial": False},
]
@pytest.mark.skipif(
not (OUT_LEGISLATOR / "63000-01.json").exists(), reason="需要先執行 election-data races2024"
)
def test_taipei_first_district_towns() -> None:
data = json.loads((OUT_LEGISLATOR / "63000-01.json").read_text(encoding="utf-8"))
assert [(t["name"], t["partial"]) for t in data["towns"]] == [("士林區", True), ("北投區", False)]
class _FakeIndex:
def __init__(self, edges: dict[str, list[str]]) -> None:
self._edges = edges
def neighbors(self, code: str) -> list[str]:
return self._edges.get(code, [])
def _shape(code: str):
from types import SimpleNamespace
return SimpleNamespace(code=code, county_code=code[:5])
def test_assign_orphans_prefers_same_town_and_spreads_outward() -> None:
from election_data.races2024 import assign_orphans
district_of = {"63000110001": "A", "63000120001": "B", "63000120002": "B"}
edges = {
# 新里 003 同時鄰接士林(A)與北投(B),同區的鄰居優先
"63000120003": ["63000110001", "63000120001"],
# 新里 004 只鄰接另一個新里,要等 003 先分好
"63000120004": ["63000120003"],
}
shapes = [_shape(c) for c in [*district_of, "63000120003", "63000120004"]]
assert assign_orphans(district_of, shapes, _FakeIndex(edges)) == {
"63000120003": "B",
"63000120004": "B",
}
@pytest.mark.skipif(not OUT_LEGISLATOR.exists(), reason="需要先執行 election-data races2024")
def test_every_pack_village_is_in_a_district() -> None:
by_county: dict[str, set[str]] = {}
for path in OUT_LEGISLATOR.glob("[0-9]*-[0-9]*.json"):
data = json.loads(path.read_text(encoding="utf-8"))
by_county.setdefault(data["countyCode"], set()).update(data["byVillage"])
packs = OUT_LEGISLATOR.parent.parent / "packs"
for county, villages in by_county.items():
pack = packs / f"{county}-before-2024-01-13" / "villages.json"
if not pack.exists():
continue
codes = {v["code"] for v in json.loads(pack.read_text(encoding="utf-8"))["villages"]}
assert codes <= villages, (county, sorted(codes - villages)[:5])
def test_remap_population_matches_renamed_offices_by_village_name() -> None:
from election_data.population import VillagePopulation
from election_data.races2024 import remap_population
def vp(code: str, site: str, village: str, total: int) -> VillagePopulation:
return VillagePopulation(code, site, village, total, (0,) * 101)
old = [
vp("64000051001", "高雄市三民一", "鼎金里", 100), # 2019 年三民區分兩個戶政所
vp("64000010001", "高雄市鹽埕區", "藍橋里", 50),
]
now = [vp("64000050007", "高雄市三民區", "鼎金里", 0), vp("64000010001", "高雄市鹽埕區", "藍橋里", 0)]
assert remap_population(old, now) == {"64000050007": 100, "64000010001": 50}