test(polls): cover tallying, the poll service and the Discord embed
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.
This commit is contained in:
parent
d9d4ef1c08
commit
06dbc88a2e
3 changed files with 1017 additions and 0 deletions
218
tests/int/polls-embed.int.spec.ts
Normal file
218
tests/int/polls-embed.int.spec.ts
Normal file
|
|
@ -0,0 +1,218 @@
|
||||||
|
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));
|
||||||
|
});
|
||||||
|
});
|
||||||
504
tests/int/polls-service.int.spec.ts
Normal file
504
tests/int/polls-service.int.spec.ts
Normal file
|
|
@ -0,0 +1,504 @@
|
||||||
|
import { getTestPayload } from "../helpers/get-test-payload";
|
||||||
|
import type { Payload } from "payload";
|
||||||
|
|
||||||
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import type { Poll, Role, User } from "@/payload-types";
|
||||||
|
import {
|
||||||
|
advancePoll,
|
||||||
|
castPollVote,
|
||||||
|
closePoll,
|
||||||
|
launchDialoguePoll,
|
||||||
|
readPollOutcome,
|
||||||
|
resolveDeadlineTie,
|
||||||
|
resolveTie,
|
||||||
|
} from "@/lib/polls/service";
|
||||||
|
import type { NpcDialoguePollConfig } from "@/lib/npc-dialogue/dialogue";
|
||||||
|
|
||||||
|
let payload: Payload;
|
||||||
|
|
||||||
|
const RUN = `poll-${Date.now().toString(36)}`;
|
||||||
|
const TIMEOUT = 30_000;
|
||||||
|
|
||||||
|
let npcId: number;
|
||||||
|
let dialogueId: number;
|
||||||
|
const roleIds: number[] = [];
|
||||||
|
const userIds: number[] = [];
|
||||||
|
|
||||||
|
/** A poll config with the two answers most tests use. */
|
||||||
|
const config = (overrides: Partial<NpcDialoguePollConfig> = {}): NpcDialoguePollConfig => ({
|
||||||
|
title: `${RUN} question`,
|
||||||
|
options: [{ label: "Work with them" }, { label: "Stay independent" }],
|
||||||
|
durationHours: 24,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
const launch = async (
|
||||||
|
nodeId: string,
|
||||||
|
initiatorId: number,
|
||||||
|
overrides: Partial<NpcDialoguePollConfig> = {},
|
||||||
|
): Promise<Poll> => {
|
||||||
|
const { poll } = await launchDialoguePoll(payload, {
|
||||||
|
dialogueId,
|
||||||
|
nodeId,
|
||||||
|
initiatorId,
|
||||||
|
config: config(overrides),
|
||||||
|
});
|
||||||
|
return poll;
|
||||||
|
};
|
||||||
|
|
||||||
|
const reload = async (id: number): Promise<Poll> =>
|
||||||
|
(await payload.findByID({
|
||||||
|
collection: "polls",
|
||||||
|
id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
})) as Poll;
|
||||||
|
|
||||||
|
describe("Poll service", () => {
|
||||||
|
beforeAll(async () => {
|
||||||
|
payload = await getTestPayload();
|
||||||
|
|
||||||
|
const npc = await payload.create({
|
||||||
|
collection: "game-npcs",
|
||||||
|
data: { name: `${RUN}_npc`, canMessage: true },
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
npcId = npc.id;
|
||||||
|
|
||||||
|
const dialogue = await payload.create({
|
||||||
|
collection: "npc-dialogues",
|
||||||
|
data: { name: `${RUN}_dialogue`, npc: npcId, flowData: { nodes: [], edges: [] } },
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
dialogueId = dialogue.id;
|
||||||
|
|
||||||
|
const logiRole = (await payload.create({
|
||||||
|
collection: "roles",
|
||||||
|
data: { name: `${RUN}-logistics`, slug: `${RUN}-logistics` },
|
||||||
|
overrideAccess: true,
|
||||||
|
depth: 0,
|
||||||
|
})) as unknown as Role;
|
||||||
|
roleIds.push(logiRole.id);
|
||||||
|
|
||||||
|
const makeUser = async (label: string, roleId?: number): Promise<number> => {
|
||||||
|
const user = (await payload.create({
|
||||||
|
collection: "users",
|
||||||
|
data: {
|
||||||
|
username: `${RUN}-${label}`,
|
||||||
|
discordUsername: `${RUN}-${label}`,
|
||||||
|
displayName: label.toUpperCase(),
|
||||||
|
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
||||||
|
password: "Test123",
|
||||||
|
...(roleId ? { roleDocs: [roleId] } : {}),
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
depth: 0,
|
||||||
|
})) as unknown as User;
|
||||||
|
userIds.push(user.id);
|
||||||
|
return user.id;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Fixed ids the tests below index by position.
|
||||||
|
await makeUser("initiator");
|
||||||
|
await makeUser("voter");
|
||||||
|
await makeUser("logistics", logiRole.id);
|
||||||
|
await makeUser("superuser");
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
if (!payload) return;
|
||||||
|
const cleanup = async (collection: "polls" | "poll-votes" | "player-flags") => {
|
||||||
|
await payload
|
||||||
|
.delete({
|
||||||
|
collection,
|
||||||
|
where: collection === "polls" ? { sourceKey: { contains: RUN } } : {},
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
.catch(() => undefined);
|
||||||
|
};
|
||||||
|
await cleanup("poll-votes");
|
||||||
|
await cleanup("polls");
|
||||||
|
await payload
|
||||||
|
.delete({ collection: "player-flags", where: { key: { contains: RUN } }, overrideAccess: true })
|
||||||
|
.catch(() => undefined);
|
||||||
|
await payload
|
||||||
|
.delete({ collection: "npc-dialogues", where: { id: { equals: dialogueId } }, overrideAccess: true })
|
||||||
|
.catch(() => undefined);
|
||||||
|
await payload
|
||||||
|
.delete({ collection: "game-npcs", where: { id: { equals: npcId } }, overrideAccess: true })
|
||||||
|
.catch(() => undefined);
|
||||||
|
await payload
|
||||||
|
.delete({ collection: "users", where: { id: { in: userIds } }, overrideAccess: true })
|
||||||
|
.catch(() => undefined);
|
||||||
|
await payload
|
||||||
|
.delete({ collection: "roles", where: { id: { in: roleIds } }, overrideAccess: true })
|
||||||
|
.catch(() => undefined);
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
describe("launch", () => {
|
||||||
|
it("opens one poll per node and joins it on a later trigger", async () => {
|
||||||
|
const nodeId = `${RUN}-launch`;
|
||||||
|
const first = await launch(nodeId, userIds[0]);
|
||||||
|
expect(first.status).toBe("open");
|
||||||
|
expect(first.options.map((o) => o.key)).toEqual(["work-with-them", "stay-independent"]);
|
||||||
|
expect(first.sourceKey).toBe(`${dialogueId}:${nodeId}`);
|
||||||
|
expect(first.initiatedBy).toBe(userIds[0]);
|
||||||
|
|
||||||
|
const second = await launchDialoguePoll(payload, {
|
||||||
|
dialogueId,
|
||||||
|
nodeId,
|
||||||
|
initiatorId: userIds[1],
|
||||||
|
config: config({ title: "a different question" }),
|
||||||
|
});
|
||||||
|
expect(second.created).toBe(false);
|
||||||
|
expect(second.poll.id).toBe(first.id);
|
||||||
|
// The author's later edit did not rewrite the poll people voted in.
|
||||||
|
expect(second.poll.title).toBe(first.title);
|
||||||
|
expect(second.poll.initiatedBy).toBe(userIds[0]);
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("derives distinct keys for two options that read the same", async () => {
|
||||||
|
const poll = await launch(`${RUN}-dupes`, userIds[0], {
|
||||||
|
options: [{ label: "Yes" }, { label: "Yes" }],
|
||||||
|
});
|
||||||
|
expect(poll.options.map((o) => o.key)).toEqual(["yes", "yes-2"]);
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("refuses a poll with fewer than two labeled options", async () => {
|
||||||
|
await expect(
|
||||||
|
launchDialoguePoll(payload, {
|
||||||
|
dialogueId,
|
||||||
|
nodeId: `${RUN}-invalid`,
|
||||||
|
initiatorId: userIds[0],
|
||||||
|
config: config({ options: [{ label: "Only one" }, { label: " " }] }),
|
||||||
|
}),
|
||||||
|
).rejects.toThrow(/at least two options/);
|
||||||
|
}, TIMEOUT);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("voting", () => {
|
||||||
|
it("records, replaces, and retracts a ballot", async () => {
|
||||||
|
const poll = await launch(`${RUN}-vote`, userIds[0]);
|
||||||
|
|
||||||
|
const first = await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[1],
|
||||||
|
answers: ["work-with-them"],
|
||||||
|
});
|
||||||
|
expect(first.ok).toBe(true);
|
||||||
|
if (!first.ok) return;
|
||||||
|
expect(first.tally.counts["work-with-them"]).toEqual({ raw: 1, weighted: 1 });
|
||||||
|
|
||||||
|
const changed = await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[1],
|
||||||
|
answers: ["stay-independent"],
|
||||||
|
});
|
||||||
|
expect(changed.ok).toBe(true);
|
||||||
|
if (!changed.ok) return;
|
||||||
|
expect(changed.tally.counts["work-with-them"].raw).toBe(0);
|
||||||
|
expect(changed.tally.counts["stay-independent"].raw).toBe(1);
|
||||||
|
expect(changed.tally.totalVotes).toBe(1);
|
||||||
|
|
||||||
|
const retracted = await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[1],
|
||||||
|
answers: [],
|
||||||
|
});
|
||||||
|
expect(retracted.ok).toBe(true);
|
||||||
|
if (!retracted.ok) return;
|
||||||
|
expect(retracted.cleared).toBe(true);
|
||||||
|
expect(retracted.tally.totalVotes).toBe(0);
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("rejects a second answer on a single-answer poll", async () => {
|
||||||
|
const poll = await launch(`${RUN}-single`, userIds[0]);
|
||||||
|
const result = await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[1],
|
||||||
|
answers: ["work-with-them", "stay-independent"],
|
||||||
|
});
|
||||||
|
expect(result).toEqual({ ok: false, reason: "too-many" });
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("accepts several answers when multi-select is on", async () => {
|
||||||
|
const poll = await launch(`${RUN}-multi`, userIds[0], { multiSelect: true });
|
||||||
|
const result = await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[1],
|
||||||
|
answers: ["work-with-them", "stay-independent"],
|
||||||
|
});
|
||||||
|
expect(result.ok).toBe(true);
|
||||||
|
if (!result.ok) return;
|
||||||
|
expect(result.tally.counts["work-with-them"].raw).toBe(1);
|
||||||
|
expect(result.tally.counts["stay-independent"].raw).toBe(1);
|
||||||
|
expect(result.tally.totalVotes).toBe(1);
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("rejects an answer the poll does not carry", async () => {
|
||||||
|
const poll = await launch(`${RUN}-unknown`, userIds[0]);
|
||||||
|
const result = await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[1],
|
||||||
|
answers: ["not-an-option"],
|
||||||
|
});
|
||||||
|
expect(result).toEqual({ ok: false, reason: "invalid-answer" });
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("refuses a voter outside the eligible roles", async () => {
|
||||||
|
const poll = await launch(`${RUN}-gated`, userIds[0], { eligibleRoleIds: [roleIds[0]] });
|
||||||
|
|
||||||
|
const outsider = await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[1],
|
||||||
|
answers: ["work-with-them"],
|
||||||
|
});
|
||||||
|
expect(outsider).toEqual({ ok: false, reason: "ineligible" });
|
||||||
|
|
||||||
|
const member = await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[2],
|
||||||
|
answers: ["work-with-them"],
|
||||||
|
});
|
||||||
|
expect(member.ok).toBe(true);
|
||||||
|
}, TIMEOUT);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("close and resolve", () => {
|
||||||
|
it("weighs a tiered vote and closes on the top score", async () => {
|
||||||
|
const poll = await launch(`${RUN}-weighted`, userIds[0], {
|
||||||
|
weightTiers: [{ label: "Logistics", roleIds: [roleIds[0]], multiplier: 1.5 }],
|
||||||
|
});
|
||||||
|
|
||||||
|
await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[1],
|
||||||
|
answers: ["work-with-them"],
|
||||||
|
});
|
||||||
|
await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[2],
|
||||||
|
answers: ["stay-independent"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const closed = await closePoll(payload, { pollId: poll.id });
|
||||||
|
expect(closed.status).toBe("closed");
|
||||||
|
expect(closed.winnerKey).toBe("stay-independent");
|
||||||
|
expect(closed.resolutionMethod).toBe("votes");
|
||||||
|
|
||||||
|
const outcome = readPollOutcome(closed);
|
||||||
|
expect(outcome?.counts["work-with-them"]).toEqual({ raw: 1, weighted: 1 });
|
||||||
|
expect(outcome?.counts["stay-independent"]).toEqual({ raw: 1, weighted: 1.5 });
|
||||||
|
expect(outcome?.totalWeight).toBe(2.5);
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("gives a tie to the initiator's vote", async () => {
|
||||||
|
const poll = await launch(`${RUN}-tie-initiator`, userIds[0]);
|
||||||
|
await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[1],
|
||||||
|
answers: ["work-with-them"],
|
||||||
|
});
|
||||||
|
await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[0],
|
||||||
|
answers: ["stay-independent"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const closed = await closePoll(payload, { pollId: poll.id });
|
||||||
|
expect(closed.status).toBe("closed");
|
||||||
|
expect(closed.winnerKey).toBe("stay-independent");
|
||||||
|
expect(closed.resolutionMethod).toBe("initiator");
|
||||||
|
expect(closed.decidedBy).toBe(userIds[0]);
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("escalates a tie the initiator cannot break, then takes a superuser decision", async () => {
|
||||||
|
const poll = await launch(`${RUN}-tie-superuser`, userIds[0], { multiSelect: true });
|
||||||
|
// The initiator picks both tied options, so their ballot cannot discriminate.
|
||||||
|
await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[0],
|
||||||
|
answers: ["work-with-them", "stay-independent"],
|
||||||
|
});
|
||||||
|
await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[1],
|
||||||
|
answers: ["work-with-them", "stay-independent"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const pending = await closePoll(payload, { pollId: poll.id });
|
||||||
|
expect(pending.status).toBe("pending_decision");
|
||||||
|
expect(pending.winnerKey).toBeNull();
|
||||||
|
expect(pending.decisionDeadline).toBeTruthy();
|
||||||
|
expect(readPollOutcome(pending)?.topKeys).toEqual(["work-with-them", "stay-independent"]);
|
||||||
|
|
||||||
|
// A key outside the tie is refused.
|
||||||
|
await expect(
|
||||||
|
resolveTie(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
winnerKey: "not-tied",
|
||||||
|
decidedBy: userIds[3],
|
||||||
|
}),
|
||||||
|
).rejects.toThrow(/not one of the tied options/);
|
||||||
|
|
||||||
|
const decided = await resolveTie(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
winnerKey: "stay-independent",
|
||||||
|
decidedBy: userIds[3],
|
||||||
|
});
|
||||||
|
expect(decided.status).toBe("closed");
|
||||||
|
expect(decided.winnerKey).toBe("stay-independent");
|
||||||
|
expect(decided.resolutionMethod).toBe("superuser");
|
||||||
|
expect(decided.decidedBy).toBe(userIds[3]);
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("picks a random tied option once the grace period expires", async () => {
|
||||||
|
const poll = await launch(`${RUN}-tie-deadline`, userIds[0], { tieGraceHours: 1 });
|
||||||
|
await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[1],
|
||||||
|
answers: ["work-with-them"],
|
||||||
|
});
|
||||||
|
await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[2],
|
||||||
|
answers: ["stay-independent"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const closedAt = Date.now();
|
||||||
|
const pending = await closePoll(payload, { pollId: poll.id, now: closedAt });
|
||||||
|
expect(pending.status).toBe("pending_decision");
|
||||||
|
|
||||||
|
// Still inside the grace window: nothing happens.
|
||||||
|
const early = await resolveDeadlineTie(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
now: closedAt + 30 * 60_000,
|
||||||
|
});
|
||||||
|
expect(early.status).toBe("pending_decision");
|
||||||
|
|
||||||
|
const late = await resolveDeadlineTie(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
now: closedAt + 2 * 3_600_000,
|
||||||
|
rng: () => 0,
|
||||||
|
});
|
||||||
|
expect(late.status).toBe("closed");
|
||||||
|
expect(late.resolutionMethod).toBe("random");
|
||||||
|
expect(late.winnerKey).toBe("work-with-them");
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("closes a poll nobody voted in, without a winner", async () => {
|
||||||
|
const poll = await launch(`${RUN}-empty`, userIds[0]);
|
||||||
|
const closed = await closePoll(payload, { pollId: poll.id });
|
||||||
|
expect(closed.status).toBe("closed");
|
||||||
|
expect(closed.winnerKey).toBeNull();
|
||||||
|
expect(closed.resolutionMethod).toBe("no_votes");
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("writes the result flag with the winning option's key", async () => {
|
||||||
|
const flagKey = `${RUN}_alignment`;
|
||||||
|
const poll = await launch(`${RUN}-flag`, userIds[0], { resultFlag: flagKey });
|
||||||
|
await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[1],
|
||||||
|
answers: ["work-with-them"],
|
||||||
|
});
|
||||||
|
|
||||||
|
await closePoll(payload, { pollId: poll.id });
|
||||||
|
|
||||||
|
const flags = await payload.find({
|
||||||
|
collection: "player-flags",
|
||||||
|
where: { key: { equals: flagKey } },
|
||||||
|
limit: 1,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
expect(flags.docs).toHaveLength(1);
|
||||||
|
expect(flags.docs[0].user).toBeNull();
|
||||||
|
expect(flags.docs[0].flagType).toBe("text");
|
||||||
|
expect(flags.docs[0].textValue).toBe("work-with-them");
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("does not write the flag when nobody voted", async () => {
|
||||||
|
const flagKey = `${RUN}_empty_flag`;
|
||||||
|
const poll = await launch(`${RUN}-flag-empty`, userIds[0], { resultFlag: flagKey });
|
||||||
|
await closePoll(payload, { pollId: poll.id });
|
||||||
|
|
||||||
|
const flags = await payload.find({
|
||||||
|
collection: "player-flags",
|
||||||
|
where: { key: { equals: flagKey } },
|
||||||
|
limit: 1,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
expect(flags.docs).toHaveLength(0);
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("is idempotent: a second close leaves the first resolution alone", async () => {
|
||||||
|
const poll = await launch(`${RUN}-idempotent`, userIds[0]);
|
||||||
|
await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[1],
|
||||||
|
answers: ["work-with-them"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const first = await closePoll(payload, { pollId: poll.id });
|
||||||
|
expect(first.winnerKey).toBe("work-with-them");
|
||||||
|
|
||||||
|
// The loser changes their mind after the close; the result must not move.
|
||||||
|
await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[2],
|
||||||
|
answers: ["stay-independent"],
|
||||||
|
});
|
||||||
|
const second = await closePoll(payload, { pollId: poll.id });
|
||||||
|
expect(second.winnerKey).toBe("work-with-them");
|
||||||
|
expect(second.resolvedAt).toBe(first.resolvedAt);
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("refuses a vote after the poll closed", async () => {
|
||||||
|
const poll = await launch(`${RUN}-closed-vote`, userIds[0]);
|
||||||
|
await closePoll(payload, { pollId: poll.id });
|
||||||
|
|
||||||
|
const result = await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[1],
|
||||||
|
answers: ["work-with-them"],
|
||||||
|
});
|
||||||
|
expect(result).toEqual({ ok: false, reason: "closed" });
|
||||||
|
}, TIMEOUT);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("advancePoll", () => {
|
||||||
|
it("closes a poll whose time ran out", async () => {
|
||||||
|
const poll = await launch(`${RUN}-due`, userIds[0], { durationHours: 0.25 });
|
||||||
|
await castPollVote(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
userId: userIds[1],
|
||||||
|
answers: ["work-with-them"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const before = await advancePoll(payload, { pollId: poll.id });
|
||||||
|
expect(before.status).toBe("open");
|
||||||
|
|
||||||
|
const after = await advancePoll(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
now: Date.now() + 30 * 60_000,
|
||||||
|
});
|
||||||
|
expect(after.status).toBe("closed");
|
||||||
|
expect(after.winnerKey).toBe("work-with-them");
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
it("leaves a settled poll untouched", async () => {
|
||||||
|
const poll = await launch(`${RUN}-settled`, userIds[0]);
|
||||||
|
await closePoll(payload, { pollId: poll.id });
|
||||||
|
|
||||||
|
const after = await advancePoll(payload, {
|
||||||
|
pollId: poll.id,
|
||||||
|
now: Date.now() + 365 * 24 * 3_600_000,
|
||||||
|
});
|
||||||
|
expect(after.status).toBe("closed");
|
||||||
|
expect((await reload(poll.id)).resolvedAt).toBe(after.resolvedAt);
|
||||||
|
}, TIMEOUT);
|
||||||
|
});
|
||||||
|
});
|
||||||
295
tests/int/polls-tally.int.spec.ts
Normal file
295
tests/int/polls-tally.int.spec.ts
Normal file
|
|
@ -0,0 +1,295 @@
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import {
|
||||||
|
breakTieWithInitiator,
|
||||||
|
buildPollWeights,
|
||||||
|
pickRandomTiedOption,
|
||||||
|
resolvePollTally,
|
||||||
|
resolvePollWeight,
|
||||||
|
tallyPoll,
|
||||||
|
type PollOption,
|
||||||
|
type PollWeightTier,
|
||||||
|
} from "@/lib/polls/tally";
|
||||||
|
|
||||||
|
const OPTIONS: PollOption[] = [
|
||||||
|
{ key: "accept", label: "Work with the faction" },
|
||||||
|
{ key: "decline", label: "Stay independent" },
|
||||||
|
{ key: "defer", label: "Defer the decision" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const tiers: PollWeightTier[] = [
|
||||||
|
{ label: "Logistics", roleIds: [4], multiplier: 1.5 },
|
||||||
|
{ label: "Command", roleIds: [1, 2], multiplier: 2 },
|
||||||
|
];
|
||||||
|
|
||||||
|
const tallyOf = (
|
||||||
|
votes: { userId: number; answers: string[] }[],
|
||||||
|
weights: Map<number, number> = new Map(),
|
||||||
|
) => tallyPoll({ options: OPTIONS, votes, weights });
|
||||||
|
|
||||||
|
describe("resolvePollWeight", () => {
|
||||||
|
it("falls back to the default when no tier matches", () => {
|
||||||
|
expect(resolvePollWeight({ roleIds: [9], tiers })).toEqual({ multiplier: 1, label: null });
|
||||||
|
expect(
|
||||||
|
resolvePollWeight({ roleIds: [], tiers, defaultWeight: 1.25 }),
|
||||||
|
).toEqual({ multiplier: 1.25, label: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses the highest matching tier instead of stacking them", () => {
|
||||||
|
// Holds Logistics and Command: 2 wins, 1.5 + 2 = 3.5 would not.
|
||||||
|
expect(resolvePollWeight({ roleIds: [4, 2], tiers })).toEqual({
|
||||||
|
multiplier: 2,
|
||||||
|
label: "Command",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the earlier tier when two matching multipliers are equal", () => {
|
||||||
|
const flat: PollWeightTier[] = [
|
||||||
|
{ label: "First", roleIds: [7], multiplier: 1.5 },
|
||||||
|
{ label: "Second", roleIds: [8], multiplier: 1.5 },
|
||||||
|
];
|
||||||
|
expect(resolvePollWeight({ roleIds: [8, 7], tiers: flat })).toEqual({
|
||||||
|
multiplier: 1.5,
|
||||||
|
label: "First",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clamps a non-positive multiplier to 1 rather than muting the vote", () => {
|
||||||
|
const broken: PollWeightTier[] = [{ label: "Broken", roleIds: [4], multiplier: 0 }];
|
||||||
|
expect(resolvePollWeight({ roleIds: [4], tiers: broken })).toEqual({
|
||||||
|
multiplier: 1,
|
||||||
|
label: "Broken",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("buildPollWeights", () => {
|
||||||
|
it("weights each voter once, from the roles they hold now", () => {
|
||||||
|
const weights = buildPollWeights({
|
||||||
|
votes: [
|
||||||
|
{ userId: 1, answers: ["accept"] },
|
||||||
|
{ userId: 2, answers: ["decline"] },
|
||||||
|
{ userId: 3, answers: ["defer"] },
|
||||||
|
],
|
||||||
|
roleIdsByUser: new Map([
|
||||||
|
[1, [4]],
|
||||||
|
[2, [1]],
|
||||||
|
[3, [99]],
|
||||||
|
]),
|
||||||
|
tiers,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect([...weights.entries()].sort()).toEqual([
|
||||||
|
[1, 1.5],
|
||||||
|
[2, 2],
|
||||||
|
[3, 1],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("gives an unlisted voter the default weight", () => {
|
||||||
|
const weights = buildPollWeights({
|
||||||
|
votes: [{ userId: 5, answers: ["accept"] }],
|
||||||
|
roleIdsByUser: new Map(),
|
||||||
|
tiers,
|
||||||
|
defaultWeight: 1,
|
||||||
|
});
|
||||||
|
expect(weights.get(5)).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("tallyPoll", () => {
|
||||||
|
it("counts raw and weighted scores separately", () => {
|
||||||
|
const tally = tallyOf(
|
||||||
|
[
|
||||||
|
{ userId: 1, answers: ["accept"] },
|
||||||
|
{ userId: 2, answers: ["accept"] },
|
||||||
|
{ userId: 3, answers: ["decline"] },
|
||||||
|
],
|
||||||
|
new Map([
|
||||||
|
[1, 2],
|
||||||
|
[2, 1],
|
||||||
|
[3, 1.5],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(tally.counts.accept).toEqual({ raw: 2, weighted: 3 });
|
||||||
|
expect(tally.counts.decline).toEqual({ raw: 1, weighted: 1.5 });
|
||||||
|
expect(tally.totalVotes).toBe(3);
|
||||||
|
expect(tally.totalWeight).toBe(4.5);
|
||||||
|
expect(tally.topKeys).toEqual(["accept"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("counts every answer on a multi-select poll", () => {
|
||||||
|
const tally = tallyOf(
|
||||||
|
[
|
||||||
|
{ userId: 1, answers: ["accept", "defer"] },
|
||||||
|
{ userId: 2, answers: ["decline"] },
|
||||||
|
],
|
||||||
|
new Map([
|
||||||
|
[1, 1],
|
||||||
|
[2, 1],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(tally.counts.accept.raw).toBe(1);
|
||||||
|
expect(tally.counts.defer.raw).toBe(1);
|
||||||
|
// Turnout is per voter, not per answer.
|
||||||
|
expect(tally.totalVotes).toBe(2);
|
||||||
|
expect(tally.totalWeight).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("dedupes a repeated key inside one vote", () => {
|
||||||
|
const tally = tallyOf(
|
||||||
|
[{ userId: 1, answers: ["accept", "accept", "accept"] }],
|
||||||
|
new Map([[1, 2]]),
|
||||||
|
);
|
||||||
|
expect(tally.counts.accept).toEqual({ raw: 1, weighted: 2 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores answers naming an option that is not on the poll", () => {
|
||||||
|
const tally = tallyOf(
|
||||||
|
[
|
||||||
|
{ userId: 1, answers: ["accept", "ghost"] },
|
||||||
|
{ userId: 2, answers: ["ghost"] },
|
||||||
|
],
|
||||||
|
new Map([
|
||||||
|
[1, 1],
|
||||||
|
[2, 1],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(tally.counts.accept.raw).toBe(1);
|
||||||
|
expect(tally.counts.ghost).toBeUndefined();
|
||||||
|
// The vote naming only a dead option is not turnout.
|
||||||
|
expect(tally.totalVotes).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("compares weights exactly, so decimal multipliers cannot fake a tie", () => {
|
||||||
|
// 1.1 + 1.1 against a single 2.2: float addition would miss the tie.
|
||||||
|
const tally = tallyOf(
|
||||||
|
[
|
||||||
|
{ userId: 1, answers: ["accept"] },
|
||||||
|
{ userId: 2, answers: ["accept"] },
|
||||||
|
{ userId: 3, answers: ["decline"] },
|
||||||
|
],
|
||||||
|
new Map([
|
||||||
|
[1, 1.1],
|
||||||
|
[2, 1.1],
|
||||||
|
[3, 2.2],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(tally.counts.accept.weighted).toBe(2.2);
|
||||||
|
expect(tally.topKeys).toEqual(["accept", "decline"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports no top option when nobody voted", () => {
|
||||||
|
const tally = tallyOf([]);
|
||||||
|
expect(tally.topScore).toBe(0);
|
||||||
|
expect(tally.topKeys).toEqual([]);
|
||||||
|
expect(tally.totalVotes).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("breakTieWithInitiator", () => {
|
||||||
|
it("picks the one tied option the initiator voted for", () => {
|
||||||
|
expect(
|
||||||
|
breakTieWithInitiator({
|
||||||
|
tiedKeys: ["accept", "decline"],
|
||||||
|
initiatorAnswers: ["decline"],
|
||||||
|
}),
|
||||||
|
).toBe("decline");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("refuses when the initiator picked several tied options", () => {
|
||||||
|
expect(
|
||||||
|
breakTieWithInitiator({
|
||||||
|
tiedKeys: ["accept", "decline"],
|
||||||
|
initiatorAnswers: ["accept", "decline"],
|
||||||
|
}),
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("refuses when the initiator voted outside the tie, or not at all", () => {
|
||||||
|
expect(
|
||||||
|
breakTieWithInitiator({ tiedKeys: ["accept", "decline"], initiatorAnswers: ["defer"] }),
|
||||||
|
).toBeNull();
|
||||||
|
expect(breakTieWithInitiator({ tiedKeys: ["accept"], initiatorAnswers: [] })).toBeNull();
|
||||||
|
expect(breakTieWithInitiator({ tiedKeys: ["accept"], initiatorAnswers: null })).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("resolvePollTally", () => {
|
||||||
|
const tiedTally = () =>
|
||||||
|
tallyOf(
|
||||||
|
[
|
||||||
|
{ userId: 1, answers: ["accept"] },
|
||||||
|
{ userId: 2, answers: ["decline"] },
|
||||||
|
],
|
||||||
|
new Map([
|
||||||
|
[1, 1],
|
||||||
|
[2, 1],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
it("decides a unique winner on votes", () => {
|
||||||
|
const tally = tallyOf(
|
||||||
|
[
|
||||||
|
{ userId: 1, answers: ["accept"] },
|
||||||
|
{ userId: 2, answers: ["accept"] },
|
||||||
|
{ userId: 3, answers: ["decline"] },
|
||||||
|
],
|
||||||
|
new Map([
|
||||||
|
[1, 1],
|
||||||
|
[2, 1],
|
||||||
|
[3, 1],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(resolvePollTally({ tally, initiatorAnswers: ["decline"] })).toEqual({
|
||||||
|
status: "decided",
|
||||||
|
winnerKey: "accept",
|
||||||
|
method: "votes",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("breaks a tie with the initiator's vote", () => {
|
||||||
|
expect(resolvePollTally({ tally: tiedTally(), initiatorAnswers: ["decline"] })).toEqual({
|
||||||
|
status: "decided",
|
||||||
|
winnerKey: "decline",
|
||||||
|
method: "initiator",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("escalates a tie the initiator cannot break", () => {
|
||||||
|
expect(
|
||||||
|
resolvePollTally({ tally: tiedTally(), initiatorAnswers: ["accept", "decline"] }),
|
||||||
|
).toEqual({ status: "pending", tiedKeys: ["accept", "decline"] });
|
||||||
|
expect(resolvePollTally({ tally: tiedTally(), initiatorAnswers: null })).toEqual({
|
||||||
|
status: "pending",
|
||||||
|
tiedKeys: ["accept", "decline"],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns none when nothing counted", () => {
|
||||||
|
expect(resolvePollTally({ tally: tallyOf([]), initiatorAnswers: ["accept"] })).toEqual({
|
||||||
|
status: "none",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("pickRandomTiedOption", () => {
|
||||||
|
it("is deterministic under an injected rng", () => {
|
||||||
|
expect(pickRandomTiedOption(["a", "b", "c"], () => 0)).toBe("a");
|
||||||
|
expect(pickRandomTiedOption(["a", "b", "c"], () => 0.5)).toBe("b");
|
||||||
|
expect(pickRandomTiedOption(["a", "b", "c"], () => 0.999)).toBe("c");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clamps an rng that returns exactly 1", () => {
|
||||||
|
expect(pickRandomTiedOption(["a", "b"], () => 1)).toBe("b");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null with nothing to pick", () => {
|
||||||
|
expect(pickRandomTiedOption([])).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in a new issue