54 cases across three files. - Pure: the highest-tier weight rule, decimal weights tying exactly, multi-select counting one turnout per voter, dead options ignored, and every rung of the tie ladder including the cases where the initiator cannot discriminate. - Service, against the real database: idempotent launch, vote replace and retract, single-answer rejection, role gating, weight resolution at close, initiator tie, superuser tie with a refused non-tied key, the deadline fallback, the result flag, double close, and a vote after close. - Embed: anonymous polls never name voters, public ones do, buttons chunk into rows of five and disable once voting ends, and the hash moves on a vote, a name, and a resolution.
218 lines
6.8 KiB
TypeScript
218 lines
6.8 KiB
TypeScript
import { beforeAll, describe, expect, it } from "vitest";
|
|
|
|
// The bot config validates its environment at import time, the same way
|
|
// `bot-commands.int.spec.ts` handles it.
|
|
process.env.DISCORD_TOKEN ||= "poll-embed-test-token";
|
|
process.env.DISCORD_GUILD_ID ||= "1";
|
|
process.env.APP_URL ||= "https://polaris.test";
|
|
|
|
import type { Poll } from "@/payload-types";
|
|
import type { PollTally } from "@/lib/polls/tally";
|
|
|
|
type PollEmbeds = typeof import("@/bot/services/pollEmbeds");
|
|
let mod: PollEmbeds;
|
|
|
|
beforeAll(async () => {
|
|
mod = await import("@/bot/services/pollEmbeds");
|
|
});
|
|
|
|
const HOUR = 3_600_000;
|
|
|
|
const poll = (over: Partial<Poll> = {}): Poll =>
|
|
({
|
|
id: 42,
|
|
title: "Should the Task Force work with the Vanguard?",
|
|
body: "They want a shared comms channel and a monthly tithe.",
|
|
options: [
|
|
{ key: "accept", label: "Work with the Vanguard", emoji: "🤝", description: null, id: "a" },
|
|
{ key: "decline", label: "Stay independent", emoji: null, description: null, id: "b" },
|
|
],
|
|
status: "open",
|
|
closesAt: new Date(Date.now() + 6 * HOUR).toISOString(),
|
|
multiSelect: false,
|
|
anonymity: "public",
|
|
defaultWeight: 1,
|
|
weightTiers: [],
|
|
tieGraceHours: 24,
|
|
sourceKey: "1:node",
|
|
openedAt: new Date().toISOString(),
|
|
initiatedBy: 1,
|
|
eligibleRoles: [],
|
|
updatedAt: "",
|
|
createdAt: "",
|
|
...over,
|
|
}) as unknown as Poll;
|
|
|
|
const tally = (over: Partial<PollTally> = {}): PollTally => ({
|
|
counts: {
|
|
accept: { raw: 2, weighted: 3 },
|
|
decline: { raw: 1, weighted: 1.5 },
|
|
},
|
|
totalVotes: 3,
|
|
totalWeight: 4.5,
|
|
topScore: 3,
|
|
topKeys: ["accept"],
|
|
...over,
|
|
});
|
|
|
|
const render = (input: Partial<Parameters<PollEmbeds["renderPollEmbed"]>[0]> = {}) =>
|
|
mod
|
|
.renderPollEmbed({
|
|
poll: poll(),
|
|
tally: tally(),
|
|
votersByOption: new Map(),
|
|
...input,
|
|
})
|
|
.toJSON();
|
|
|
|
describe("Poll embed", () => {
|
|
it("names the question, both answers and the weighted tally", () => {
|
|
const embed = render();
|
|
|
|
expect(embed.title).toBe("Should the Task Force work with the Vanguard?");
|
|
// The host comes from APP_URL, so assert the path the link must carry.
|
|
expect(embed.url).toMatch(/\/polls\/42$/);
|
|
const fields = embed.fields ?? [];
|
|
expect(fields[0].name).toContain("Work with the Vanguard");
|
|
// Weighted differs from raw, so both are shown.
|
|
expect(fields[0].name).toContain("2");
|
|
expect(fields[0].name).toContain("3");
|
|
expect(fields[1].name).toContain("1.5");
|
|
expect(embed.description).toContain("3 voters");
|
|
expect(embed.description).toContain("One answer");
|
|
expect(embed.description).toContain("Public");
|
|
});
|
|
|
|
it("shows voter names on a public poll", () => {
|
|
const embed = render({
|
|
votersByOption: new Map([["accept", ["Alpha", "Bravo"]]]),
|
|
});
|
|
expect(embed.fields?.[0].value).toContain("Alpha, Bravo");
|
|
});
|
|
|
|
it("never shows voter names on an anonymous poll", () => {
|
|
const embed = render({
|
|
poll: poll({ anonymity: "anonymous" }),
|
|
votersByOption: new Map([["accept", ["Alpha", "Bravo"]]]),
|
|
});
|
|
|
|
const body = JSON.stringify(embed);
|
|
expect(body).not.toContain("Alpha");
|
|
expect(body).not.toContain("Bravo");
|
|
expect(embed.description).toContain("Anonymous");
|
|
// Counts still render.
|
|
expect(embed.fields?.[0].name).toContain("Work with the Vanguard");
|
|
});
|
|
|
|
it("announces the winner once closed", () => {
|
|
const embed = render({
|
|
poll: poll({
|
|
status: "closed",
|
|
winnerKey: "decline",
|
|
resolutionMethod: "initiator",
|
|
closesAt: new Date(Date.now() - HOUR).toISOString(),
|
|
}),
|
|
});
|
|
|
|
expect(embed.description).toContain("Closed");
|
|
expect(embed.description).toContain("Stay independent");
|
|
});
|
|
|
|
it("reports no decision when a closed poll never resolved", () => {
|
|
const embed = render({
|
|
poll: poll({
|
|
status: "closed",
|
|
winnerKey: null,
|
|
resolutionMethod: "no_votes",
|
|
closesAt: new Date(Date.now() - HOUR).toISOString(),
|
|
}),
|
|
});
|
|
expect(embed.description).toContain("No decision");
|
|
});
|
|
|
|
it("marks a pending tie and its deadline", () => {
|
|
const embed = render({
|
|
poll: poll({
|
|
status: "pending_decision",
|
|
closesAt: new Date(Date.now() - HOUR).toISOString(),
|
|
decisionDeadline: new Date(Date.now() + HOUR).toISOString(),
|
|
}),
|
|
});
|
|
|
|
expect(embed.description).toContain("Tied");
|
|
expect(embed.description).toContain("superuser");
|
|
expect(embed.description).toContain("random tied option");
|
|
});
|
|
});
|
|
|
|
describe("Poll buttons", () => {
|
|
it("one neutral button per option, keyed by poll and option", () => {
|
|
const rows = mod.buildPollRows(poll()).map((row) => row.toJSON());
|
|
|
|
expect(rows).toHaveLength(1);
|
|
const buttons = rows[0].components;
|
|
expect(buttons).toHaveLength(2);
|
|
expect(buttons[0]).toMatchObject({
|
|
custom_id: "ptf-poll:42:accept",
|
|
style: 2,
|
|
disabled: false,
|
|
label: "🤝 Work with the Vanguard",
|
|
});
|
|
expect(buttons[1]).toMatchObject({ custom_id: "ptf-poll:42:decline", style: 2 });
|
|
});
|
|
|
|
it("chunks into rows of five", () => {
|
|
const many = Array.from({ length: 7 }, (_, index) => ({
|
|
key: `o${index}`,
|
|
label: `Option ${index}`,
|
|
emoji: null,
|
|
description: null,
|
|
id: `id${index}`,
|
|
}));
|
|
const rows = mod.buildPollRows(poll({ options: many })).map((row) => row.toJSON());
|
|
|
|
expect(rows.map((row) => row.components.length)).toEqual([5, 2]);
|
|
});
|
|
|
|
it("disables every button once voting is over", () => {
|
|
const closed = mod
|
|
.buildPollRows(poll({ closesAt: new Date(Date.now() - HOUR).toISOString() }))
|
|
.map((row) => row.toJSON());
|
|
expect(closed[0].components.every((button) => button.disabled === true)).toBe(true);
|
|
|
|
const pending = mod
|
|
.buildPollRows(poll({ status: "pending_decision" }))
|
|
.map((row) => row.toJSON());
|
|
expect(pending[0].components.every((button) => button.disabled === true)).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe("Poll hash", () => {
|
|
const base = {
|
|
poll: poll(),
|
|
tally: tally(),
|
|
votersByOption: new Map<string, string[]>(),
|
|
};
|
|
|
|
it("is stable for identical content", () => {
|
|
expect(mod.pollHash(base)).toBe(mod.pollHash({ ...base }));
|
|
});
|
|
|
|
it("changes when a vote lands", () => {
|
|
const voted = {
|
|
...base,
|
|
tally: tally({ counts: { accept: { raw: 3, weighted: 4 }, decline: { raw: 1, weighted: 1.5 } } }),
|
|
};
|
|
expect(mod.pollHash(voted)).not.toBe(mod.pollHash(base));
|
|
});
|
|
|
|
it("changes when a public voter's name appears", () => {
|
|
const named = { ...base, votersByOption: new Map([["accept", ["Alpha"]]]) };
|
|
expect(mod.pollHash(named)).not.toBe(mod.pollHash(base));
|
|
});
|
|
|
|
it("changes when the poll resolves", () => {
|
|
const closed = { ...base, poll: poll({ status: "closed", winnerKey: "accept" }) };
|
|
expect(mod.pollHash(closed)).not.toBe(mod.pollHash(base));
|
|
});
|
|
});
|