Files
dragonroll/tests/foundry-pairing-status.test.js
2026-10-14 14:07:52 +00:00

269 lines
11 KiB
JavaScript

// Tests for how the Dragonroll Foundry module connects a world to a campaign
// (Syndria98/dragonroll#17 and #19). Like foundry-sync-toggle.test.js, the module
// script runs inside a `node:vm` context of stubbed Foundry globals; here each
// test also decides what Dragonroll answers, because the pairing status is that
// answer plus what this client holds (its sync token and its sign-up link).
//
// The world no longer redeems a code typed into its settings: it asks Dragonroll
// for the same sign-up link every service gets, shows it, and picks its token up
// once a user has answered that link.
//
// 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");
const MODULE_ID = "dragonroll-foundry";
const MODULE_SOURCE = fs.readFileSync(
path.join(__dirname, "..", "dragonroll-foundry", "scripts", "api.js"),
"utf8",
);
const LINKED_CAMPAIGN = { id: "campaign-1", name: "Curse of Strahd" };
const SIGN_UP_LINK = "http://frontend.test/link/authorize?service=foundry#code=link-code-1";
// The stub starts as a world that finished pairing (`syncToken: ""` is one that
// never did), optionally holding a sign-up link it is waiting on. `answers` maps
// a route fragment to the JSON Dragonroll replies with; a route that is not
// listed answers `{status:"ok"}`, and one mapped to null answers HTML, like a
// Dragonroll old enough not to have that route at all.
function makeStubWorld({
syncToken = "sync-token-1",
linkCode = "",
linkUrl = "",
answers = {},
} = {}) {
const state = {
hooks: new Map(),
registered: new Map(),
requests: [],
notifications: [],
};
const settingsStore = {
autoSync: true,
syncToken,
linkCode,
linkUrl,
dragonrollApiUrl: "http://backend.test:5000",
};
const sandbox = {
console: { log() {}, info() {}, warn() {}, error() {} },
URL,
CONFIG: {},
window: { location: { origin: "http://vtt.test" } },
ui: {
notifications: {
info: (text) => state.notifications.push(["info", text]),
warn: (text) => state.notifications.push(["warn", text]),
error: (text) => state.notifications.push(["error", text]),
},
},
Hooks: {
once(name, fn) { state.hooks.set(name, [fn]); },
on(name, fn) {
const handlers = state.hooks.get(name) || [];
handlers.push(fn);
state.hooks.set(name, handlers);
},
},
// The pairing status never waits on a timer: it is written when the world is
// ready and whenever a link check answers, so dropping these keeps the
// snapshot and reconcile loops out of these tests.
setTimeout: () => 0,
clearTimeout: () => {},
setInterval: () => 0,
clearInterval: () => {},
fetch: async (url, options = {}) => {
const href = String(url);
state.requests.push({
href,
method: options.method,
body: options.body ? JSON.parse(options.body) : null,
authorization: options.headers?.Authorization || "",
});
const route = Object.keys(answers).find((fragment) => href.includes(fragment));
const payload = route ? answers[route] : { status: "ok" };
if (payload === null) {
return { ok: false, status: 404, json: async () => { throw new SyntaxError("Unexpected token < in JSON."); } };
}
return { ok: true, status: 200, json: async () => payload };
},
Actor: { async create() { return null; } },
Item: { async create() { return null; } },
};
sandbox.game = {
user: { isGM: true, name: "Test GM" },
world: { id: "world-1", title: "Test World" },
system: { id: "dnd5e" },
modules: { get: () => ({}) },
actors: { contents: [], get: () => null },
items: { contents: [], get: () => null },
settings: {
register(module, key, definition) {
state.registered.set(key, definition);
if (!(key in settingsStore)) settingsStore[key] = definition.default;
},
get(module, key) { return settingsStore[key]; },
async set(module, key, value) {
settingsStore[key] = value;
await state.registered.get(key)?.onChange?.(value);
},
},
};
vm.createContext(sandbox);
vm.runInContext(MODULE_SOURCE, sandbox);
state.game = sandbox.game;
state.setting = (key) => settingsStore[key];
state.status = () => settingsStore.pairingStatus;
state.statusRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync/status"));
state.linkStarts = () => state.requests.filter((request) => request.href.includes("link/start"));
state.linkPickups = () => state.requests.filter((request) => request.href.includes("link/pickup"));
// The module's own awaits run in the vm's promise intrinsics, so a few turns of
// the event loop are what it takes for a written status to be observable.
state.settle = async () => {
for (let round = 0; round < 10; round += 1) await new Promise((resolve) => setImmediate(resolve));
};
state.fire = async (name, ...args) => {
for (const handler of state.hooks.get(name) || []) await handler(...args);
await state.settle();
};
state.start = async () => {
await state.fire("init");
await state.fire("ready");
return state;
};
return state;
}
test("the pairing status is a setting the module configures", async () => {
const world = await makeStubWorld().start();
const setting = world.registered.get("pairingStatus");
assert.equal(setting.config, true, "the pairing status appears in the module settings");
assert.equal(setting.type.name, "String", "the pairing status is a sentence");
assert.equal(setting.scope, "client", "the pairing status belongs to this client, like the token it comes from");
});
test("an unpaired world asks Dragonroll for a sign-up link and shows it", async () => {
const world = await makeStubWorld({
syncToken: "",
answers: { "link/start": { status: "ok", code: "link-code-1", linkUrl: SIGN_UP_LINK } },
}).start();
const started = world.linkStarts()[0];
assert.ok(started, "the world asks for a link of its own");
assert.equal(started.body.service, "foundry", "and says which service it is");
assert.equal(started.body.target.id, "world-1", "the world tells Dragonroll who it is");
assert.equal(started.body.target.name, "Test World");
assert.equal(started.body.target.meta.system, "dnd5e");
assert.match(world.status(), /^Not connected yet/);
assert.ok(world.status().includes(SIGN_UP_LINK), "the status is the link the GM has to open");
assert.equal(world.setting("linkCode"), "link-code-1", "the code behind the link is kept to ask with");
});
test("a world that holds a token neither asks for a link nor waits on one", async () => {
const world = await makeStubWorld({
answers: { "foundry/sync/status": { status: "ok", campaign: LINKED_CAMPAIGN, worldId: "world-1" } },
}).start();
assert.equal(world.status(), `Connected to the Dragonroll campaign "${LINKED_CAMPAIGN.name}".`);
assert.deepEqual(world.linkStarts(), [], "a paired world has nothing to link");
assert.equal(world.statusRequests()[0].authorization, "Bearer sync-token-1", "the campaign is asked with the sync token");
});
test("a campaign that unlinked this world stops being reported as connected", async () => {
const world = await makeStubWorld({
answers: { "foundry/sync/status": { status: "error", msg: "unauthorized" } },
}).start();
assert.match(world.status(), /^Not connected/);
assert.match(world.status(), /no longer linked/);
assert.equal(world.setting("syncToken"), "", "the dead token is dropped, so nothing keeps pushing to that campaign");
});
test("an unreachable Dragonroll keeps the pairing this client already knows", async () => {
const world = await makeStubWorld({ answers: { "foundry/sync/status": null } }).start();
assert.equal(world.status(), "Connected to a Dragonroll campaign.",
"a Dragonroll without the status route says nothing, so the token speaks");
});
test("a link still waiting on its GM says the world is not connected yet", async () => {
const world = await makeStubWorld({
syncToken: "",
linkCode: "link-code-1",
linkUrl: SIGN_UP_LINK,
answers: { "link/pickup": { status: "ok", state: "pending" } },
}).start();
assert.equal(world.linkPickups()[0].body.code, "link-code-1", "the world asks with the code it was given");
assert.deepEqual(world.linkStarts(), [], "an unanswered link is kept, not replaced");
assert.match(world.status(), /^Not connected yet/);
assert.ok(world.status().includes(SIGN_UP_LINK), "and it is still the link to open");
});
test("a picked-up link connects the world, hands over its token and is dropped", async () => {
const world = await makeStubWorld({
syncToken: "",
linkCode: "link-code-1",
linkUrl: SIGN_UP_LINK,
answers: {
"link/pickup": {
status: "ok",
state: "linked",
campaign: LINKED_CAMPAIGN,
syncToken: "sync-token-2",
bridgeConfig: { url: "http://bridge.test", pushToken: "push-1" },
},
// The token this link handed over is the one the campaign is asked with.
"foundry/sync/status": { status: "ok", campaign: LINKED_CAMPAIGN, worldId: "world-1" },
},
}).start();
assert.equal(world.status(), `Connected to the Dragonroll campaign "${LINKED_CAMPAIGN.name}".`);
assert.equal(world.setting("syncToken"), "sync-token-2", "the token the link came with is what sync runs on");
assert.deepEqual(world.setting("bridgeConfig"), { url: "http://bridge.test", pushToken: "push-1" });
assert.equal(world.setting("linkCode"), "", "a link that delivered its token is not asked about again");
assert.equal(world.setting("linkUrl"), "");
});
test("an expired link is replaced by one the GM can still open", async () => {
const world = await makeStubWorld({
syncToken: "",
linkCode: "link-code-1",
linkUrl: SIGN_UP_LINK,
answers: {
"link/pickup": { status: "ok", state: "expired" },
"link/start": { status: "ok", code: "link-code-2", linkUrl: "http://frontend.test/link/authorize?service=foundry#code=link-code-2" },
},
}).start();
assert.equal(world.setting("linkCode"), "link-code-2", "the world keeps a link nobody has to guess at");
assert.match(world.status(), /link-code-2/, "and shows the new one");
});
test("whatever is typed into the status is replaced by the real one", async () => {
const world = await makeStubWorld({
answers: { "foundry/sync/status": { status: "ok", campaign: LINKED_CAMPAIGN, worldId: "world-1" } },
});
await world.start();
await world.game.settings.set(MODULE_ID, "pairingStatus", "My own status text");
await world.settle();
assert.equal(world.status(), `Connected to the Dragonroll campaign "${LINKED_CAMPAIGN.name}".`);
});