294 lines
16 KiB
TypeScript
294 lines
16 KiB
TypeScript
import { existsSync } from "node:fs";
|
||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||
import { tmpdir } from "node:os";
|
||
import { join } from "node:path";
|
||
import { SCENARIOS } from "@election2026/content";
|
||
import { DEFAULT_PACKS_ROOT } from "@election2026/pack-loader";
|
||
import { ApiError, PeopleListResponse, PersonRecordResponse, type RecordsFile } from "@election2026/protocol";
|
||
import Fastify, { type FastifyInstance, type FastifyReply } from "fastify";
|
||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||
import type { z } from "zod";
|
||
import { buildApp } from "../src/app.ts";
|
||
import { DEFAULT_RECORDS_FILE, recordAbilities, registerPeople, searchKey } from "../src/people-routes.ts";
|
||
|
||
const fail = (reply: FastifyReply, status: number, error: string, details?: string[]): FastifyReply =>
|
||
reply.code(status).send(details ? { error, details } : { error });
|
||
const parse = <T extends z.ZodType>(schema: T, body: unknown) => {
|
||
const r = schema.safeParse(body);
|
||
return r.success ? ({ ok: true, data: r.data } as const) : ({ ok: false, details: r.error.issues.map((i) => i.message) } as const);
|
||
};
|
||
|
||
const run = (over: Record<string, unknown> = {}) => ({
|
||
year: 2022,
|
||
date: "2022-11-26",
|
||
election: "直轄市議員",
|
||
office: "councilor",
|
||
indigenous: null,
|
||
county: "臺北市",
|
||
countyCode: "63000",
|
||
district: "第3選區",
|
||
number: 1,
|
||
party: "甲黨",
|
||
votes: 12_000,
|
||
share: 0.12,
|
||
elected: true,
|
||
incumbent: false,
|
||
...over,
|
||
});
|
||
|
||
const person = (i: number, over: Record<string, unknown> = {}, runs = [run()]) => ({
|
||
id: `r-${i.toString(16).padStart(10, "0")}`,
|
||
name: `測試人${i}`,
|
||
gender: null,
|
||
birthYear: 1970,
|
||
confidence: "high",
|
||
counties: ["63000"],
|
||
parties: ["甲黨"],
|
||
stats: { runs: runs.length, wins: 1, firstYear: 2022, lastYear: 2022, maxVotes: 12_000 },
|
||
runs,
|
||
scores: [{ key: "fame", value: 3.2, basis: "生涯單次最高 12,000 票" }],
|
||
...over,
|
||
});
|
||
|
||
const FIXTURE = {
|
||
protocolVersion: "1.0.0",
|
||
generatedAt: "2026-10-26",
|
||
note: "分數是依公開選舉紀錄計算的遊戲數值,不代表對個人的評價",
|
||
sources: [{ title: "中央選舉委員會選舉資料庫", url: "https://data.cec.gov.tw/", retrievedAt: "2026-10-25" }],
|
||
scoreDefs: [{ key: "fame", label: "知名度", formula: "取對數", source: "中選會" }],
|
||
elections: [
|
||
{ folder: "a", year: 2022, date: "2022-11-26", election: "直轄市議員", office: "councilor", indigenous: null, candidates: 1, elected: 1, noVotes: 0 },
|
||
{ folder: "b", year: 2018, date: "2018-11-24", election: "直轄市長", office: "mayor", indigenous: null, candidates: 1, elected: 1, noVotes: 0 },
|
||
{ folder: "c", year: 2024, date: "2024-01-13", election: "總統副總統", office: "president", indigenous: null, candidates: 2, elected: 2, noVotes: 0 },
|
||
{ folder: "d", year: 2024, date: "2024-01-13", election: "不分區立法委員", office: "legislator", indigenous: null, candidates: 1, elected: 1, noVotes: 0 },
|
||
],
|
||
people: [
|
||
// 120 位 2022 臺北市議員候選人(測分頁)
|
||
...Array.from({ length: 120 }, (_, i) => person(i + 1)),
|
||
person(500, { name: "伊凡諾幹 Iban Nokan" }, [run({ indigenous: "山地原住民", district: "第8選區" })]),
|
||
// 2018 新北市長、2022 臺北市議員:縣市、選舉、年份要同一次參選都符合
|
||
person(501, { name: "跨縣市", counties: ["63000", "65000"] }, [
|
||
run({ year: 2018, date: "2018-11-24", election: "直轄市長", office: "mayor", county: "新北市", countyCode: "65000", district: null }),
|
||
run(),
|
||
]),
|
||
// 2020 臺北市區域立委、2024 副總統:全國性的選舉沒有縣市
|
||
person(502, { name: "副手", counties: ["63000"] }, [
|
||
run({ year: 2020, date: "2020-01-11", election: "立法委員", office: "legislator", district: "第1選區", votes: 80_000 }),
|
||
run({ year: 2024, date: "2024-01-13", election: "副總統", office: "president", county: "全國", countyCode: null, district: null, votes: 5_000_000, share: 0.4, runningMate: "正手" }),
|
||
]),
|
||
// 2024 不分區立委:沒有個人得票,記名單排名與政黨票
|
||
person(503, { name: "名單", counties: [] }, [
|
||
run({ year: 2024, date: "2024-01-13", election: "不分區立法委員", office: "legislator", county: "全國", countyCode: null, district: null, votes: null, share: null, listRank: 3, partyVotes: 4_000_000, partyShare: 0.3 }),
|
||
]),
|
||
],
|
||
} satisfies Record<string, unknown>;
|
||
|
||
async function appWith(file: string): Promise<FastifyInstance> {
|
||
const app = Fastify();
|
||
registerPeople(app, { fail, parse, file });
|
||
await app.ready();
|
||
return app;
|
||
}
|
||
|
||
describe("政治人物資料庫 API", () => {
|
||
let dir: string;
|
||
let app: FastifyInstance;
|
||
beforeAll(async () => {
|
||
dir = await mkdtemp(join(tmpdir(), "people-"));
|
||
await writeFile(join(dir, "records.json"), JSON.stringify(FIXTURE), "utf-8");
|
||
app = await appWith(join(dir, "records.json"));
|
||
});
|
||
afterAll(async () => {
|
||
await app.close();
|
||
await rm(dir, { recursive: true, force: true });
|
||
});
|
||
|
||
const list = async (qs: string) => {
|
||
const res = await app.inject(`/api/people${qs}`);
|
||
expect(res.statusCode).toBe(200);
|
||
return PeopleListResponse.parse(res.json());
|
||
};
|
||
|
||
it("每頁 50 人,附年份清單", async () => {
|
||
const first = await list("");
|
||
expect(first.total).toBe(124);
|
||
expect(first.people).toHaveLength(50);
|
||
expect(first.years).toEqual([2024, 2022, 2018]);
|
||
expect(first.note).toContain("不代表對個人的評價");
|
||
const last = await list("?page=3");
|
||
expect(last.people).toHaveLength(24);
|
||
expect((await list("?page=9")).people).toHaveLength(0);
|
||
});
|
||
|
||
it("篩選:縣市、選舉種類、年份要同一次參選都符合", async () => {
|
||
expect((await list("?office=mayor")).people.map((p) => p.name)).toEqual(["跨縣市"]);
|
||
expect((await list("?county=65000&office=mayor&year=2018")).total).toBe(1);
|
||
expect((await list("?county=65000&office=councilor")).total).toBe(0);
|
||
expect((await list("?county=63000&year=2022")).total).toBe(122);
|
||
});
|
||
|
||
it("篩選:總統(含副總統)、立委(區域、原住民、不分區);全國性的選舉沒有縣市", async () => {
|
||
expect((await list("?office=president")).people.map((p) => p.name)).toEqual(["副手"]);
|
||
expect((await list("?office=legislator")).people.map((p) => p.name).sort()).toEqual(["副手", "名單"]);
|
||
expect((await list("?office=legislator&year=2024")).people.map((p) => p.name)).toEqual(["名單"]);
|
||
// 選了縣市:只剩那個縣市的區域立委,全國性的副總統、不分區不算
|
||
expect((await list("?county=63000&office=legislator")).people.map((p) => p.name)).toEqual(["副手"]);
|
||
expect((await list("?county=63000&office=president")).total).toBe(0);
|
||
const [vice] = (await list(`?q=${encodeURIComponent("副手")}`)).people;
|
||
expect(vice!.latest).toBe("2024 全國 副總統");
|
||
const [listed] = (await list(`?q=${encodeURIComponent("名單")}`)).people;
|
||
expect(listed!.latest).toBe("2024 全國 不分區立法委員");
|
||
});
|
||
|
||
it("搜尋姓名:去空白、間隔號,不分大小寫", async () => {
|
||
expect((await list(`?q=${encodeURIComponent("iban nokan")}`)).people.map((p) => p.name)).toEqual(["伊凡諾幹 Iban Nokan"]);
|
||
expect((await list(`?q=${encodeURIComponent("測試人12")}`)).total).toBe(2); // 測試人12、測試人120
|
||
expect(searchKey("柔夏.布待 Rosya")).toBe("柔夏布待rosya");
|
||
});
|
||
|
||
it("列表顯示最近一次參選", async () => {
|
||
const [p] = (await list(`?q=${encodeURIComponent("跨縣市")}`)).people;
|
||
expect(p).toMatchObject({ runs: 2, latest: "2022 臺北市第3選區 直轄市議員", party: "甲黨" });
|
||
});
|
||
|
||
it("不合法的查詢回 400", async () => {
|
||
for (const qs of ["?office=king", "?county=abc", "?page=0", "?year=abc"]) {
|
||
const res = await app.inject(`/api/people${qs}`);
|
||
expect(res.statusCode, qs).toBe(400);
|
||
expect(ApiError.safeParse(res.json()).success).toBe(true);
|
||
}
|
||
});
|
||
|
||
it("個人頁:分數附上算法與出處", async () => {
|
||
const res = await app.inject("/api/people/r-0000000001");
|
||
expect(res.statusCode).toBe(200);
|
||
const body = PersonRecordResponse.parse(res.json());
|
||
expect(body.person.scores[0]).toMatchObject({ key: "fame", label: "知名度", formula: "取對數", source: "中選會", value: 3.2 });
|
||
expect(body.sources[0]!.title).toContain("中央選舉委員會");
|
||
});
|
||
|
||
it("找不到的人回 404", async () => {
|
||
expect((await app.inject("/api/people/r-ffffffffff")).statusCode).toBe(404);
|
||
expect((await app.inject("/api/people/not-an-id")).statusCode).toBe(404);
|
||
});
|
||
});
|
||
|
||
describe("資料庫檔案有問題時伺服器照常運作", () => {
|
||
it("檔案不在:空清單", async () => {
|
||
const app = await appWith(join(tmpdir(), "no-such-dir", "records.json"));
|
||
const res = await app.inject("/api/people");
|
||
expect(res.statusCode).toBe(200);
|
||
expect(PeopleListResponse.parse(res.json()).total).toBe(0);
|
||
expect((await app.inject("/api/people/r-0000000001")).statusCode).toBe(404);
|
||
await app.close();
|
||
});
|
||
|
||
it("格式不對:空清單", async () => {
|
||
const dir = await mkdtemp(join(tmpdir(), "people-bad-"));
|
||
await writeFile(join(dir, "a.json"), JSON.stringify({ people: [{ id: 1 }] }), "utf-8");
|
||
await writeFile(join(dir, "b.json"), "{ 壞掉", "utf-8");
|
||
for (const f of ["a.json", "b.json"]) {
|
||
const app = await appWith(join(dir, f));
|
||
expect(PeopleListResponse.parse((await app.inject("/api/people")).json()).total).toBe(0);
|
||
await app.close();
|
||
}
|
||
await rm(dir, { recursive: true, force: true });
|
||
});
|
||
});
|
||
|
||
const scenario = SCENARIOS[0];
|
||
const built = existsSync(join(DEFAULT_PACKS_ROOT, scenario.packId, "manifest.json")) && existsSync(DEFAULT_RECORDS_FILE);
|
||
|
||
describe.skipIf(!built)("實際的 records.json(election-data records 產生)", () => {
|
||
let app: FastifyInstance;
|
||
beforeAll(async () => {
|
||
app = await buildApp({ maxRuns: 5 });
|
||
});
|
||
afterAll(() => app.close());
|
||
|
||
it("2022 年臺北市議員候選人都查得到,個人頁有五項分數", async () => {
|
||
const res = await app.inject("/api/people?county=63000&office=councilor&year=2022");
|
||
const body = PeopleListResponse.parse(res.json());
|
||
expect(body.total).toBeGreaterThan(100);
|
||
expect(body.years).toContain(1994);
|
||
const detail = PersonRecordResponse.parse((await app.inject(`/api/people/${body.people[0]!.id}`)).json());
|
||
expect(detail.person.scores.map((s) => s.key)).toEqual(["fame", "organization", "seniority", "strength", "finance"]);
|
||
expect(detail.person.scores.every((s) => s.formula.length > 0 && s.source.length > 0)).toBe(true);
|
||
});
|
||
|
||
it("總統副總統、立委也收:1996–2024 年每次總統選舉都有正副兩位當選", async () => {
|
||
const body = PeopleListResponse.parse((await app.inject("/api/people?office=president")).json());
|
||
expect(body.total).toBeGreaterThan(30);
|
||
expect(body.years).toEqual(expect.arrayContaining([1995, 1996, 2000, 2004, 2008, 2012, 2016, 2020, 2024]));
|
||
for (const year of [1996, 2000, 2004, 2008, 2012, 2016, 2020, 2024]) {
|
||
const winners = PeopleListResponse.parse((await app.inject(`/api/people?office=president&year=${year}`)).json());
|
||
const ids = winners.people.map((p) => p.id);
|
||
const runs = await Promise.all(ids.map(async (id) => PersonRecordResponse.parse((await app.inject(`/api/people/${id}`)).json()).person.runs));
|
||
const elected = runs.flat().filter((r) => r.year === year && r.office === "president" && r.elected);
|
||
expect(elected.map((r) => r.election).sort(), String(year)).toEqual(["副總統", "總統"]);
|
||
}
|
||
});
|
||
});
|
||
|
||
// 型別檢查:測試資料要符合 RecordsFile
|
||
const _typed: RecordsFile = FIXTURE as unknown as RecordsFile;
|
||
void _typed;
|
||
|
||
describe("玩真實候選人的開局能力(依公開選舉紀錄)", () => {
|
||
const people = FIXTURE.people as unknown as Parameters<typeof recordAbilities>[0];
|
||
|
||
it("只看那場選舉之前的紀錄:當選次數→組織、最高得票→媒體、從政年數→口才;財務、清廉一律 0", () => {
|
||
const veteran = person(900, { name: "老將" }, [
|
||
run({ year: 2010, date: "2010-11-27", votes: 40_000 }),
|
||
run({ year: 2014, date: "2014-11-29", votes: 50_000 }),
|
||
run({ year: 2018, date: "2018-11-24", votes: 60_000 }),
|
||
run({ year: 2022, date: "2022-11-26", votes: 400_000 }),
|
||
]) as unknown as (typeof people)[number];
|
||
const r = recordAbilities([...people, veteran], "老將", "63000", "2022-11-26")!;
|
||
expect(r.abilities).toEqual({ media: 1, organization: 2, eloquence: 1, finance: 0, integrity: 0 });
|
||
expect(r.basis).toContain("2022 年以前");
|
||
// 第一次參選之前沒有紀錄
|
||
expect(recordAbilities([...people, veteran], "老將", "63000", "2010-11-27")).toBeNull();
|
||
});
|
||
|
||
it("同名同縣市有兩個人、或比對信心低:不給(寧可不給也不要給錯人)", () => {
|
||
const twin = person(901, { name: "測試人1" }) as unknown as (typeof people)[number];
|
||
expect(recordAbilities([...people, twin], "測試人1", "63000", "2026-01-01")).toBeNull();
|
||
const low = person(902, { name: "不確定", confidence: "low" }) as unknown as (typeof people)[number];
|
||
expect(recordAbilities([low], "不確定", "63000", "2026-01-01")).toBeNull();
|
||
// 別的縣市的同名者不算;總統選舉不限縣市
|
||
expect(recordAbilities(people, "跨縣市", "66000", "2026-01-01")).toBeNull();
|
||
expect(recordAbilities(people, "跨縣市", "00000", "2026-01-01")).not.toBeNull();
|
||
});
|
||
|
||
it("同名的有好幾位:有這場選舉本身紀錄的那位優先(只用來認人,這一場不算進能力)", () => {
|
||
const rookie = person(910, { name: "同名" }, [run({ year: 2024, date: "2024-01-13", election: "立法委員", office: "legislator", votes: 90_000 })]);
|
||
const veteran = person(911, { name: "同名", birthYear: 1950 }, [run({ year: 2014, date: "2014-11-29" }), run({ year: 2018, date: "2018-11-24" })]);
|
||
const both = [...people, rookie, veteran] as unknown as typeof people;
|
||
// 2024 臺北市的立委選舉:是第一次參選的那位,之前沒有紀錄 → 不給
|
||
expect(recordAbilities(both, "同名", "63000", "2024-01-13")).toBeNull();
|
||
// 2022 臺北市議員:兩位都沒有那一天的紀錄,認不出來 → 不給
|
||
expect(recordAbilities(both, "同名", "63000", "2022-11-26")).toBeNull();
|
||
// 總統選舉:看那一天有總統副總統紀錄的那位
|
||
const vice = person(912, { name: "同名" }, [
|
||
run({ year: 2020, date: "2020-01-11", election: "立法委員", office: "legislator", votes: 80_000 }),
|
||
run({ year: 2024, date: "2024-01-13", election: "副總統", office: "president", county: "全國", countyCode: null, district: null, votes: 5_000_000 }),
|
||
]);
|
||
const r = recordAbilities([...both, vice] as unknown as typeof people, "同名", "00000", "2024-01-13")!;
|
||
expect(r.abilities).toEqual({ media: 1, organization: 1, eloquence: 0, finance: 0, integrity: 0 });
|
||
});
|
||
|
||
it("總統、副總統的全國票數只讓媒體停在 2 級;不分區沒有個人得票,不算進媒體", () => {
|
||
const national = person(920, { name: "中央" }, [
|
||
run({ year: 2012, date: "2012-01-14", election: "不分區立法委員", office: "legislator", county: "全國", countyCode: null, district: null, votes: null, share: null, listRank: 1 }),
|
||
run({ year: 2016, date: "2016-01-16", election: "立法委員", office: "legislator", votes: 20_000 }),
|
||
run({ year: 2020, date: "2020-01-11", election: "副總統", office: "president", county: "全國", countyCode: null, district: null, votes: 8_000_000 }),
|
||
]);
|
||
const all = [...people, national] as unknown as typeof people;
|
||
// 2020 年以前:不分區+區域立委,最高 20,000 票 → 媒體 0;當選 2 次 → 組織 1;2012→2016 四年 → 口才 1
|
||
expect(recordAbilities(all, "中央", "63000", "2020-01-11")!.abilities).toEqual({ media: 0, organization: 1, eloquence: 1, finance: 0, integrity: 0 });
|
||
// 2024 年:2020 副總統 800 萬票 → 媒體 2(上限,和大縣市長一樣)
|
||
expect(recordAbilities(all, "中央", "00000", "2024-01-13")!.abilities.media).toBe(2);
|
||
});
|
||
});
|