48 lines
2.5 KiB
TypeScript
48 lines
2.5 KiB
TypeScript
/**
|
||
* 契約測試:Python 管線產出的資料包,必須能被 TypeScript 端的 Zod 定義解析。
|
||
* 沒有產出時略過(CI 先跑管線再跑這個測試)。
|
||
*/
|
||
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
||
import { dirname, join } from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
import { describe, expect, it } from "vitest";
|
||
import { CellsFile, DataPackManifest, HistoryFile, TownsFile, VillagesFile } from "../src/index.ts";
|
||
|
||
const buildDir = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "data", "build");
|
||
const packsDir = join(buildDir, "packs");
|
||
const packs = existsSync(packsDir) ? readdirSync(packsDir) : [];
|
||
const read = (path: string): unknown => JSON.parse(readFileSync(path, "utf-8"));
|
||
|
||
describe.skipIf(packs.length === 0)("已產出的資料包", () => {
|
||
for (const pack of packs) {
|
||
describe(pack, () => {
|
||
const dir = join(packsDir, pack);
|
||
const manifest = DataPackManifest.parse(read(join(dir, "manifest.json")));
|
||
|
||
it("每個檔案都符合協定", () => {
|
||
expect(VillagesFile.safeParse(read(join(dir, manifest.files.villages))).success).toBe(true);
|
||
expect(TownsFile.safeParse(read(join(dir, manifest.files.towns))).success).toBe(true);
|
||
expect(CellsFile.safeParse(read(join(dir, manifest.files.cells))).success).toBe(true);
|
||
expect(HistoryFile.safeParse(read(join(dir, manifest.files.history))).success).toBe(true);
|
||
});
|
||
|
||
it("每個村里都有 30 個選民群,總和等於成年人口", () => {
|
||
const villages = VillagesFile.parse(read(join(dir, manifest.files.villages))).villages;
|
||
const cells = CellsFile.parse(read(join(dir, manifest.files.cells))).cells.values;
|
||
expect(Object.keys(cells).length).toBe(villages.length);
|
||
for (const v of villages) {
|
||
const sum = (cells[v.code] ?? []).reduce((a, b) => a + b, 0);
|
||
expect(Math.abs(sum - v.population.adults)).toBeLessThan(1);
|
||
}
|
||
});
|
||
|
||
it("歷屆得票與中選會總數一致", () => {
|
||
const { reconciliation } = HistoryFile.parse(read(join(dir, manifest.files.history))).history;
|
||
// 2016 年臺南有一個跨村里投開票所(大仁里、大山里)涵蓋的里在 2018 年前就合併了,對不到現在的里(883 票,千分之一以下)
|
||
const tolerance = (r: { electionId: string; cecValid: number }) => (r.electionId.startsWith("2016-") ? r.cecValid * 1e-3 : 0);
|
||
expect(reconciliation.filter((r) => Math.abs(r.diff) > tolerance(r))).toEqual([]);
|
||
});
|
||
});
|
||
}
|
||
});
|