Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
test(core): reduce flakiness in coverage
Elian Doranb90fc439ea28
diff --git a/packages/trilium-core/src/services/handlers.spec.ts b/packages/trilium-core/src/services/handlers.spec.tsnew file mode 100644index 0000000000..444984be64--- /dev/null+++ b/packages/trilium-core/src/services/handlers.spec.ts@@ -0,0 +1,218 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import becca from "../becca/becca.js";+import BAttribute from "../becca/entities/battribute.js";+import BBranch from "../becca/entities/bbranch.js";+import { buildNote } from "../test/becca_easy_mocking.js";+import config from "./config.js";+import eventService from "./events.js";+import handlers from "./handlers.js";+import hiddenSubtreeService from "./hidden_subtree.js";+import noteService from "./notes.js";+import oneTimeTimer from "./one_time_timer.js";+import scriptService from "./script.js";+import treeService from "./tree.js";+import { randomString } from "./utils/index.js";++// handlers.ts only subscribes to events at import time, so it is otherwise+// covered incidentally (whenever some unrelated test happens to fire one of+// these events), which makes its coverage flaky. These tests drive the handlers+// deterministically by emitting the events and spying on the downstream+// singletons (which handlers.ts holds direct references to).++function addAttribute(noteId: string, type: "label" | "relation", name: string, value: string) {+ return new BAttribute({ noteId, attributeId: randomString(12), type, name, value, position: 0, isInheritable: false });+}++describe("handlers", () => {+ const originalScriptingEnabled = config.Security.backendScriptingEnabled;++ let sortNotesIfNeeded: ReturnType<typeof vi.spyOn>;+ let executeNoteNoException: ReturnType<typeof vi.spyOn>;+ let duplicateSubtree: ReturnType<typeof vi.spyOn>;+ let scheduleExecution: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ becca.reset();+ buildNote({ id: "root", title: "root" });+ config.Security.backendScriptingEnabled = true;++ sortNotesIfNeeded = vi.spyOn(treeService, "sortNotesIfNeeded").mockImplementation(() => {});+ executeNoteNoException = vi.spyOn(scriptService, "executeNoteNoException").mockImplementation(() => {});+ duplicateSubtree = vi.spyOn(noteService, "duplicateSubtreeWithoutRoot").mockImplementation(() => {});+ scheduleExecution = vi.spyOn(oneTimeTimer, "scheduleExecution").mockImplementation(() => {});+ vi.spyOn(hiddenSubtreeService, "checkHiddenSubtree").mockImplementation(() => {});+ });++ afterEach(() => {+ vi.restoreAllMocks();+ config.Security.backendScriptingEnabled = originalScriptingEnabled;+ });++ describe("runAttachedRelations", () => {+ it("does nothing when backend scripting is disabled", () => {+ config.Security.backendScriptingEnabled = false;+ buildNote({ id: "target", type: "code", mime: "application/javascript;env=backend", content: "" });+ const note = buildNote({ id: "src" });+ addAttribute("src", "relation", "runOnNoteChange", "target");++ handlers.runAttachedRelations(note, "runOnNoteChange", note);+ expect(executeNoteNoException).not.toHaveBeenCalled();+ });++ it("executes each unique target note exactly once", () => {+ const target = buildNote({ id: "target", type: "code", mime: "application/javascript;env=backend", content: "" });+ const note = buildNote({ id: "src" });+ // Two relations pointing at the same target — must only execute once.+ addAttribute("src", "relation", "runOnNoteChange", "target");+ addAttribute("src", "relation", "runOnNoteChange", "target");++ handlers.runAttachedRelations(note, "runOnNoteChange", note);+ expect(executeNoteNoException).toHaveBeenCalledTimes(1);+ expect(executeNoteNoException).toHaveBeenCalledWith(target, expect.objectContaining({ originEntity: note }));+ });++ it("ignores relations whose target note is missing", () => {+ const note = buildNote({ id: "src" });+ addAttribute("src", "relation", "runOnNoteChange", "does-not-exist");++ handlers.runAttachedRelations(note, "runOnNoteChange", note);+ expect(executeNoteNoException).not.toHaveBeenCalled();+ });+ });++ describe("NOTE_TITLE_CHANGED", () => {+ it("runs runOnNoteTitleChange scripts", () => {+ const target = buildNote({ id: "t2", type: "code", mime: "application/javascript;env=backend", content: "" });+ const note = buildNote({ id: "s2" });+ addAttribute("s2", "relation", "runOnNoteTitleChange", "t2");++ eventService.emit(eventService.NOTE_TITLE_CHANGED, note);+ expect(executeNoteNoException).toHaveBeenCalledWith(target, expect.anything());+ });++ it("re-sorts a sorted parent", () => {+ buildNote({ id: "par2", children: [{ id: "chld2" }] });+ addAttribute("par2", "label", "sorted", "");+ const child = becca.notes["chld2"];+ expect(child).toBeDefined();++ eventService.emit(eventService.NOTE_TITLE_CHANGED, child);+ expect(sortNotesIfNeeded).toHaveBeenCalledWith("par2");+ });+ });++ describe("ENTITY_CHANGED (attributes)", () => {+ it("re-sorts the owning note when a 'sorted' label changes", () => {+ buildNote({ id: "p" });+ const attr = addAttribute("p", "label", "sorted", "");++ eventService.emit(eventService.ENTITY_CHANGED, { entityName: "attributes", entity: attr });+ expect(sortNotesIfNeeded).toHaveBeenCalledWith("p");+ });++ it("re-sorts the parent when a sort-affecting label (e.g. 'top') changes", () => {+ buildNote({ id: "par", children: [{ id: "chld" }] });+ addAttribute("par", "label", "sorted", "title");+ const topAttr = addAttribute("chld", "label", "top", "");++ eventService.emit(eventService.ENTITY_CHANGED, { entityName: "attributes", entity: topAttr });+ expect(sortNotesIfNeeded).toHaveBeenCalledWith("par");+ });+ });++ describe("ENTITY_CREATED (template relation)", () => {+ it("copies template content and subtree into an empty note", () => {+ buildNote({ id: "tmpl", type: "text", mime: "text/html", content: "TEMPLATE BODY" });+ const note = buildNote({ id: "n", type: "text", mime: "text/html", content: "" });+ const setContent = vi.spyOn(note, "setContent").mockImplementation(() => {});+ vi.spyOn(note, "save").mockReturnValue(note);+ const rel = addAttribute("n", "relation", "template", "tmpl");++ eventService.emit(eventService.ENTITY_CREATED, { entityName: "attributes", entity: rel });++ expect(setContent).toHaveBeenCalledWith("TEMPLATE BODY");+ expect(duplicateSubtree).toHaveBeenCalledWith("tmpl", "n");+ });+ });++ describe("ENTITY_DELETED", () => {+ it("reschedules a hidden-subtree check when a system ('_') note is deleted", () => {+ const sysNote = buildNote({ id: "_systemDeleted", title: "sys" });++ eventService.emit(eventService.ENTITY_DELETED, { entityName: "notes", entity: sysNote });+ expect(scheduleExecution).toHaveBeenCalledWith("hidden-subtree-check", expect.any(Number), expect.any(Function));+ });+ });++ describe("runOn* relation events", () => {+ function buildTargetAndSource(relationName: string, sourceId: string) {+ const target = buildNote({ id: `${sourceId}-tgt`, type: "code", mime: "application/javascript;env=backend", content: "" });+ const source = buildNote({ id: sourceId });+ addAttribute(sourceId, "relation", relationName, target.noteId);+ return { target, source };+ }++ it("runs runOnNoteContentChange when note content changes", () => {+ const { target, source } = buildTargetAndSource("runOnNoteContentChange", "ncc");+ eventService.emit(eventService.NOTE_CONTENT_CHANGE, { entity: source });+ expect(executeNoteNoException).toHaveBeenCalledWith(target, expect.anything());+ });++ it("runs runOnChildNoteCreation on the parent when a child is created", () => {+ const { target, source } = buildTargetAndSource("runOnChildNoteCreation", "cnc");+ const child = buildNote({ id: "cnc-child" });+ eventService.emit(eventService.CHILD_NOTE_CREATED, { parentNote: source, childNote: child });+ expect(executeNoteNoException).toHaveBeenCalledWith(target, expect.anything());+ });++ it("runs runOnNoteCreation when a note is created", () => {+ const { target, source } = buildTargetAndSource("runOnNoteCreation", "ncr");+ eventService.emit(eventService.ENTITY_CREATED, { entityName: "notes", entity: source });+ expect(executeNoteNoException).toHaveBeenCalledWith(target, expect.anything());+ });++ it("runs runOnAttributeCreation when an attribute is created", () => {+ const { target } = buildTargetAndSource("runOnAttributeCreation", "acr");+ const trigger = addAttribute("acr", "label", "someLabel", "");+ eventService.emit(eventService.ENTITY_CREATED, { entityName: "attributes", entity: trigger });+ expect(executeNoteNoException).toHaveBeenCalledWith(target, expect.anything());+ });++ it("runs runOnBranchCreation and re-sorts a sorted parent when a branch is created", () => {+ const target = buildNote({ id: "bcr-tgt", type: "code", mime: "application/javascript;env=backend", content: "" });+ const parent = buildNote({ id: "bcr-parent" });+ addAttribute("bcr-parent", "label", "sorted", "");+ buildNote({ id: "bcr-child" });+ addAttribute("bcr-child", "relation", "runOnBranchCreation", target.noteId);+ const branch = new BBranch({ noteId: "bcr-child", parentNoteId: parent.noteId, branchId: "bcr-parent_bcr-child" });++ eventService.emit(eventService.ENTITY_CREATED, { entityName: "branches", entity: branch });+ expect(executeNoteNoException).toHaveBeenCalledWith(target, expect.anything());+ expect(sortNotesIfNeeded).toHaveBeenCalledWith("bcr-parent");+ });++ it("runs runOnBranchChange and re-sorts a sorted parent when a branch changes", () => {+ const target = buildNote({ id: "bch-tgt", type: "code", mime: "application/javascript;env=backend", content: "" });+ const parent = buildNote({ id: "bch-parent" });+ addAttribute("bch-parent", "label", "sorted", "");+ buildNote({ id: "bch-child" });+ addAttribute("bch-child", "relation", "runOnBranchChange", target.noteId);+ const branch = new BBranch({ noteId: "bch-child", parentNoteId: parent.noteId, branchId: "bch-parent_bch-child" });++ eventService.emit(eventService.ENTITY_CHANGED, { entityName: "branches", entity: branch });+ expect(executeNoteNoException).toHaveBeenCalledWith(target, expect.anything());+ expect(sortNotesIfNeeded).toHaveBeenCalledWith("bch-parent");+ });++ it("runs runOnBranchDeletion when a branch is deleted", () => {+ const target = buildNote({ id: "bdl-tgt", type: "code", mime: "application/javascript;env=backend", content: "" });+ buildNote({ id: "bdl-child" });+ addAttribute("bdl-child", "relation", "runOnBranchDeletion", target.noteId);+ const branch = new BBranch({ noteId: "bdl-child", parentNoteId: "root", branchId: "root_bdl-child" });++ eventService.emit(eventService.ENTITY_DELETED, { entityName: "branches", entity: branch });+ expect(executeNoteNoException).toHaveBeenCalledWith(target, expect.anything());+ });+ });+});diff --git a/packages/trilium-core/src/services/scheduler.spec.ts b/packages/trilium-core/src/services/scheduler.spec.tsnew file mode 100644index 0000000000..5ddc39fdef--- /dev/null+++ b/packages/trilium-core/src/services/scheduler.spec.ts@@ -0,0 +1,186 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import becca from "../becca/becca.js";+import { buildNote } from "../test/becca_easy_mocking.js";+import attributeService from "./attributes.js";+import config from "./config.js";+import hiddenSubtreeService from "./hidden_subtree.js";+import options from "./options.js";+import protected_session from "./protected_session.js";+import { startScheduler } from "./scheduler.js";+import scriptService from "./script.js";+import sqlInit from "./sql_init.js";+import ws from "./ws.js";++// scheduler.ts is otherwise covered only incidentally (its timers rarely fire+// within a test's lifetime), which makes its coverage flaky. These tests drive+// startScheduler deterministically with fake timers instead.+//+// We spy on the real service singletons rather than vi.mock()-ing their modules:+// scheduler.js is already evaluated by the test setup's initializeCore(), so its+// internal imports are bound to the real modules — mocking them after the fact+// would not be picked up, but spying on the shared singleton objects is.++const SECOND = 1000;+const HOUR = 3600 * SECOND;++/**+ * startScheduler() registers all its timers inside `sqlInit.dbReady.then(...)`.+ * Awaiting the (already-resolved) dbReady promise lets those then-callbacks run+ * first, so the timers exist before we advance the fake clock.+ */+async function settleDbReady() {+ await sqlInit.dbReady;+ await Promise.resolve();+}++function buildBackendScript() {+ return buildNote({ type: "code", mime: "application/javascript;env=backend", content: "" });+}++describe("scheduler", () => {+ const originalScriptingEnabled = config.Security.backendScriptingEnabled;+ const originalInstanceName = config.General.instanceName;+ const originalSafeMode = process.env.TRILIUM_SAFE_MODE;++ let getNotesWithLabel: ReturnType<typeof vi.spyOn>;+ let executeNoteNoException: ReturnType<typeof vi.spyOn>;+ let checkHiddenSubtree: ReturnType<typeof vi.spyOn>;+ let isDbInitialized: ReturnType<typeof vi.spyOn>;+ let isProtectedSessionAvailable: ReturnType<typeof vi.spyOn>;+ let getLastProtectedSessionOperationDate: ReturnType<typeof vi.spyOn>;+ let resetDataKey: ReturnType<typeof vi.spyOn>;+ let getOptionInt: ReturnType<typeof vi.spyOn>;+ let reloadFrontend: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ becca.reset();+ vi.useFakeTimers();+ vi.spyOn(console, "log").mockImplementation(() => {});++ config.Security.backendScriptingEnabled = true;+ config.General.instanceName = "";+ delete process.env.TRILIUM_SAFE_MODE;++ getNotesWithLabel = vi.spyOn(attributeService, "getNotesWithLabel").mockReturnValue([]);+ executeNoteNoException = vi.spyOn(scriptService, "executeNoteNoException").mockImplementation(() => {});+ checkHiddenSubtree = vi.spyOn(hiddenSubtreeService, "checkHiddenSubtree").mockImplementation(() => {});+ isDbInitialized = vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);+ isProtectedSessionAvailable = vi.spyOn(protected_session, "isProtectedSessionAvailable").mockReturnValue(false);+ getLastProtectedSessionOperationDate = vi.spyOn(protected_session, "getLastProtectedSessionOperationDate").mockReturnValue(null);+ resetDataKey = vi.spyOn(protected_session, "resetDataKey").mockImplementation(() => {});+ getOptionInt = vi.spyOn(options, "getOptionInt").mockReturnValue(600);+ reloadFrontend = vi.spyOn(ws, "reloadFrontend").mockImplementation(() => {});+ });++ afterEach(() => {+ vi.clearAllTimers();+ vi.useRealTimers();+ vi.restoreAllMocks();+ config.Security.backendScriptingEnabled = originalScriptingEnabled;+ config.General.instanceName = originalInstanceName;+ if (originalSafeMode === undefined) {+ delete process.env.TRILIUM_SAFE_MODE;+ } else {+ process.env.TRILIUM_SAFE_MODE = originalSafeMode;+ }+ });++ it("runs backendStartup, hourly and daily scripts on their timers when scripting is enabled", async () => {+ isDbInitialized.mockReturnValue(true);+ const scriptNote = buildBackendScript();+ getNotesWithLabel.mockReturnValue([scriptNote]);++ startScheduler();+ await settleDbReady();++ // DB was already initialized → hidden subtree is checked immediately via dbReady.+ expect(checkHiddenSubtree).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(10 * SECOND);+ expect(getNotesWithLabel).toHaveBeenCalledWith("run", "backendStartup");+ expect(executeNoteNoException).toHaveBeenCalledWith(scriptNote, expect.objectContaining({ originEntity: scriptNote }));++ getNotesWithLabel.mockClear();+ await vi.advanceTimersByTimeAsync(HOUR);+ expect(getNotesWithLabel).toHaveBeenCalledWith("run", "hourly");++ getNotesWithLabel.mockClear();+ await vi.advanceTimersByTimeAsync(24 * HOUR);+ expect(getNotesWithLabel).toHaveBeenCalledWith("run", "daily");+ });++ it("checks the hidden subtree only via the periodic maintenance interval when the DB is not yet initialized", async () => {+ isDbInitialized.mockReturnValue(false);++ startScheduler();+ await settleDbReady();+ expect(checkHiddenSubtree).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(7 * HOUR);+ expect(checkHiddenSubtree).toHaveBeenCalledTimes(1);+ });++ it("does not schedule script timers when backend scripting is disabled, but still runs maintenance", async () => {+ config.Security.backendScriptingEnabled = false;++ startScheduler();+ await settleDbReady();+ await vi.advanceTimersByTimeAsync(7 * HOUR);++ expect(getNotesWithLabel).not.toHaveBeenCalled();+ expect(checkHiddenSubtree).toHaveBeenCalled();+ });++ it("does not schedule script timers in safe mode", async () => {+ process.env.TRILIUM_SAFE_MODE = "1";++ startScheduler();+ await settleDbReady();+ await vi.advanceTimersByTimeAsync(HOUR);++ expect(getNotesWithLabel).not.toHaveBeenCalled();+ });++ it("expires the protected session once it has timed out", async () => {+ isProtectedSessionAvailable.mockReturnValue(true);+ // Non-zero (the source guards on the date being truthy) but far in the past.+ getLastProtectedSessionOperationDate.mockReturnValue(1);+ getOptionInt.mockReturnValue(10); // 10s timeout++ startScheduler();+ await settleDbReady();++ await vi.advanceTimersByTimeAsync(30 * SECOND);+ expect(resetDataKey).toHaveBeenCalled();+ expect(reloadFrontend).toHaveBeenCalledWith(expect.any(String));+ });++ it("honors runOnInstance / runAtHour filters and tolerates malformed runAtHour", async () => {+ const runnable = buildBackendScript(); // no filters → always runs++ const wrongInstance = buildBackendScript();+ wrongInstance.getLabelValues = (name) => (name === "runOnInstance" ? ["some-other-instance"] : []);++ const malformed = buildBackendScript();+ malformed.getLabelValues = (name) => {+ if (name === "runAtHour") {+ throw new Error("not a number");+ }+ return [];+ };++ getNotesWithLabel.mockReturnValue([runnable, wrongInstance, malformed]);++ startScheduler();+ await settleDbReady();+ await vi.advanceTimersByTimeAsync(10 * SECOND); // backendStartup++ // runnable + malformed (its bad runAtHour is swallowed → treated as "no hour filter") run;+ // wrongInstance is filtered out because instanceName ("") is not in its runOnInstance list.+ expect(executeNoteNoException).toHaveBeenCalledTimes(2);+ expect(executeNoteNoException).toHaveBeenCalledWith(runnable, expect.anything());+ expect(executeNoteNoException).toHaveBeenCalledWith(malformed, expect.anything());+ expect(executeNoteNoException).not.toHaveBeenCalledWith(wrongInstance, expect.anything());+ });+});diff --git a/packages/trilium-core/src/services/script.spec.ts b/packages/trilium-core/src/services/script.spec.tsindex 2779f0514e..ebf497cdfe 100644--- a/packages/trilium-core/src/services/script.spec.ts+++ b/packages/trilium-core/src/services/script.spec.ts@@ -175,6 +175,21 @@ describe("getScriptBundle", () => {expect(bundle!.script).toContain("api.log('backend');");expect(bundle!.script).not.toContain("api.log('frontend');");});++ it("builds an HTML bundle for an HTML note", () => {+ const note = buildNote({ type: "render", mime: "text/html", content: "<p>hi</p>" });++ const bundle = getScriptBundle(note, true, "frontend");+ expect(bundle).toBeDefined();+ expect(bundle?.html).toContain("<p>hi</p>");+ });++ it("throws when the note's content is not available (protected)", () => {+ const note = buildNote({ type: "code", mime: "application/javascript;env=backend", content: "" });+ note.isContentAvailable = () => false;++ expect(() => getScriptBundle(note)).toThrow(/protected/);+ });});describe("executeNote", () => {@@ -196,6 +211,13 @@ describe("executeNote", () => {expect.objectContaining({ type: "toast" }));});++ it("throws when the note is protected and unavailable", () => {+ const note = buildNote({ type: "code", mime: "application/javascript;env=backend", content: "" });+ note.isContentAvailable = () => false;++ expect(() => scriptService.executeNote(note, {})).toThrow(/protected/);+ });});describe("getScriptBundleForFrontend", () => {@@ -343,3 +365,72 @@ describe("JSX building", () => {expect(buildJsx(script).code).toStrictEqual(expected);});});++describe("executeScript", () => {+ // executeScript funnels through executeBundle, which enforces backendScriptingEnabled.+ const originalScriptingEnabled = config.Security.backendScriptingEnabled;++ beforeAll(() => {+ config.Security.backendScriptingEnabled = true;+ });++ afterAll(() => {+ config.Security.backendScriptingEnabled = originalScriptingEnabled;+ });++ beforeEach(() => {+ becca.reset();+ });++ it("executes a frontend script excerpt in the backend context", () => {+ const note = buildNote({ type: "code", mime: "application/javascript;env=backend", content: "" });++ getContext().init(() => {+ const result = scriptService.executeScript(`() => "hello from excerpt"`, [], note.noteId, note.noteId, "notes", note.noteId, becca);+ expect(result).toBe("hello from excerpt");+ });+ });++ it("serializes params and passes them to the excerpt", () => {+ const note = buildNote({ type: "code", mime: "application/javascript;env=backend", content: "" });++ getContext().init(() => {+ const result = scriptService.executeScript(`(count, label) => label + ":" + (count + 1)`, [4, "n"], note.noteId, note.noteId, "notes", note.noteId, becca);+ expect(result).toBe("n:5");+ });+ });++ it("throws when the current note cannot be found", () => {+ getContext().init(() => {+ expect(() => scriptService.executeScript(`() => 1`, [], "missing", "missing", "notes", "missing", becca)).toThrow(/Cannot find note/);+ });+ });+});++describe("executeNoteNoException", () => {+ const originalScriptingEnabled = config.Security.backendScriptingEnabled;++ beforeAll(() => {+ config.Security.backendScriptingEnabled = true;+ });++ afterAll(() => {+ config.Security.backendScriptingEnabled = originalScriptingEnabled;+ });++ beforeEach(() => {+ becca.reset();+ });++ it("swallows runtime errors thrown by the script", () => {+ const note = buildNote({+ type: "code",+ mime: "application/javascript;env=backend",+ content: `throw new Error("boom");`+ });++ getContext().init(() => {+ expect(() => scriptService.executeNoteNoException(note, {})).not.toThrow();+ });+ });+});