// Tests for linking the characters of a campaign to the Discord players of the server it is // linked to (Syndria98/dragonroll#72): each player holds one character, anybody claims a free // one for themselves, and only a server administrator moves or frees one somebody else holds. // // Same set-up as tests/map-tokens.test.js, which the repository root runs without installing // anything: the express router of routes/discord.js is loaded into `node:vm` with its models // stubbed, and the last checks read the sources of the bot, whose command wiring is what has // to stay right. // // Run with `npm test` from the repository root, or `node --test tests/`. const { test } = require("node:test"); const assert = require("node:assert/strict"); const fs = require("node:fs"); const path = require("node:path"); const vm = require("node:vm"); function readRepoFile(...parts) { return fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8"); } // A mongoose query answers whatever `await query` and `query.lean()` answer with, and lets `select()` // and `sort()` sit in between. function mongooseQuery(value) { const result = { select: () => result, sort: () => result, lean: () => Promise.resolve(value), then: (onFulfilled, onRejected) => Promise.resolve(value).then(onFulfilled, onRejected), }; return result; } const GUILD_ID = "12345678901234567"; const PLAYER = "1111111111111111111"; const OTHER_PLAYER = "2222222222222222222"; // The pieces of a filter the routes build against actors: the campaign, the player holding the // character, and plain or `$ne` ids. function actorMatches(actor, filter = {}) { if (filter.campaign !== undefined && String(actor.campaign) !== String(filter.campaign)) return false; if (filter.discordUserId !== undefined && String(actor.discordUserId ?? null) !== String(filter.discordUserId ?? null)) return false; if (filter._id !== undefined) { if (filter._id && typeof filter._id === "object" && filter._id.$ne !== undefined) { if (String(actor._id) === String(filter._id.$ne)) return false; } else if (String(actor._id) !== String(filter._id)) return false; } return true; } // Loads routes/discord.js over a store of actors, a guild link and the campaign that guild holds. function loadDiscordRoutes({ guildLink = { guildId: GUILD_ID, dragonrollUser: "user-1" }, campaign = { _id: "campaign-1", name: "Katlum" }, actors = [] } = {}) { const store = actors.map((actor) => ({ campaign: "campaign-1", discordUserId: null, save: async () => {}, ...actor })); const routes = new Map(); const router = { get: (route, ...handlers) => routes.set(`GET ${route}`, handlers), post: (route, ...handlers) => routes.set(`POST ${route}`, handlers), delete: () => {}, }; const requireStub = (id) => { if (id === "express") return { Router: () => router }; if (id === "../models/Actor") return { findOne: (filter) => { const actor = store.find((candidate) => actorMatches(candidate, filter)); return mongooseQuery(actor ?? null); }, find: (filter) => mongooseQuery(store.filter((candidate) => actorMatches(candidate, filter)) .slice() .sort((a, b) => String(a.name).localeCompare(String(b.name)))), updateMany: async (filter, update) => { let modifiedCount = 0; for (const actor of store) { if (!actorMatches(actor, filter)) continue; if (update.$set && "discordUserId" in update.$set) actor.discordUserId = update.$set.discordUserId; modifiedCount += 1; } return { modifiedCount }; }, }; if (id === "../models/Campaign") return { findOne: () => mongooseQuery(campaign) }; if (id === "../models/DiscordGuildLink") return { findOne: () => mongooseQuery(guildLink) }; if (id === "../models/ServiceLinkRequest") return {}; if (id === "../models/User") return {}; if (id === "../services/service-links") return { requireDiscordBot: (req, res, next) => next(), NOTIFICATION_WINDOW_MS: 1 }; throw new Error(`require("${id}") is not stubbed`); }; const moduleStub = { exports: {} }; vm.compileFunction(readRepoFile("backend", "src", "routes", "discord.js"), ["require", "module", "exports"])( requireStub, moduleStub, moduleStub.exports ); async function call(route, { body = {}, params = {} } = {}) { const handlers = routes.get(route); assert.ok(handlers, `${route} is not mounted`); const res = { payload: null, json(payload) { this.payload = payload; } }; // The last handler of the chain, skipping the bot-secret gate the harness stands behind. await handlers[handlers.length - 1]({ body, params: { guildId: GUILD_ID, ...params } }, res); return res.payload; } function actor(id) { return store.find((candidate) => candidate._id === id); } return { call, actor }; } const ASSIGN = "POST /bot/guild/:guildId/actors/assign"; const UNASSIGN = "POST /bot/guild/:guildId/actors/unassign"; function assignmentRouteTests() { test("assigning links one campaign character to a Discord player", async () => { const api = loadDiscordRoutes({ actors: [{ _id: "actor-1", name: "Katlum" }] }); const response = await api.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } }); assert.equal(response.status, "ok"); assert.deepEqual(response.actor, { id: "actor-1", name: "Katlum", discordUserId: PLAYER }); assert.equal(api.actor("actor-1").discordUserId, PLAYER); assert.equal(response.previous, null); }); test("a player never holds two characters: taking a second one frees the first", async () => { const api = loadDiscordRoutes({ actors: [ { _id: "actor-1", name: "Katlum", discordUserId: PLAYER }, { _id: "actor-2", name: "Solus" } ] }); const response = await api.call(ASSIGN, { body: { actorId: "actor-2", discordUserId: PLAYER } }); assert.equal(response.status, "ok"); assert.equal(api.actor("actor-1").discordUserId, null); assert.equal(api.actor("actor-2").discordUserId, PLAYER); assert.deepEqual(response.previous, { id: "actor-1", name: "Katlum" }); }); test("a player cannot take a character another player already holds", async () => { const api = loadDiscordRoutes({ actors: [{ _id: "actor-1", name: "Katlum", discordUserId: OTHER_PLAYER }] }); const response = await api.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } }); assert.equal(response.msg, "discord.errors.actor-held"); assert.equal(api.actor("actor-1").discordUserId, OTHER_PLAYER); }); test("a server administrator moves a held character to themselves", async () => { const api = loadDiscordRoutes({ actors: [ { _id: "actor-1", name: "Katlum", discordUserId: OTHER_PLAYER }, { _id: "actor-2", name: "Solus", discordUserId: PLAYER } ] }); const response = await api.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER, admin: true } }); assert.equal(response.status, "ok"); assert.equal(api.actor("actor-1").discordUserId, PLAYER); assert.equal(api.actor("actor-2").discordUserId, null); }); test("unassigning without a character frees the one linked to the player", async () => { const api = loadDiscordRoutes({ actors: [ { _id: "actor-1", name: "Katlum", discordUserId: PLAYER }, { _id: "actor-2", name: "Silang", discordUserId: OTHER_PLAYER } ] }); const response = await api.call(UNASSIGN, { body: { discordUserId: PLAYER } }); assert.equal(response.status, "ok"); assert.deepEqual(response.actor, { id: "actor-1", name: "Katlum" }); assert.equal(response.wasYours, true); assert.equal(api.actor("actor-1").discordUserId, null); assert.equal(api.actor("actor-2").discordUserId, OTHER_PLAYER); }); test("a player cannot unassign a character held by somebody else", async () => { const api = loadDiscordRoutes({ actors: [{ _id: "actor-1", name: "Katlum", discordUserId: OTHER_PLAYER }] }); const response = await api.call(UNASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } }); assert.equal(response.msg, "discord.errors.actor-held"); assert.equal(api.actor("actor-1").discordUserId, OTHER_PLAYER); }); test("a server administrator frees anybody's character", async () => { const api = loadDiscordRoutes({ actors: [{ _id: "actor-1", name: "Katlum", discordUserId: OTHER_PLAYER }] }); const response = await api.call(UNASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER, admin: true } }); assert.equal(response.status, "ok"); assert.equal(response.wasYours, false); assert.equal(api.actor("actor-1").discordUserId, null); }); } function assignmentGuardTests() { test("linking needs a guild with a connected account and a linked campaign", async () => { const connected = loadDiscordRoutes({ actors: [{ _id: "actor-1", name: "Katlum" }] }); assert.equal((await connected.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } })).status, "ok"); const notLinked = loadDiscordRoutes({ guildLink: null }); assert.equal((await notLinked.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } })).msg, "discord.errors.not-connected"); assert.equal((await notLinked.call(UNASSIGN, { body: { discordUserId: PLAYER } })).msg, "discord.errors.not-connected"); const noCampaign = loadDiscordRoutes({ campaign: null }); assert.equal((await noCampaign.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: PLAYER } })).msg, "errors.notfound"); }); test("linking needs a whole player and one of the campaign's own characters", async () => { const api = loadDiscordRoutes({ actors: [{ _id: "actor-1", name: "Katlum", campaign: "campaign-1" }] }); assert.equal((await api.call(ASSIGN, { body: { discordUserId: PLAYER } })).msg, "errors.missing-data"); assert.equal((await api.call(ASSIGN, { body: { actorId: "actor-1" } })).msg, "errors.missing-data"); assert.equal((await api.call(ASSIGN, { body: { actorId: "actor-1", discordUserId: "bob" } })).msg, "errors.missing-data"); assert.equal((await api.call(UNASSIGN, { body: {} })).msg, "errors.missing-data"); const otherCampaign = loadDiscordRoutes({ actors: [{ _id: "actor-9", name: "Stranger", campaign: "campaign-2" }] }); assert.equal((await otherCampaign.call(ASSIGN, { body: { actorId: "actor-9", discordUserId: PLAYER } })).msg, "errors.notfound"); }); test("the bot roster carries the player linked to each character", async () => { const api = loadDiscordRoutes({ actors: [ { _id: "actor-1", name: "Katlum", discordUserId: PLAYER }, { _id: "actor-2", name: "Solus" } ] }); const response = await api.call("GET /bot/guild/:guildId/actors"); assert.equal(response.status, "ok"); assert.deepEqual(response.actors.map((actor) => actor.discordUserId), [PLAYER, null]); }); } function botWiringTests() { const commands = readRepoFile("discord-bot", "src", "commands.js"); const api = readRepoFile("discord-bot", "src", "dragonroll-api.js"); const bot = readRepoFile("discord-bot", "src", "index.js"); test("the dragonroll command carries assign and unassign with a character choice", () => { assert.match(commands, /setName\('assign'\)[\s\S]*setName\('character'\)[\s\S]*setRequired\(true\)[\s\S]*setAutocomplete\(true\)/); assert.match(commands, /setName\('unassign'\)[\s\S]*setName\('character'\)[\s\S]*setAutocomplete\(true\)/); // The unassign character is optional, so a player can free their own without naming it. const unassign = /setName\('unassign'\)([\s\S]*)$/.exec(commands)?.[1] ?? ""; assert.doesNotMatch(unassign, /setRequired\(true\)/); }); test("the bot client calls the new routes and answers the new subcommands", () => { assert.match(api, /\/actors\/assign/); assert.match(api, /\/actors\/unassign/); assert.match(bot, /\['assign', 'unassign'\]\.includes\(subcommand\)/); assert.match(bot, /dragonroll\.assignActor\(guildId/); assert.match(bot, /dragonroll\.unassignActor\(guildId/); }); test("the character choices autocomplete both new subcommands", () => { const autocomplete = /if \(interaction\.commandName === 'dragonroll'\) \{([\s\S]*?)\n \}\n/.exec(bot)?.[1] ?? ""; assert.match(autocomplete, /\['assign', 'unassign'\]\.includes\(subcommand\)/); assert.match(autocomplete, /respondActorChoices\(interaction, guildId\)/); }); test("the roster shows the player and the status card shows your character", () => { assert.match(bot, /actor\.discordUserId \? ` 🎮 <@\$\{actor\.discordUserId\}>`/); assert.match(bot, /name: 'Your character'/); }); test("the actor model holds one Discord player per character and per campaign", () => { const model = readRepoFile("backend", "src", "models", "Actor.js"); assert.match(model, /discordUserId: \{ type: String, default: null \}/); assert.match(model, /\{ campaign: 1, discordUserId: 1 \},\s*\{ unique: true, partialFilterExpression: \{ discordUserId: \{ \$type: 'string' \} \} \}/); }); } assignmentRouteTests(); assignmentGuardTests(); botWiringTests();