313 lines
11 KiB
JavaScript
313 lines
11 KiB
JavaScript
// Tests for the Dragonroll Foundry module's sync toggle and per-actor force sync
|
|
// (Syndria98/dragonroll#8). The module is a Foundry client script with no module
|
|
// wrapper, so it is loaded into a `node:vm` context holding stubbed Foundry
|
|
// globals (`game`, `Hooks`, `ui`, `fetch`) with fake timers: that makes every
|
|
// queued push, retry and reconcile observable without a running Foundry VTT.
|
|
//
|
|
// 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",
|
|
);
|
|
|
|
function stubDocument(id, name, extra = {}) {
|
|
return {
|
|
id,
|
|
name,
|
|
flags: {},
|
|
getFlag(module, key) { return this.flags?.[module]?.[key]; },
|
|
async update(data) {
|
|
for (const [key, value] of Object.entries(data)) {
|
|
const parts = key.split(".");
|
|
const last = parts.pop();
|
|
let target = this;
|
|
for (const part of parts) target = target[part] ??= {};
|
|
target[last] = value;
|
|
}
|
|
return this;
|
|
},
|
|
toObject() {
|
|
return {
|
|
_id: this.id,
|
|
name: this.name,
|
|
type: this.type,
|
|
img: "icons/svg/mystery-man.svg",
|
|
flags: this.flags,
|
|
...(this.system ? { system: this.system } : {}),
|
|
};
|
|
},
|
|
...extra,
|
|
};
|
|
}
|
|
|
|
function makeWorldItem(id, name) {
|
|
return stubDocument(id, name, {
|
|
documentName: "Item",
|
|
type: "weapon",
|
|
parent: null,
|
|
system: { properties: { value: [] }, quantity: 1, weight: 3, rarity: "common" },
|
|
});
|
|
}
|
|
|
|
function makeStubWorld({ autoSync = true } = {}) {
|
|
const state = {
|
|
hooks: new Map(),
|
|
registered: new Map(),
|
|
requests: [],
|
|
notifications: [],
|
|
timers: new Map(),
|
|
nextTimerId: 1,
|
|
};
|
|
|
|
const actors = [
|
|
stubDocument("actor-1", "Thalia", { documentName: "Actor", type: "character", items: { contents: [] } }),
|
|
stubDocument("actor-2", "Grunt", { documentName: "Actor", type: "npc", items: { contents: [] } }),
|
|
];
|
|
const settingsStore = {
|
|
autoSync,
|
|
syncToken: "sync-token-1",
|
|
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);
|
|
},
|
|
},
|
|
// Fake timers: the module debounces and retries with setTimeout, so the tests
|
|
// decide when those callbacks run instead of waiting on the wall clock.
|
|
setTimeout: (fn, delay = 0) => {
|
|
const id = state.nextTimerId++;
|
|
state.timers.set(id, { fn, delay });
|
|
return id;
|
|
},
|
|
clearTimeout: (id) => state.timers.delete(id),
|
|
setInterval: () => 0,
|
|
clearInterval: () => {},
|
|
fetch: async (url, options = {}) => {
|
|
state.requests.push({
|
|
href: String(url),
|
|
method: options.method,
|
|
body: options.body ? JSON.parse(options.body) : null,
|
|
});
|
|
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
|
|
},
|
|
Actor: { async create() { return null; } },
|
|
Item: { async create() { return null; } },
|
|
};
|
|
|
|
sandbox.game = {
|
|
user: { isGM: true },
|
|
world: { id: "world-1", title: "Test World" },
|
|
system: { id: "dnd5e" },
|
|
modules: { get: () => ({}) },
|
|
actors: { contents: actors, get: (id) => actors.find((actor) => actor.id === id) },
|
|
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.actor = (id) => actors.find((document) => document.id === id);
|
|
// Sync pushes only: the pairing status read lives under the same prefix, and it
|
|
// tells nothing about what the world sent.
|
|
state.syncRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync")
|
|
&& !request.href.includes("foundry/sync/status"));
|
|
|
|
state.fire = async (name, ...args) => {
|
|
for (const handler of state.hooks.get(name) || []) await handler(...args);
|
|
await drain();
|
|
};
|
|
|
|
state.runTimers = async () => {
|
|
for (let round = 0; round < 6; round += 1) {
|
|
if (!state.timers.size && round > 2) break;
|
|
const due = [...state.timers.values()];
|
|
state.timers.clear();
|
|
for (const timer of due) await timer.fn();
|
|
await drain();
|
|
}
|
|
};
|
|
|
|
async function drain() {
|
|
await new Promise((resolve) => setImmediate(resolve));
|
|
}
|
|
|
|
state.linkedSetup = async () => {
|
|
await state.fire("init");
|
|
await state.fire("ready");
|
|
await state.runTimers();
|
|
state.requests.length = 0;
|
|
return state;
|
|
};
|
|
|
|
return state;
|
|
}
|
|
|
|
async function forceSyncActors(world, ...actorIds) {
|
|
const options = [];
|
|
await world.fire("getActorDirectoryEntryContext", null, options);
|
|
const entry = options.find((option) => option.name === "Dragonroll: Force Sync");
|
|
assert.ok(entry, "Dragonroll: Force Sync is offered in the actor directory context menu");
|
|
await entry.callback(actorIds.map((actorId) => ({ dataset: { actorId } })));
|
|
await world.runTimers();
|
|
}
|
|
|
|
test("auto-sync is a module setting that is on by default", async () => {
|
|
const world = makeStubWorld();
|
|
await world.fire("init");
|
|
|
|
const setting = world.registered.get("autoSync");
|
|
assert.equal(setting.default, true, "autosync is on by default");
|
|
assert.equal(setting.config, true, "autosync appears in the module settings");
|
|
assert.equal(world.game.settings.get(MODULE_ID, "autoSync"), true);
|
|
});
|
|
|
|
test("autosync on: Foundry CRUD events keep syncing with Dragonroll", async () => {
|
|
const world = await makeStubWorld().linkedSetup();
|
|
|
|
await world.fire("updateActor", world.actor("actor-1"));
|
|
await world.runTimers();
|
|
|
|
const pushes = world.syncRequests();
|
|
assert.equal(pushes.length, 1);
|
|
assert.equal(pushes[0].body.actors[0]._id, "actor-1");
|
|
});
|
|
|
|
test("autosync off: CRUD requests stop syncing", async () => {
|
|
const world = await makeStubWorld().linkedSetup();
|
|
|
|
await world.game.settings.set(MODULE_ID, "autoSync", false);
|
|
await world.fire("updateActor", world.actor("actor-1"));
|
|
await world.fire("deleteActor", world.actor("actor-2"));
|
|
await world.fire("createItem", makeWorldItem("item-1", "Longsword"));
|
|
await world.runTimers();
|
|
|
|
assert.deepEqual(world.syncRequests(), []);
|
|
});
|
|
|
|
test("edits made while autosync is off are delivered when it is turned back on", async () => {
|
|
const world = await makeStubWorld().linkedSetup();
|
|
|
|
await world.game.settings.set(MODULE_ID, "autoSync", false);
|
|
await world.fire("updateActor", world.actor("actor-1"));
|
|
await world.fire("createItem", makeWorldItem("item-1", "Longsword"));
|
|
await world.runTimers();
|
|
assert.deepEqual(world.syncRequests(), []);
|
|
|
|
await world.game.settings.set(MODULE_ID, "autoSync", true);
|
|
await world.runTimers();
|
|
|
|
const pushes = world.syncRequests();
|
|
assert.ok(pushes.some((request) => request.body?.fullSync === false
|
|
&& request.body.actors?.some((actor) => actor._id === "actor-1")),
|
|
"the actor edit queued while autosync was off is sent");
|
|
assert.ok(pushes.some((request) => request.href.includes("foundry/sync/item-snapshot")
|
|
&& request.body.items.some((item) => item._id === "item-1")),
|
|
"the item edit queued while autosync was off is sent");
|
|
});
|
|
|
|
test("autosync off at world start: no snapshot and no reconcile", async () => {
|
|
const world = makeStubWorld({ autoSync: false });
|
|
await world.fire("init");
|
|
await world.fire("ready");
|
|
await world.runTimers();
|
|
|
|
assert.deepEqual(world.syncRequests(), []);
|
|
});
|
|
|
|
test("force sync sends selected actors to Dragonroll even with autosync off", async () => {
|
|
const world = await makeStubWorld().linkedSetup();
|
|
await world.game.settings.set(MODULE_ID, "autoSync", false);
|
|
|
|
await forceSyncActors(world, "actor-2");
|
|
|
|
const pushes = world.syncRequests();
|
|
assert.equal(pushes.length, 1);
|
|
assert.equal(pushes[0].body.fullSync, false, "a forced actor never prunes the campaign");
|
|
assert.deepEqual(pushes[0].body.actors.map((actor) => actor._id), ["actor-2"]);
|
|
assert.deepEqual(world.notifications.filter(([kind]) => kind !== "info"), []);
|
|
});
|
|
|
|
test("force sync sends every selected actor in one push", async () => {
|
|
const world = await makeStubWorld().linkedSetup();
|
|
await world.game.settings.set(MODULE_ID, "autoSync", false);
|
|
|
|
await forceSyncActors(world, "actor-1", "actor-2");
|
|
|
|
const pushes = world.syncRequests();
|
|
assert.equal(pushes.length, 1);
|
|
assert.deepEqual(pushes[0].body.actors.map((actor) => actor._id), ["actor-1", "actor-2"]);
|
|
});
|
|
|
|
test("force sync also works while autosync is on", async () => {
|
|
const world = await makeStubWorld().linkedSetup();
|
|
|
|
await forceSyncActors(world, "actor-1");
|
|
|
|
assert.deepEqual(world.syncRequests()[0]?.body.actors.map((actor) => actor._id), ["actor-1"]);
|
|
});
|
|
|
|
test("force sync refuses an actor Dragonroll does not import", async () => {
|
|
const world = makeStubWorld({ autoSync: false });
|
|
await world.fire("init");
|
|
const cart = stubDocument("actor-3", "Cart", { documentName: "Actor", type: "vehicle", items: { contents: [] } });
|
|
world.game.actors.contents.push(cart);
|
|
|
|
await forceSyncActors(world, "actor-3");
|
|
|
|
assert.deepEqual(world.syncRequests(), []);
|
|
assert.ok(world.notifications.some(([kind, text]) => kind === "warn" && text.includes("Cart")));
|
|
});
|
|
|
|
test("turning autosync back on reconciles both sides again", async () => {
|
|
const world = makeStubWorld({ autoSync: false });
|
|
await world.fire("init");
|
|
await world.fire("ready");
|
|
await world.runTimers();
|
|
assert.deepEqual(world.syncRequests(), []);
|
|
|
|
await world.game.settings.set(MODULE_ID, "autoSync", true);
|
|
await world.runTimers();
|
|
|
|
assert.ok(world.syncRequests().some((request) => request.body?.fullSync === true),
|
|
"the world sends its full snapshot again");
|
|
assert.ok(world.requests.some((request) => request.href.includes("foundry/sync/characters")),
|
|
"Dragonroll documents are applied back into the world");
|
|
});
|