Fix #61: Fix tests #68

Closed
Agent wants to merge 1 commits from ai/issue-61 into master
5 changed files with 58 additions and 18 deletions

View File

@@ -23,6 +23,7 @@ let updatingPairingStatus = false;
let linkedCampaignName = ""; let linkedCampaignName = "";
let linkProblem = ""; let linkProblem = "";
let actorSyncTimeout; let actorSyncTimeout;
let characterSyncRetryTimeout;
let characterSyncRunning = false; let characterSyncRunning = false;
let actorSyncErrorLogged = false; let actorSyncErrorLogged = false;
const syncingActorIds = new Set(); const syncingActorIds = new Set();
@@ -1223,6 +1224,14 @@ async function reconcileDragonrollCharacters() {
} }
} }
// Both sides converge on a timer that only runs while the world is open, so a
// round that could not reach Dragonroll is asked for again in a while instead of
// leaving the campaign with whatever it happened to receive.
function scheduleDragonrollCharacterSync(delay = 15000) {
clearTimeout(characterSyncRetryTimeout);
characterSyncRetryTimeout = setTimeout(reconcileDragonrollCharacters, delay);
}
async function initializeCharacterSync() { async function initializeCharacterSync() {
if (!getSyncToken() || !game.user?.isGM || !game.world || !isAutoSyncEnabled()) return; if (!getSyncToken() || !game.user?.isGM || !game.world || !isAutoSyncEnabled()) return;
try { try {

View File

@@ -55,7 +55,7 @@ function matches(document, filter = {}) {
}); });
} }
function fakeModel(table, seed = []) { function fakeModel(table, seed = [], campaignId) {
const rows = []; const rows = [];
let counter = 0; let counter = 0;
@@ -74,7 +74,9 @@ function fakeModel(table, seed = []) {
Object.defineProperty(Document.prototype, "id", { get() { return this._id; } }); Object.defineProperty(Document.prototype, "id", { get() { return this._id; } });
for (const data of seed) { for (const data of seed) {
const row = new Document({ [table === "folder" ? "target" : "name"]: undefined, ...data }); // A seeded row belongs to the campaign the requests are made against unless the
// seed says otherwise: the routes scope every lookup by campaign.
const row = new Document({ campaign: campaignId, [table === "folder" ? "target" : "name"]: undefined, ...data });
row.isNew = false; row.isNew = false;
rows.push(row); rows.push(row);
} }
@@ -121,13 +123,16 @@ function loadSyncRoute({ seed = {}, worldId = "world-1" } = {}) {
}; };
const campaign = { _id: "campaign-1", id: "campaign-1", name: "Test Campaign", foundryWorldId: worldId }; const campaign = { _id: "campaign-1", id: "campaign-1", name: "Test Campaign", foundryWorldId: worldId };
const models = { const models = {
"../models/Actor": fakeModel("actor", seed.actors), "../models/Actor": fakeModel("actor", seed.actors, campaign.id),
"../models/Item": fakeModel("item", seed.items), "../models/Item": fakeModel("item", seed.items, campaign.id),
"../models/Folder": fakeModel("folder", seed.folders), "../models/Folder": fakeModel("folder", seed.folders, campaign.id),
}; };
const requireStub = (id) => { const requireStub = (id) => {
if (id === "express") return { Router: () => router }; if (id === "express") return { Router: () => router };
// The route hashes the sync token with node's own crypto: the real module costs nothing
// to hand it, and nothing here depends on what the hash looks like.
if (id === "node:crypto") return require("node:crypto");
if (id === "mongoose") return { isValidObjectId: (value) => typeof value === "string" && value.length > 20 }; if (id === "mongoose") return { isValidObjectId: (value) => typeof value === "string" && value.length > 20 };
if (id === "../models/Campaign") return { findOne: async () => campaign }; if (id === "../models/Campaign") return { findOne: async () => campaign };
if (id === "../services/actor-foundry") return { foundryActorToCharacter: (actor) => ({ name: actor?.name ?? "" }) }; if (id === "../services/actor-foundry") return { foundryActorToCharacter: (actor) => ({ name: actor?.name ?? "" }) };
@@ -298,9 +303,12 @@ test("every folder listing says which campaign list it belongs to", () => {
// field existed carry none at all. tests/entry-folders.test.js runs these routes. // field existed carry none at all. tests/entry-folders.test.js runs these routes.
for (const route of ["note.js", "folder.js"]) { for (const route of ["note.js", "folder.js"]) {
const source = read("backend", "src", "routes", route); const source = read("backend", "src", "routes", route);
const listings = source.match(/Folder\.find\(/g) ?? []; // The listings that gather a campaign's folders are the ones shown as a section's
// tree. A walk of one folder's own children (`parentFolder`) is inside a single
// list already: folders are only ever nested within their own section.
const listings = source.match(/Folder\.find\(\{\s*campaign/g) ?? [];
assert.ok(listings.length, `${route} lists folders`); assert.ok(listings.length, `${route} lists folders`);
const filtered = source.match(/Folder\.find\(\{[^{]*Folder\.filterForTarget\((?:'note'|target)\)/g) ?? []; const filtered = source.match(/Folder\.find\(\{\s*campaign[^{]*Folder\.filterForTarget\((?:'note'|target)\)/g) ?? [];
assert.equal(filtered.length, listings.length, `${route} has a folder listing that names no campaign list`); assert.equal(filtered.length, listings.length, `${route} has a folder listing that names no campaign list`);
} }
}); });
@@ -354,6 +362,10 @@ function makeWorld() {
id: "actor-1", name: "Thalia", type: "character", documentName: "Actor", flags: {}, id: "actor-1", name: "Thalia", type: "character", documentName: "Actor", flags: {},
items: { contents: [carriedItem] }, items: { contents: [carriedItem] },
getFlag() { return undefined; }, getFlag() { return undefined; },
// A pushed actor has its items marked as synced and itself mapped to the
// campaign row: nothing here reads those flags back.
async update() { return this; },
async updateEmbeddedDocuments() { return []; },
toObject() { return { _id: this.id, name: this.name, type: this.type, flags: this.flags }; }, toObject() { return { _id: this.id, name: this.name, type: this.type, flags: this.flags }; },
}, },
]; ];
@@ -523,12 +535,12 @@ test("autosync off: folder changes stop syncing", async () => {
// --- The sidebar groups its items under those folders ---------------------------- // --- The sidebar groups its items under those folders ----------------------------
async function loadItemFoldersService() { function loadItemFoldersService() {
const source = read("frontend", "app", "services", "ItemFolders.js").replace("export { BuildItemRows };", "return { BuildItemRows };"); const source = read("frontend", "app", "services", "ItemFolders.js").replace("export { BuildItemRows };", "return { BuildItemRows };");
return vm.compileFunction(source)(); return vm.compileFunction(source)();
} }
const { BuildItemRows } = await loadItemFoldersService(); const { BuildItemRows } = loadItemFoldersService();
const SIDEBAR_FOLDERS = [ const SIDEBAR_FOLDERS = [
{ _id: "f-melee", name: "Melee Weapons" }, { _id: "f-melee", name: "Melee Weapons" },
@@ -546,13 +558,15 @@ test("items are grouped under the folder they stand in, nested", () => {
row.kind, row.kind === "folder" ? row.folder.name : row.item.name, row.depth, row.kind, row.kind === "folder" ? row.folder.name : row.item.name, row.depth,
]); ]);
// Every folder is followed by what stands in it, one step deeper, and the items that
// stand at the root come last (see BuildItemRows).
assert.deepEqual(shape, [ assert.deepEqual(shape, [
["folder", "Melee Weapons", 0], ["folder", "Melee Weapons", 0],
["item", "Longsword", 1],
["folder", "Ranged Weapons", 0], ["folder", "Ranged Weapons", 0],
["folder", "Powder Weapons", 1], ["folder", "Powder Weapons", 1],
["item", "Pistol", 1], ["item", "Pistol", 2],
["item", "Torch", 0], ["item", "Torch", 0],
["item", "Longsword", 1],
]); ]);
}); });
@@ -579,9 +593,9 @@ test("an item whose folder is gone, or a folder nested in itself, reads as a roo
); );
const shape = rows.map((row) => [row.kind, row.kind === "folder" ? row.folder.name : row.item.name]); const shape = rows.map((row) => [row.kind, row.kind === "folder" ? row.folder.name : row.item.name]);
assert.ok(shape.includes(["item", "Torch"]), "the item is not lost with the folder that was removed"); assert.ok(shape.some(([kind, name]) => kind === "item" && name === "Torch"), "the item is not lost with the folder that was removed");
assert.deepEqual(new Set(shape.filter(([kind]) => kind === "folder").map(([, name]) => name)), new Set(["A", "B"])); assert.deepEqual(new Set(shape.filter(([kind]) => kind === "folder").map(([, name]) => name)), new Set(["A", "B"]));
assert.equal(rows.filter(([kind]) => kind === "folder").length, 2, "a broken tree is walked once, not forever"); assert.equal(shape.filter(([kind]) => kind === "folder").length, 2, "a broken tree is walked once, not forever");
}); });
test("every locale labels the folder row", () => { test("every locale labels the folder row", () => {

View File

@@ -66,8 +66,8 @@ test("the item routes accept the icon and upload one", () => {
test("the item info window is registered and opens on a sidebar click", () => { test("the item info window is registered and opens on a sidebar click", () => {
assert.match(windowDefsSource, /item_sheet:\s*{\s*title:[^}]*ItemSheetWindow\.vue/s); assert.match(windowDefsSource, /item_sheet:\s*{\s*title:[^}]*ItemSheetWindow\.vue/s);
// clicking (or Enter/Space on) an item row opens the window instead of expanding inline. // clicking (or Enter/Space on) an item row opens the window instead of expanding inline.
// Since #44 the rows come from the folder tree the world synced, so the row holds the item. // The rows come from the item list's folder tree, so the row holds the item.
assert.match(sidebarSource, /v-for="row in itemRows"[\s\S]*?@click="openItemSheet\(row\.item\)"/); assert.match(sidebarSource, /v-for="row in entryRows\.item\.value"[\s\S]*?@click="openItemSheet\(row\.item\)"/);
assert.match(sidebarSource, /CreateWindow\(['"]item_sheet['"],\s*\{ item \}\)/); assert.match(sidebarSource, /CreateWindow\(['"]item_sheet['"],\s*\{ item \}\)/);
assert.doesNotMatch(sidebarSource, /toggleEntryDetails/); assert.doesNotMatch(sidebarSource, /toggleEntryDetails/);
}); });

View File

@@ -85,6 +85,9 @@ function loadMapRoutes({ ownsCampaign = true, maps = [], notes = [] } = {}) {
}, },
// The pins do not ask after actors, only the token routes below do. // The pins do not ask after actors, only the token routes below do.
"../models/Actor": { findOne: () => mongooseQuery(null) }, "../models/Actor": { findOne: () => mongooseQuery(null) },
// The map list's own folder tree: `/list` reads it and `/update` checks a move
// against it, so the pins need the model to answer, never what it answers.
"../models/Folder": { find: () => mongooseQuery([]), belongsToSection: async () => true },
}); });
} }
@@ -181,7 +184,12 @@ function loadNoteRoutes({ ownsCampaign = true, notes = [], folders = [], deleted
findById: (id) => mongooseQuery(notes.find((note) => note._id === id) ?? null), findById: (id) => mongooseQuery(notes.find((note) => note._id === id) ?? null),
deleteOne: () => mongooseQuery({ deletedCount }), deleteOne: () => mongooseQuery({ deletedCount }),
}, },
"../models/Folder": { find: () => mongooseQuery(folders) }, "../models/Folder": {
find: () => mongooseQuery(folders),
// models/Folder.js: the note tree is every folder that is not one of the other
// campaign lists, whose rows carry no target at all.
filterForTarget: (target) => (target === "note" ? { target: { $nin: ["actor", "item", "map"] } } : { target }),
},
"../models/Map": { "../models/Map": {
// The driver drops the pins of the note from every map holding one; what is worth // The driver drops the pins of the note from every map holding one; what is worth
// keeping here is the filter it is asked to do that with. // keeping here is the filter it is asked to do that with.

View File

@@ -82,6 +82,9 @@ function loadMapRoutes({ ownsCampaign = true, maps = [], actors = [] } = {}) {
: null : null
), ),
}, },
// The map list's own folder tree: `/list` reads it and `/update` checks a move
// against it, so the tokens need the model to answer, never what it answers.
"../models/Folder": { find: () => mongooseQuery([]), belongsToSection: async () => true },
}); });
} }
@@ -188,6 +191,8 @@ function loadActorRoutes({ ownsCampaign = true, actors = [], deletedCount = 1 }
return { modifiedCount: 1 }; return { modifiedCount: 1 };
}, },
}, },
// The actor list's own folder tree, which the delete does not ask after.
"../models/Folder": { find: () => mongooseQuery([]), belongsToSection: async () => true },
}); });
return { api, tokensPulled }; return { api, tokensPulled };
} }
@@ -299,10 +304,14 @@ function mapViewerTokenWiringTests() {
const sidebar = readRepoFile("frontend", "app", "components", "partials", "ContentSidebar.vue"); const sidebar = readRepoFile("frontend", "app", "components", "partials", "ContentSidebar.vue");
test("an actor row of the sidebar can be dragged out of it", () => { test("an actor row of the sidebar can be dragged out of it", () => {
const actorRow = /<div v-for="actor in actors"[^>]*>/.exec(sidebar)?.[0]; // The actors' block of the sidebar: since the entry lists got their folders the rows
// come from that tree, so the actor row holds its actor as `row.item`.
const actorSection = /<template v-else-if="activeSection === 'actors'">([\s\S]*?)<\/template>\s*\n\s*<template v-else-if="activeSection === 'items'">/
.exec(sidebar)?.[1] ?? "";
const actorRow = /<div v-else class="entity-entry"[^>]*>/.exec(actorSection)?.[0];
assert.ok(actorRow, "expected the actor rows of the sidebar"); assert.ok(actorRow, "expected the actor rows of the sidebar");
assert.match(actorRow, /draggable="true"/); assert.match(actorRow, /draggable="true"/);
assert.match(actorRow, /@dragstart="startActorDrag\(\$event, actor\)"/); assert.match(actorRow, /@dragstart="startActorDrag\(\$event, row\.item\)"/);
assert.match(sidebar, /setData\(ACTOR_DRAG_TYPE, String\(actor\._id\)\)/); assert.match(sidebar, /setData\(ACTOR_DRAG_TYPE, String\(actor\._id\)\)/);
}); });