390 lines
18 KiB
JavaScript
390 lines
18 KiB
JavaScript
// Tests for the notes pinned onto a map (Syndria98/dragonroll#20): right clicking a map pins one of
|
|
// the campaign notes at that spot, and clicking the marker reads the linked note in a window.
|
|
//
|
|
// The repository root installs no dependencies, so both sides are loaded into `node:vm` contexts.
|
|
// The express routers run against a stubbed `require` (express itself, multer and the mongoose
|
|
// models) answering with plain objects: that keeps the ownership, same-campaign and dedup rules of
|
|
// POST /map/pin observable without a database. `frontend/app/services/MapPins.js` holds the image ↔
|
|
// screen translation and the note picker labels, and is loaded the way map-viewer.test.js loads
|
|
// Content.js. The last checks read the template of the map viewer, because there the wiring itself
|
|
// 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;
|
|
}
|
|
|
|
// Loads an express router file with every module it requires stubbed out: `stubs` maps a require
|
|
// path ("../models/Map") to the module the route should see.
|
|
function loadRouter(relativeParts, stubs) {
|
|
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 };
|
|
if (id === "../services/storage") return { single: () => (req, res, next) => next() };
|
|
if (!(id in stubs)) throw new Error(`require("${id}") is not stubbed`);
|
|
return stubs[id];
|
|
};
|
|
|
|
// Both files only need `require`, `module` and `exports`, so they are compiled as functions in
|
|
// the realm of the tests: the objects the routes build are then plain host objects to assert on.
|
|
const moduleStub = { exports: {} };
|
|
vm.compileFunction(readRepoFile(...relativeParts), ["require", "module", "exports"])(
|
|
requireStub, moduleStub, moduleStub.exports
|
|
);
|
|
|
|
async function call(route, { body = {}, query = {}, params = {}, user = { id: "user-1" } } = {}) {
|
|
const handlers = routes.get(route);
|
|
assert.ok(handlers, `${route} is not mounted`);
|
|
const res = { payload: null, json(payload) { this.payload = payload; } };
|
|
// The multer middleware the routes mount is stubbed away, so the handler is the last one.
|
|
await handlers[handlers.length - 1]({ body, query, params, user }, res);
|
|
return res.payload;
|
|
}
|
|
|
|
return { routes, call };
|
|
}
|
|
|
|
function makeMap(pins = []) {
|
|
return { _id: "map-1", campaign: "campaign-1", pins, save: async () => {} };
|
|
}
|
|
|
|
function loadMapRoutes({ ownsCampaign = true, maps = [], notes = [] } = {}) {
|
|
return loadRouter(["backend", "src", "routes", "map.js"], {
|
|
"../models/Campaign": { findOne: () => mongooseQuery(ownsCampaign ? { _id: "campaign-1" } : null) },
|
|
"../models/Map": { findById: (id) => mongooseQuery(maps.find((map) => map._id === id) ?? null) },
|
|
"../models/Note": {
|
|
findOne: (filter) => mongooseQuery(
|
|
notes.some((note) => note._id === String(filter._id) && String(note.campaign) === String(filter.campaign))
|
|
? { _id: String(filter._id) }
|
|
: null
|
|
),
|
|
},
|
|
// The pins do not ask after actors, only the token routes below do.
|
|
"../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 },
|
|
});
|
|
}
|
|
|
|
function mapPinRouteTests() {
|
|
test("pinning a note stores it at the spot that was clicked", async () => {
|
|
const map = makeMap();
|
|
const api = loadMapRoutes({ maps: [map], notes: [{ _id: "note-1", campaign: "campaign-1" }] });
|
|
|
|
const response = await api.call("POST /pin", { body: { id: "map-1", note: "note-1", x: 420, y: 96 } });
|
|
|
|
assert.equal(response.status, "ok");
|
|
assert.deepEqual(map.pins, [{ note: "note-1", x: 420, y: 96 }]);
|
|
});
|
|
|
|
test("a pin keeps whole image pixels and never goes off the top left corner", async () => {
|
|
const map = makeMap();
|
|
const api = loadMapRoutes({ maps: [map], notes: [{ _id: "note-1", campaign: "campaign-1" }] });
|
|
|
|
// Coordinates arrive as strings from a multipart form, and a drag can leave the image.
|
|
await api.call("POST /pin", { body: { id: "map-1", note: "note-1", x: "120.6", y: -8 } });
|
|
|
|
assert.deepEqual(map.pins, [{ note: "note-1", x: 121, y: 0 }]);
|
|
});
|
|
|
|
test("a note of another campaign cannot be pinned onto a map", async () => {
|
|
const map = makeMap();
|
|
const api = loadMapRoutes({ maps: [map], notes: [{ _id: "note-2", campaign: "campaign-2" }] });
|
|
|
|
const response = await api.call("POST /pin", { body: { id: "map-1", note: "note-2", x: 10, y: 10 } });
|
|
|
|
assert.equal(response.msg, "errors.notfound");
|
|
assert.deepEqual(map.pins, []);
|
|
});
|
|
|
|
test("a map of somebody else's campaign answers unauthorized", async () => {
|
|
const map = makeMap();
|
|
const api = loadMapRoutes({ ownsCampaign: false, maps: [map], notes: [{ _id: "note-1", campaign: "campaign-1" }] });
|
|
|
|
const response = await api.call("POST /pin", { body: { id: "map-1", note: "note-1", x: 10, y: 10 } });
|
|
|
|
assert.equal(response.msg, "unauthorized");
|
|
assert.deepEqual(map.pins, []);
|
|
});
|
|
|
|
test("pinning a note again moves its marker instead of adding a twin", async () => {
|
|
const map = makeMap([{ _id: "pin-1", note: "note-1", x: 10, y: 10 }]);
|
|
const api = loadMapRoutes({ maps: [map], notes: [{ _id: "note-1", campaign: "campaign-1" }] });
|
|
|
|
await api.call("POST /pin", { body: { id: "map-1", note: "note-1", x: 300, y: 220 } });
|
|
|
|
assert.equal(map.pins.length, 1);
|
|
assert.deepEqual({ ...map.pins[0] }, { _id: "pin-1", note: "note-1", x: 300, y: 220 });
|
|
});
|
|
|
|
test("pinning needs both a map and a note", async () => {
|
|
const map = makeMap();
|
|
const api = loadMapRoutes({ maps: [map], notes: [{ _id: "note-1", campaign: "campaign-1" }] });
|
|
|
|
assert.equal((await api.call("POST /pin", { body: { note: "note-1", x: 1, y: 1 } })).msg, "errors.missing-data");
|
|
assert.equal((await api.call("POST /pin", { body: { id: "map-1", x: 1, y: 1 } })).msg, "errors.missing-data");
|
|
assert.deepEqual(map.pins, []);
|
|
});
|
|
|
|
test("unpin removes the pin it is given and keeps the others", async () => {
|
|
const map = makeMap([
|
|
{ _id: "pin-1", note: "note-1", x: 10, y: 10 },
|
|
{ _id: "pin-2", note: "note-2", x: 20, y: 20 },
|
|
]);
|
|
const api = loadMapRoutes({ maps: [map], notes: [] });
|
|
|
|
const response = await api.call("POST /unpin", { body: { id: "map-1", pin: "pin-1" } });
|
|
|
|
assert.equal(response.status, "ok");
|
|
assert.deepEqual(map.pins.map((pin) => pin._id), ["pin-2"]);
|
|
});
|
|
|
|
test("unpin of a map of somebody else keeps its pins", async () => {
|
|
const map = makeMap([{ _id: "pin-1", note: "note-1", x: 10, y: 10 }]);
|
|
const api = loadMapRoutes({ ownsCampaign: false, maps: [map] });
|
|
|
|
const response = await api.call("POST /unpin", { body: { id: "map-1", pin: "pin-1" } });
|
|
|
|
assert.equal(response.msg, "unauthorized");
|
|
assert.equal(map.pins.length, 1);
|
|
});
|
|
}
|
|
|
|
function loadNoteRoutes({ ownsCampaign = true, notes = [], folders = [], deletedCount = 1 } = {}) {
|
|
const pinsPulled = [];
|
|
const api = loadRouter(["backend", "src", "routes", "note.js"], {
|
|
"../models/Campaign": { findOne: () => mongooseQuery(ownsCampaign ? { _id: "campaign-1" } : null) },
|
|
"../models/Note": {
|
|
find: () => mongooseQuery(notes),
|
|
findById: (id) => mongooseQuery(notes.find((note) => note._id === id) ?? null),
|
|
deleteOne: () => mongooseQuery({ deletedCount }),
|
|
},
|
|
"../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": {
|
|
// 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.
|
|
updateMany: async (filter, update) => {
|
|
pinsPulled.push({ filter, update });
|
|
return { modifiedCount: 1 };
|
|
},
|
|
},
|
|
});
|
|
return { api, pinsPulled };
|
|
}
|
|
|
|
function campaignNotesTests() {
|
|
const notes = [
|
|
{ _id: "note-1", title: "The Altar", folder: "folder-2" },
|
|
{ _id: "note-2", title: "The Inn", folder: null },
|
|
];
|
|
const folders = [
|
|
{ _id: "folder-1", name: "Undercity" },
|
|
{ _id: "folder-2", name: "Temple", parentFolder: "folder-1" },
|
|
];
|
|
|
|
test("the note picker answers with every note and the folders they live in", async () => {
|
|
const { api } = loadNoteRoutes({ notes, folders });
|
|
|
|
const response = await api.call("GET /all", { query: { campaign: "campaign-1" } });
|
|
|
|
assert.equal(response.status, "ok");
|
|
assert.deepEqual(response.notes.map((note) => note.title), ["The Altar", "The Inn"]);
|
|
assert.deepEqual(response.folders.map((folder) => folder.name), ["Undercity", "Temple"]);
|
|
});
|
|
|
|
test("the note picker needs a campaign, and only of one's own", async () => {
|
|
const { api } = loadNoteRoutes({ notes, folders });
|
|
const { api: foreignCampaign } = loadNoteRoutes({ ownsCampaign: false, notes, folders });
|
|
|
|
assert.equal((await api.call("GET /all")).msg, "errors.missing-data");
|
|
assert.equal((await foreignCampaign.call("GET /all", { query: { campaign: "campaign-1" } })).msg, "unauthorized");
|
|
});
|
|
|
|
test("a note can be read on its own, the way a map pin asks for it", async () => {
|
|
const { api } = loadNoteRoutes({ notes: [{ _id: "note-1", title: "The Altar", content: "## The altar" }] });
|
|
|
|
const response = await api.call("GET /retrieve/:id", { params: { id: "note-1" } });
|
|
|
|
assert.equal(response.status, "ok");
|
|
assert.equal(response.note.content, "## The altar");
|
|
});
|
|
|
|
test("a note of a campaign the user does not own cannot be read", async () => {
|
|
const { api } = loadNoteRoutes({ ownsCampaign: false, notes: [{ _id: "note-1", title: "The Altar" }] });
|
|
|
|
const response = await api.call("GET /retrieve/:id", { params: { id: "note-1" } });
|
|
|
|
assert.equal(response.msg, "unauthorized");
|
|
});
|
|
|
|
test("deleting a note pulls the pins pointing at it", async () => {
|
|
const { api, pinsPulled } = loadNoteRoutes({ notes: [{ _id: "note-1", title: "The Altar" }] });
|
|
|
|
const response = await api.call("POST /delete", { body: { id: "note-1" } });
|
|
|
|
assert.equal(response.status, "ok");
|
|
assert.deepEqual(pinsPulled, [{ filter: { "pins.note": "note-1" }, update: { $pull: { pins: { note: "note-1" } } } }]);
|
|
});
|
|
|
|
test("deleting a note that is not there does not touch any map", async () => {
|
|
const { api, pinsPulled } = loadNoteRoutes({ notes: [], deletedCount: 0 });
|
|
|
|
const response = await api.call("POST /delete", { body: { id: "note-9" } });
|
|
|
|
assert.equal(response.msg, "errors.notfound");
|
|
assert.deepEqual(pinsPulled, []);
|
|
});
|
|
}
|
|
|
|
function loadMapPinsService() {
|
|
const source = readRepoFile("frontend", "app", "services", "MapPins.js");
|
|
const body = source
|
|
.replace(/import\s*\{[^}]*\}\s*from\s*['"]vue['"];?/, "")
|
|
.replace(/export\s*\{/, "return {")
|
|
.concat("\n;");
|
|
|
|
return vm.compileFunction(body, [])();
|
|
}
|
|
|
|
function mapPinsServiceTests() {
|
|
const service = loadMapPinsService();
|
|
// 800x600 image, shown at 200% and panned so its top left corner sits at (20, 10) of the viewport.
|
|
const view = { zoom: 2, pan: { x: 20, y: 10 }, width: 800, height: 600 };
|
|
|
|
test("a spot of the viewport becomes the pixel of the image it stands for", () => {
|
|
assert.deepEqual(service.ToImagePoint({ x: 100, y: 50 }, view), { x: 40, y: 20 });
|
|
});
|
|
|
|
test("spots outside the image pin nothing", () => {
|
|
assert.equal(service.ToImagePoint({ x: 10, y: 50 }, view), null);
|
|
assert.equal(service.ToImagePoint({ x: 100, y: -5 }, view), null);
|
|
assert.equal(service.ToImagePoint({ x: 1700, y: 50 }, view), null);
|
|
});
|
|
|
|
test("without a loaded image there is no spot to pin", () => {
|
|
assert.equal(service.ToImagePoint({ x: 100, y: 50 }, { zoom: 1, pan: { x: 0, y: 0 }, width: 0, height: 0 }), null);
|
|
assert.equal(service.ToImagePoint({ x: 100, y: 50 }, undefined), null);
|
|
});
|
|
|
|
test("a pin lands on the same spot of the screen it was placed at", () => {
|
|
// An even spot: the image pixels of a pin are rounded, so the round trip is exact there.
|
|
const spot = service.ToImagePoint({ x: 370, y: 124 }, view);
|
|
assert.deepEqual(spot, { x: 175, y: 57 });
|
|
assert.deepEqual(service.ToScreenPoint(spot, view), { x: 370, y: 124 });
|
|
});
|
|
|
|
test("pins follow the map but keep their own size", () => {
|
|
// Only the position scales: the marker itself is drawn outside of the scaled stage.
|
|
assert.deepEqual(service.ToScreenPoint({ x: 40, y: 20 }, { ...view, zoom: 4 }), { x: 180, y: 90 });
|
|
assert.deepEqual(service.ToScreenPoint({ x: 40, y: 20 }, { ...view, pan: { x: -40, y: 0 } }), { x: 40, y: 40 });
|
|
});
|
|
|
|
test("notes of a folder are labelled with where they live", () => {
|
|
const options = service.BuildNoteOptions(
|
|
[{ _id: "note-1", title: "The Altar", folder: "folder-2" }, { _id: "note-2", title: "The Inn", folder: null }],
|
|
[{ _id: "folder-1", name: "Undercity" }, { _id: "folder-2", name: "Temple", parentFolder: "folder-1" }]
|
|
);
|
|
|
|
assert.deepEqual(options.map((option) => option.label), ["The Inn", "Undercity / Temple / The Altar"]);
|
|
assert.equal(options.find((option) => option.value === "note-1").path, "Undercity / Temple");
|
|
});
|
|
|
|
test("the picker is sorted by the label it shows, not by the bare title", () => {
|
|
const options = service.BuildNoteOptions(
|
|
[{ _id: "note-1", title: "Bridge", folder: null }, { _id: "note-2", title: "Altar", folder: "folder-1" }],
|
|
[{ _id: "folder-1", name: "Cave" }]
|
|
);
|
|
|
|
// "Altar" would lead the menu by title, but it is nowhere near it once its folder is named.
|
|
assert.deepEqual(options.map((option) => option.value), ["note-1", "note-2"]);
|
|
});
|
|
|
|
test("a note without a title is left out of the picker", () => {
|
|
const options = service.BuildNoteOptions([{ _id: "note-1", title: " " }], []);
|
|
|
|
assert.deepEqual(options, []);
|
|
});
|
|
|
|
test("a broken folder chain cannot loop the picker", () => {
|
|
const options = service.BuildNoteOptions(
|
|
[{ _id: "note-1", title: "The Altar", folder: "folder-1" }],
|
|
[{ _id: "folder-1", name: "One", parentFolder: "folder-2" }, { _id: "folder-2", name: "Two", parentFolder: "folder-1" }]
|
|
);
|
|
|
|
assert.equal(options[0].label, "Two / One / The Altar");
|
|
});
|
|
|
|
test("renaming a note keeps the folder path of its label", () => {
|
|
const option = { value: "note-1", title: "The Altar", path: "Undercity / Temple" };
|
|
option.title = "The Ruined Altar";
|
|
|
|
assert.equal(service.OptionLabel(option), "Undercity / Temple / The Ruined Altar");
|
|
});
|
|
}
|
|
|
|
function mapViewerWiringTests() {
|
|
const pane = readRepoFile("frontend", "app", "components", "viewer", "map", "MapViewerPane.vue");
|
|
const definitions = readRepoFile("frontend", "app", "services", "WindowDefinitions.js");
|
|
const windowSource = readRepoFile("frontend", "app", "components", "windows", "PinnedNoteWindow.vue");
|
|
|
|
test("right clicking the map opens the pin menu", () => {
|
|
const viewport = /<div[^>]*ref="viewport"[^>]*>/.exec(pane)?.[0];
|
|
assert.ok(viewport, "expected the map viewport element");
|
|
assert.match(viewport, /@contextmenu\.prevent="onMapContextMenu"/);
|
|
});
|
|
|
|
test("pins are drawn in screen space and only they catch the mouse", () => {
|
|
// Inside the scaled stage the markers would shrink and grow with the map instead of staying
|
|
// where they were placed; the overlay must not take the mouse away from panning.
|
|
assert.match(pane, /class="map-pin"[^>]*:style="pinStyle\(pin\)"/);
|
|
assert.match(pane, /\.map-pins\s*\{[^}]*pointer-events:\s*none/);
|
|
assert.match(pane, /\.map-pin\s*\{[^}]*pointer-events:\s*auto/);
|
|
});
|
|
|
|
test("a pin opens the linked note and does not start a pan", () => {
|
|
assert.match(pane, /@pointerdown\.stop/);
|
|
assert.match(pane, /@click="openPinnedNote\(pin\)"/);
|
|
assert.match(pane, /CreateWindow\('pinned_note'/);
|
|
});
|
|
|
|
test("the pinned note window is registered and reads the note from the server", () => {
|
|
assert.match(definitions, /pinned_note:\s*\{[^}]*windows\.pinned-note[^}]*PinnedNoteWindow\.vue/s);
|
|
assert.match(windowSource, /get\(`\/note\/retrieve\/\$\{noteId\}`\)/);
|
|
});
|
|
}
|
|
|
|
mapPinRouteTests();
|
|
campaignNotesTests();
|
|
mapPinsServiceTests();
|
|
mapViewerWiringTests();
|