"""中選會選舉結果的解析(歷屆參選人資料庫用)。""" from __future__ import annotations from collections.abc import Iterator import pytest from election_data.people.cec_results import ElectionSpec, candidate_totals, load_at_large, load_election pytestmark = pytest.mark.unit def _ctks( prv: str, city: str, area: str, town: str, vil: str, station: str, no: str, votes: int ) -> list[str]: return [prv, city, area, town, vil, station, no, str(votes), "0", ""] def test_candidate_totals_district_level_and_verification() -> None: rows = [ _ctks("63", "000", "01", "000", "0000", "0000", "1", 30), _ctks("63", "000", "01", "010", "0000", "0000", "1", 30), # 鄉鎮層級,不採用 _ctks("63", "000", "01", "010", "0001", "0001", "1", 10), _ctks("63", "000", "01", "010", "0002", "0002", "1", 20), ] assert candidate_totals(rows, national=False) == {("63", "000", "01", "1"): 30} bad = [*rows[:-1], _ctks("63", "000", "01", "010", "0002", "0002", "1", 21)] with pytest.raises(ValueError, match="不一致"): candidate_totals(bad, national=False) def test_candidate_totals_national() -> None: rows = [ _ctks("00", "000", "00", "000", "0000", "0000", "1", 15), _ctks("63", "000", "00", "000", "0000", "0000", "1", 15), _ctks("63", "000", "01", "010", "0001", "0001", "1", 5), _ctks("64", "000", "01", "010", "0001", "0002", "1", 10), ] assert candidate_totals(rows, national=True) == {("00", "000", "00", "1"): 15} class FakeArchive: def __init__(self, tables: dict[str, list[list[str]]]) -> None: self.tables = tables def rows(self, folder: str, kind: str) -> Iterator[list[str]]: yield from self.tables[kind] def test_load_election_shares_and_district_labels() -> None: archive = FakeArchive( { "elpaty": [["1", "中國國民黨"], ["16", "民主進步黨"]], "elbase": [["10", "002", "00", "000", "0000", "宜蘭縣"]], "elcand": [ [ "10", "002", "01", "000", "0000", "1", "甲", "1", "1", "0600101", "", "", "大學", "N", "", "", ], [ "10", "002", "01", "000", "0000", "2", "乙", "16", "2", "0700101", "", "", "碩士", "Y", "*", "", ], ], "elctks": [ _ctks("10", "002", "01", "000", "0000", "0000", "1", 40), _ctks("10", "002", "01", "000", "0000", "0000", "2", 60), _ctks("10", "002", "01", "010", "0001", "0001", "1", 40), _ctks("10", "002", "01", "010", "0001", "0001", "2", 60), ], } ) spec = ElectionSpec("x", "2024 立法委員選舉(區域)", "legislator_district", None) a, b = load_election(archive, spec) # type: ignore[arg-type] assert (a.district, a.county, a.votes, a.share, a.elected) == ("宜蘭縣選舉區", "宜蘭縣", 40, 0.4, False) assert (b.party, b.gender, b.birth_date, b.elected) == ("民主進步黨", "F", "1981-01-01", True) def test_load_at_large_from_elrepm() -> None: archive = FakeArchive( { "elpaty": [["1", "中國國民黨"]], "elrepm": [["1", "1", "韓國瑜", "1", "0460617", "66", "新北市", "碩士", "N", "*"]], } ) (r,) = load_at_large(archive) # type: ignore[arg-type] assert (r.name, r.party, r.gender, r.birth_date, r.votes, r.elected) == ( "韓國瑜", "中國國民黨", "M", "1957-06-17", None, True, )