election-game/backend/packages/protocol/test/protocol.test.ts

63 lines
1.9 KiB
TypeScript
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 { describe, expect, it } from "vitest";
import { AGE_BANDS, CellsBlock, LEANS, VillageCode, VillageRecord } from "../src/index.ts";
const village = {
code: "68000010001",
name: "示例里",
townCode: "68000010",
townName: "桃園區",
countyCode: "68000",
countyName: "桃園市",
population: {
total: 3000,
adults: 2400,
byAgeBand: { "20-29": 400, "30-39": 500, "40-49": 500, "50-64": 600, "65+": 400 },
indigenousLowland: 10,
indigenousHighland: 5,
},
electors: 2380,
baseTurnout: 0.68,
lean: { a_core: 0.2, a_lean: 0.15, middle: 0.2, b_lean: 0.15, b_core: 0.2, c_lean: 0.1 },
attributes: {
areaKm2: 0.8,
densityPerKm2: 3750,
templeCount: 2,
churchCount: 1,
templesPer1000: 0.67,
hakkaShare: null,
incomeMedian: 650,
incomeMean: 900,
factionStrength: 0.5,
},
flags: [],
};
describe("村里代碼", () => {
it("接受 11 碼數字", () => {
expect(VillageCode.safeParse("68000010001").success).toBe(true);
});
it("拒絕中選會的 4 碼村里段與字母代碼", () => {
expect(VillageCode.safeParse("0001").success).toBe(false);
expect(VillageCode.safeParse("680000100A1").success).toBe(false);
});
});
describe("VillageRecord", () => {
it("接受完整的村里紀錄", () => {
expect(VillageRecord.safeParse(village).success).toBe(true);
});
it("拒絕超出 0–1 的比例", () => {
const bad = { ...village, baseTurnout: 1.2 };
expect(VillageRecord.safeParse(bad).success).toBe(false);
});
});
describe("CellsBlock", () => {
it("每個村里必須剛好 30 格", () => {
const ok = { ages: [...AGE_BANDS], leans: [...LEANS], values: { "68000010001": new Array(30).fill(1) } };
const bad = { ...ok, values: { "68000010001": new Array(29).fill(1) } };
expect(CellsBlock.safeParse(ok).success).toBe(true);
expect(CellsBlock.safeParse(bad).success).toBe(false);
});
});