Files
dragonroll/tests/entry-folders.test.js
Gitea OpenCode Agent cd92a2d112
Some checks failed
Test / test (push) Failing after 2s
Fix issue #49: Unify folder system
2026-10-15 12:11:19 +00:00

445 lines
21 KiB
JavaScript

// Tests for the folder system shared by every campaign list (Syndria98/dragonroll#49):
// folders are created, renamed, coloured and deleted for the actors, the items and the
// maps as well as for the notes, and each list only ever shows the folders of its own.
//
// The repository root installs no dependencies, so each side is loaded the way the other
// tests do it. The routes run against a stubbed `require` (express and the models answer
// with plain objects and a small filter matcher) — except the Folder model's own logic,
// which is read out of the real model file so its target filter is the one under test. The
// frontend services are plain ES modules and are read as text, and the sidebar is read as
// text too, the way tests/sidebar-entity-entry.test.js reads it.
//
// 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 read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
// --- Enough of the query language the folder routes use --------------------------
function matches(document, filter = {}) {
return Object.entries(filter).every(([key, expected]) => {
if (key === "$or") return expected.some((part) => matches(document, part));
const value = document?.[key];
if (expected && typeof expected === "object" && !Array.isArray(expected) && !(expected instanceof Date)) {
return Object.entries(expected).every(([operator, wanted]) => {
// A row without the field at all counts as "not one of these", which is
// how MongoDB's $nin keeps the note folders saved before `target` existed.
if (operator === "$ne") return String(value ?? "") !== String(wanted ?? "");
if (operator === "$in") return wanted.some((entry) => String(value ?? "") === String(entry ?? ""));
if (operator === "$nin") return !wanted.some((entry) => String(value ?? "") === String(entry ?? ""));
if (operator === "$exists") return (value !== undefined && value !== null) === wanted;
throw new Error(`filter operator "${key}.${operator}" is not stubbed`);
});
}
return String(value ?? "") === String(expected ?? "");
});
}
function mongooseQuery(rows) {
const result = {
select: () => result,
sort: () => result,
limit: (count) => mongooseQuery(rows.slice(0, count)),
lean: () => Promise.resolve(rows),
then: (onFulfilled, onRejected) => Promise.resolve(rows).then(onFulfilled, onRejected),
};
return result;
}
function fakeCollection(name, seed = []) {
const rows = [];
let counter = 0;
function Document(data = {}) {
counter += 1;
this._id = `${name}-${counter}`;
this.isNew = true;
Object.assign(this, data);
}
Document.prototype.save = async function save() {
if (this.isNew) rows.push(this);
this.isNew = false;
return this;
};
Object.defineProperty(Document.prototype, "id", { get() { return this._id; } });
function seedRow(data) {
const row = new Document(data);
row.isNew = false;
rows.push(row);
return row;
}
for (const data of seed) seedRow(data);
const model = function Model(data) { return new Document(data); };
model.rows = rows;
model.seed = seedRow;
model.find = (filter) => mongooseQuery(rows.filter((row) => matches(row, filter)));
// A row that answers both when awaited and through `.lean()`, because the routes read
// some of their lookups one way and some the other.
const one = (row) => Object.assign(Promise.resolve(row ?? null), { lean: () => Promise.resolve(row ?? null) });
model.findOne = (filter) => one(rows.find((document) => matches(document, filter)));
model.findById = (id) => one(rows.find((document) => String(document._id) === String(id)));
model.deleteOne = async (filter) => {
const hit = rows.filter((row) => matches(row, filter));
for (const row of hit) rows.splice(rows.indexOf(row), 1);
return { deletedCount: hit.length };
};
model.updateMany = async (filter, update) => {
const hit = rows.filter((row) => matches(row, filter));
for (const row of hit) Object.assign(row, update.$set ?? {});
return { modifiedCount: hit.length };
};
return model;
}
// --- The real Folder model's own logic, over a stubbed mongoose -------------------
// The model file's statics (`filterForTarget`, `isTarget`, `belongsToSection`) and the
// `target` enum, read out of the file with a mongoose that only builds a schema. What the
// routes ask for is therefore the code under test, not a copy of it.
function realFolderModel(seed = []) {
let definition = null;
function Schema(schemaDefinition) {
definition = schemaDefinition;
this.statics = {};
}
Schema.prototype.index = function index() {};
Schema.Types = { ObjectId: "ObjectId" };
const mongoose = {
Schema,
isValidObjectId: (value) => typeof value === "string" && value.length > 0,
model: (name, schema) => Object.assign(function Model() {}, schema.statics),
};
const moduleStub = { exports: {} };
vm.compileFunction(read("backend", "src", "models", "Folder.js"), ["require", "module"])(
(id) => {
if (id === "mongoose") return mongoose;
throw new Error(`require("${id}") is not stubbed`);
},
moduleStub
);
const collection = fakeCollection("folder", seed);
const model = Object.assign(collection, moduleStub.exports);
model.definition = () => definition;
return model;
}
// --- Routes against stubbed models ----------------------------------------------
function loadRoute(file, models) {
const routes = new Map();
const router = {
get: (route, ...handlers) => routes.set(`GET ${route}`, handlers),
post: (route, ...handlers) => routes.set(`POST ${route}`, handlers),
};
const requireStub = (id) => {
if (id === "express") return { Router: () => router };
// The image upload middleware: the folder routes never see a file.
if (id === "../services/storage") return { single: () => (req, res, next) => next() };
if (models[id]) return models[id];
throw new Error(`require("${id}") is not stubbed`);
};
const moduleStub = { exports: {} };
vm.compileFunction(read("backend", "src", "routes", file), ["require", "module", "exports"])(
requireStub, moduleStub, moduleStub.exports
);
return async function call(route, { body = {}, query = {} } = {}) {
const handlers = routes.get(route);
assert.ok(handlers, `${route} is not mounted`);
const res = { payload: null, json(payload) { this.payload = payload; } };
await handlers[handlers.length - 1]({ body, query, user: { id: "user-1" } }, res);
return res.payload;
};
}
// The routes share one set of tables, the way the API does: a folder deleted through
// `/folder/delete` has to empty the rows pointing at it in each of them.
function campaign({ folders = [], notes = [], actors = [], items = [], maps = [] } = {}) {
const campaignDoc = { _id: "campaign-1", id: "campaign-1", createdBy: "user-1" };
const collections = {
// Folders belong to the campaign the tests run their requests against unless a
// seed says otherwise.
Folder: realFolderModel(folders.map((folder) => ({ campaign: "campaign-1", ...folder }))),
Note: fakeCollection("note", notes),
Actor: fakeCollection("actor", actors),
Item: fakeCollection("item", items),
Map: fakeCollection("map", maps),
};
const models = {
// `userOwnsCampaign` reads the campaign through `findOne(...).lean()`.
"../models/Campaign": { findOne: () => ({ lean: async () => campaignDoc }) },
"../models/Folder": collections.Folder,
"../models/Note": collections.Note,
"../models/Actor": collections.Actor,
"../models/Item": collections.Item,
"../models/Map": collections.Map,
};
return { call: (file) => loadRoute(file, models), collections };
}
// --- Every list gets a folder of its own ----------------------------------------
test("a folder is made for the campaign list the sidebar names", async () => {
const { collections, call } = campaign();
const create = await call("folder.js");
for (const target of ["actor", "item", "map"]) {
const response = await create("POST /create", { body: { name: `${target} folder`, campaign: "campaign-1", target } });
assert.equal(response.status, "ok");
assert.equal(response.folder.target, target, `${target} folders are filed as such`);
}
assert.deepEqual(collections.Folder.rows.map((folder) => folder.target), ["actor", "item", "map"]);
});
test("a folder made without a target belongs to the notes, as it always did", async () => {
const { collections, call } = campaign();
const response = await call("folder.js")("POST /create", { body: { name: "Lore", campaign: "campaign-1" } });
assert.equal(response.status, "ok");
assert.equal(collections.Folder.rows[0].target, "note");
});
test("the notes keep the folders saved before the model knew about targets", async () => {
const legacy = { _id: "folder-legacy", name: "Old lore" };
const { collections, call } = campaign({
folders: [legacy, { _id: "folder-actors", name: "Adventurers", target: "actor" }],
});
const notes = await call("note.js")("GET /list", { query: { campaign: "campaign-1" } });
const listed = await call("folder.js")("GET /list", { query: { campaign: "campaign-1" } });
assert.equal(notes.status, "ok");
assert.deepEqual(notes.folders.map((folder) => folder._id), ["folder-legacy"], "the notes tree shows its own folders only");
assert.deepEqual(listed.folders.map((folder) => folder._id), ["folder-legacy"], "and a request naming no target means the notes");
assert.deepEqual(collections.Folder.rows.length, 2, "the actor folder is left alone, it is another list's");
});
test("a list answers with the folders of its own section", async () => {
const { call } = campaign({
folders: [
{ _id: "folder-note", name: "Lore", target: "note" },
{ _id: "folder-actor", name: "Adventurers", target: "actor" },
{ _id: "folder-item", name: "Gear", target: "item" },
{ _id: "folder-map", name: "Regions", target: "map" },
],
});
for (const [target, ids] of [["note", ["folder-note"]], ["actor", ["folder-actor"]], ["item", ["folder-item"]], ["map", ["folder-map"]]]) {
const response = await call("folder.js")("GET /list", { query: { campaign: "campaign-1", target } });
assert.deepEqual(response.folders.map((folder) => folder._id), ids, `${target} folders only`);
}
});
test("a folder is not made for a list that does not exist", async () => {
const { collections, call } = campaign();
const response = await call("folder.js")("POST /create", { body: { name: "Nowhere", campaign: "campaign-1", target: "spell" } });
assert.equal(response.status, "error");
assert.equal(response.msg, "errors.missing-data");
assert.deepEqual(collections.Folder.rows, []);
});
test("the actor, item and map lists send the tree their rows stand in", async () => {
const { call } = campaign({
folders: [{ _id: "folder-actor", name: "Adventurers", target: "actor", color: "#e74c3c" }],
actors: [{ _id: "actor-1", name: "Thalia", campaign: "campaign-1" }],
items: [{ _id: "item-1", name: "Longsword", campaign: "campaign-1" }],
maps: [{ _id: "map-1", name: "Crossroads", campaign: "campaign-1" }],
});
for (const [file, key] of [["actor.js", "actors"], ["item.js", "items"], ["map.js", "maps"]]) {
const response = await call(file)("GET /list", { query: { campaign: "campaign-1" } });
assert.equal(response.status, "ok");
assert.equal(response[key].length, 1);
assert.ok(Array.isArray(response.folders), `${file} sends its folders along`);
}
});
// --- Filing rows, and emptying a folder that goes away ---------------------------
test("an actor, an item and a map each move into a folder of their own list", async () => {
const { collections, call } = campaign({
folders: [
{ _id: "folder-actor", name: "Adventurers", target: "actor" },
{ _id: "folder-item", name: "Gear", target: "item" },
{ _id: "folder-map", name: "Regions", target: "map" },
],
actors: [{ _id: "actor-1", name: "Thalia", campaign: "campaign-1" }],
items: [{ _id: "item-1", name: "Longsword", campaign: "campaign-1" }],
maps: [{ _id: "map-1", name: "Crossroads", campaign: "campaign-1" }],
});
const actor = await call("actor.js")("POST /update", { body: { id: "actor-1", folder: "folder-actor" } });
const item = await call("item.js")("POST /update", { body: { id: "item-1", folder: "folder-item" } });
const map = await call("map.js")("POST /update", { body: { id: "map-1", folder: "folder-map" } });
assert.equal(actor.status, "ok");
assert.equal(String(actor.actor.folder), "folder-actor");
assert.equal(String(collections.Actor.rows[0].folder), "folder-actor");
assert.equal(String(item.item.folder), "folder-item");
assert.equal(String(map.map.folder), "folder-map");
});
test("a move refuses a folder of another list, or of another campaign", async () => {
const { collections, call } = campaign({
folders: [
{ _id: "folder-actor", name: "Adventurers", target: "actor" },
{ _id: "folder-item", name: "Gear", target: "item" },
{ _id: "folder-other", name: "Somebody else's", target: "actor", campaign: "campaign-2" },
],
actors: [{ _id: "actor-1", name: "Thalia", campaign: "campaign-1" }],
});
const update = await call("actor.js");
const wrongList = await update("POST /update", { body: { id: "actor-1", folder: "folder-item" } });
const wrongCampaign = await update("POST /update", { body: { id: "actor-1", folder: "folder-other" } });
assert.equal(wrongList.status, "error");
assert.equal(wrongList.msg, "errors.notfound");
assert.equal(wrongCampaign.status, "error");
assert.equal(collections.Actor.rows[0].folder, undefined, "the actor stays where it was");
const toRoot = await update("POST /update", { body: { id: "actor-1", folder: null } });
assert.equal(toRoot.status, "ok");
assert.equal(toRoot.actor.folder, null, "and the root of the list is always a valid target");
});
test("updating an entry that says nothing about folders leaves it where it stands", async () => {
const { collections, call } = campaign({
folders: [{ _id: "folder-actor", name: "Adventurers", target: "actor" }],
actors: [{ _id: "actor-1", name: "Thalia", campaign: "campaign-1", folder: "folder-actor" }],
});
const response = await call("actor.js")("POST /update", { body: { id: "actor-1", level: 3 } });
assert.equal(response.status, "ok");
assert.equal(String(collections.Actor.rows[0].folder), "folder-actor", "a sheet save does not file the actor away");
});
test("deleting a folder moves what stood in it to the root of every list", async () => {
const { collections, call } = campaign({
folders: [
{ _id: "folder-actor", name: "Adventurers", target: "actor" },
{ _id: "folder-actor-sub", name: "Family", target: "actor", parentFolder: "folder-actor" },
],
notes: [{ _id: "note-1", title: "Lore", campaign: "campaign-1", folder: "folder-actor-sub" }],
actors: [{ _id: "actor-1", name: "Thalia", campaign: "campaign-1", folder: "folder-actor" }],
items: [{ _id: "item-1", name: "Longsword", campaign: "campaign-1", folder: "folder-actor" }],
maps: [{ _id: "map-1", name: "Crossroads", campaign: "campaign-1", folder: "folder-actor-sub" }],
});
const response = await call("folder.js")("POST /delete", { body: { id: "folder-actor" } });
assert.equal(response.status, "ok");
assert.deepEqual(collections.Folder.rows, [], "the folder and the one nested in it are gone");
assert.equal(collections.Actor.rows[0].folder, null);
assert.equal(collections.Item.rows[0].folder, null);
assert.equal(collections.Map.rows[0].folder, null);
assert.equal(collections.Note.rows[0].folder, null);
});
// --- The frontend: one folder row, and a menu that works everywhere --------------
function loadEntryColorsService() {
const source = read("frontend", "app", "services", "EntryColors.js").replace(
"export { ENTRY_COLORS, BuildColorMenu };", "return { ENTRY_COLORS, BuildColorMenu };"
);
return vm.compileFunction(source)();
}
test("the colour menu offers the palette once, to every section", () => {
const { ENTRY_COLORS, BuildColorMenu } = loadEntryColorsService();
const picked = [];
const menu = BuildColorMenu((color) => picked.push(color), { defaultLabel: "No colour" });
assert.equal(menu.filter((item) => item.color).length, ENTRY_COLORS.length, "one swatch per preset colour");
assert.deepEqual(menu.at(-1).name, "No colour");
menu.at(-1).action();
assert.deepEqual(picked, [null], "and the last item takes the colour off");
menu[0].action();
assert.deepEqual(picked, [null, ENTRY_COLORS[0].value]);
// The notes' tree shares the palette instead of keeping its own copy.
const noteTree = read("frontend", "app", "components", "partials", "NestedNoteList.vue");
assert.match(noteTree, /import \{ BuildColorMenu \} from '~\/services\/EntryColors'/);
assert.doesNotMatch(noteTree, /const entryColors = /, "the note tree has no palette of its own");
});
test("every entry section files its rows under folder rows", () => {
const sidebar = read("frontend", "app", "components", "partials", "ContentSidebar.vue");
// The three entry lists are each built from their own folders and rendered with the
// folder row, which is how the item list already did it.
for (const kind of ["actor", "item", "map"]) {
assert.match(sidebar, new RegExp(`${kind}: computed\\(\\(\\) => BuildItemRows\\(${kind}s\\.value, entryFolders\\.${kind}\\.value, collapsedFolderIds\\.value\\)\\)`));
}
assert.equal(sidebar.match(/<EntryFolderRow/g)?.length, 3, "each entry section renders folder rows");
assert.match(sidebar, /entryFolders\[kind\]\.value = response\.data\.folders/, "each list reads the tree it is sent");
});
test("every entry section can create, rename, colour and delete a folder", () => {
const sidebar = read("frontend", "app", "components", "partials", "ContentSidebar.vue");
// The header's folder button names the list the folder belongs to; the notes ask for
// their own, and a click event must not slip in as the target.
assert.match(sidebar, /@click="createFolder\(\)"/);
assert.match(sidebar, /@click="createFolder\(entryEntityType\(activeSection\)\)"/);
assert.match(sidebar, /function createFolder\(target = 'note'\)/);
assert.match(sidebar, /CreateWindow\('new_folder', \{ campaign: campaignId\.value, target \}\)/);
// Rename, colour, delete: the same routes the note tree uses, so the same window and
// the same `/folder/*` calls serve every section.
assert.match(sidebar, /CreateWindow\('new_folder', \{ folderId: folder\._id, campaign: campaignId\.value, name: folder\.name \}\)/);
assert.match(sidebar, /Server\(\)\.post\('\/folder\/update', \{ id: folder\._id, color \}\)/);
assert.match(sidebar, /Server\(\)\.post\('\/folder\/delete', \{ id: folder\._id \}\)/);
// And an entry of any list can be filed into a folder, or back to the root.
assert.match(sidebar, /Server\(\)\.post\(`\/\$\{entityType\}\/update`, \{ id: entry\._id, folder: folderId \}\)/);
// The window hands the target to the API when making a folder.
const window = read("frontend", "app", "components", "windows", "NewFolderWindow.vue");
assert.match(window, /folderData\.target = data\.target \?\? 'note'/);
// A saved folder only appears in the list it belongs to.
assert.match(sidebar, /fetchCampaignEntries\(section, true\)/);
});
test("a folder row says what it is and shows the colour it was given", () => {
const row = read("frontend", "app", "components", "partials", "EntryFolderRow.vue");
assert.match(row, /:aria-expanded="\(!collapsed\)\.toString\(\)"/);
assert.match(row, /@click="emit\('toggle'\)"/);
assert.match(row, /@contextmenu\.prevent="ShowContextMenu\(menu\)"/);
assert.match(row, /folder\.color \? \{ '--entry-color': folder\.color \} : null/);
// The colour tints the row instead of replacing its text colours, the way notes and
// note folders do.
assert.match(row, /\.entry-folder-row\.has-color \{ background: color-mix\(in srgb, var\(--entry-color\)/);
});
test("every locale says what the folder menus do", () => {
const keys = ["toggle", "rename", "color", "default", "delete", "move-to", "root"];
for (const locale of ["en", "es", "ca"]) {
const campaigns = JSON.parse(read("frontend", "i18n", "locales", locale, "campaigns.json"));
for (const key of keys) {
assert.ok(campaigns.folders?.[key], `${locale} is missing campaigns.folders.${key}`);
}
}
});