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): close 13 single-line coverage gaps across core
Elian Doran94dfa60e1177
diff --git a/packages/trilium-core/src/errors.spec.ts b/packages/trilium-core/src/errors.spec.tsnew file mode 100644index 0000000000..befec7bc87--- /dev/null+++ b/packages/trilium-core/src/errors.spec.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from "vitest";++import { ForbiddenError, HttpError, NotFoundError, OpenIdError, ValidationError } from "./errors.js";++describe("errors", () => {+ it("carries the message plus the status code / name of each error type", () => {+ expect(new HttpError("boom", 418)).toMatchObject({ message: "boom", statusCode: 418, name: "HttpError" });+ expect(new NotFoundError("gone")).toMatchObject({ message: "gone", statusCode: 404, name: "NotFoundError" });+ expect(new ForbiddenError("nope")).toMatchObject({ message: "nope", statusCode: 403, name: "ForbiddenError" });+ expect(new ValidationError("bad")).toMatchObject({ message: "bad", statusCode: 400, name: "ValidationError" });++ // OpenIdError is a plain carrier, not an Error subclass.+ const openIdError = new OpenIdError("oidc failed");+ expect(openIdError.message).toBe("oidc failed");+ expect(openIdError).not.toBeInstanceOf(Error);+ });+});diff --git a/packages/trilium-core/src/migrations/0220__migrate_images_to_attachments.spec.ts b/packages/trilium-core/src/migrations/0220__migrate_images_to_attachments.spec.tsnew file mode 100644index 0000000000..a37d861cbe--- /dev/null+++ b/packages/trilium-core/src/migrations/0220__migrate_images_to_attachments.spec.ts@@ -0,0 +1,76 @@+import { describe, expect, it, vi } from "vitest";++import becca from "../becca/becca.js";+import BNote from "../becca/entities/bnote.js";+import { getContext } from "../services/context.js";+import { getLog } from "../services/log.js";+import noteService from "../services/notes.js";+import optionService from "../services/options.js";+import { getSql } from "../services/sql/index.js";+import migration from "./0220__migrate_images_to_attachments.js";++/**+ * Creates a text note holding an image child that is referenced from it through an+ * `imageLink` relation — the exact shape the migration converts into an attachment.+ */+function createLinkedImageNote(suffix: string) {+ return getContext().init(() => {+ const { note: parent } = noteService.createNewNote({+ parentNoteId: "root",+ title: `0220-parent-${suffix}`,+ content: `<p>before</p>`,+ type: "text"+ });+ const { note: image } = noteService.createNewNote({+ parentNoteId: parent.noteId,+ title: `0220-image-${suffix}.png`,+ content: Buffer.from("fake-png-bytes"),+ type: "image",+ mime: "image/png"+ });+ parent.addRelation("imageLink", image.noteId);++ return { parentNoteId: parent.noteId, imageNoteId: image.noteId, imageTitle: image.title };+ });+}++describe("Migration 0220: migrate images to attachments", () => {+ it("disables image compression and converts a linked image note into a parent attachment", () => {+ const { parentNoteId, imageNoteId, imageTitle } = createLinkedImageNote("ok");++ migration();++ expect(optionService.getOption("compressImages")).toBe("false");++ // The image note itself is (soft) deleted and its content now lives as an+ // attachment of the referencing parent.+ expect(+ getSql().getValue<number>("SELECT isDeleted FROM notes WHERE noteId = ?", [imageNoteId])+ ).toBe(1);+ const attachments = becca.getNoteOrThrow(parentNoteId).getAttachmentsByRole("image");+ expect(attachments.map((attachment) => attachment.title)).toContain(imageTitle);+ });++ it("logs the failure and keeps going when a note cannot be converted", () => {+ const { imageNoteId } = createLinkedImageNote("boom");++ const errorSpy = vi.spyOn(getLog(), "error").mockImplementation(() => {});+ const convertSpy = vi+ .spyOn(BNote.prototype, "convertToParentAttachment")+ .mockImplementation(function (this: BNote) {+ if (this.noteId === imageNoteId) {+ throw new Error("conversion exploded");+ }+ return null;+ });++ try {+ // A single unconvertible note must not abort the whole migration.+ expect(() => migration()).not.toThrow();+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("conversion exploded"));+ } finally {+ convertSpy.mockRestore();+ errorSpy.mockRestore();+ }+ });+});diff --git a/packages/trilium-core/src/routes/api/files.spec.ts b/packages/trilium-core/src/routes/api/files.spec.tsindex c54bf49760..e3d1d39ae5 100644--- a/packages/trilium-core/src/routes/api/files.spec.ts+++ b/packages/trilium-core/src/routes/api/files.spec.ts@@ -1,5 +1,7 @@import { beforeAll, describe, expect, it } from "vitest";+import protectedSessionService from "../../services/protected_session";+import { encodeUtf8 } from "../../services/utils/binary";import { createTextNote } from "../../test/api_fixtures";import { CoreApiTester } from "../../test/api_tester";@@ -55,6 +57,22 @@ describe("Files API (core)", () => {const res = await api.get("/api/notes/missingNote123/download");expect(res.status).toBe(404);});++ it("401s when downloading a protected note without an active protected session", async () => {+ const { noteId } = await createTextNote(api, { content: "<p>secret</p>" });++ // Protecting a note needs the data key; dropping it afterwards leaves exactly the+ // state the download guard rejects (protected note + no protected session).+ protectedSessionService.setDataKey(encodeUtf8("0123456789abcdef")); // exactly 16 bytes+ try {+ expect((await api.put(`/api/notes/${noteId}/protect/1`)).status).toBe(204);+ } finally {+ protectedSessionService.resetDataKey();+ }++ const res = await api.get(`/api/notes/${noteId}/download`);+ expect(res.status).toBe(401);+ });});describe("attachment download/open", () => {diff --git a/packages/trilium-core/src/routes/api/options.spec.ts b/packages/trilium-core/src/routes/api/options.spec.tsindex df50372e43..c13e8867ce 100644--- a/packages/trilium-core/src/routes/api/options.spec.ts+++ b/packages/trilium-core/src/routes/api/options.spec.ts@@ -15,6 +15,18 @@ function getOptionValue(name: string): string | null {return getSql().getValue<string | null>("SELECT value FROM options WHERE name = ?", [name]);}+/** Creates a code note carrying a `#run` label and returns its note ID. */+async function createCodeNote(title: string, mime: string): Promise<string> {+ const created = await api.post<{ note: { noteId: string } }>("/api/notes/root/children?target=into", {+ body: { title, type: "code", mime, content: "api.log('hi');" }+ });+ const { noteId } = created.body.note;+ await api.put(`/api/notes/${noteId}/set-attribute`, {+ body: { type: "label", name: "run", value: "backendStartup" }+ });+ return noteId;+}+describe("Options API (core)", () => {beforeAll(() => {api = CoreApiTester.build();@@ -50,6 +62,50 @@ describe("Options API (core)", () => {}});+ it("exposes the read-only security config flags", async () => {+ const original = getConfig();+ initConfig({+ ...original,+ Security: {+ ...original.Security,+ backendScriptingEnabled: true,+ sqlConsoleEnabled: true,+ allowLanAccess: true+ }+ });+ try {+ const res = await api.get<Record<string, string>>("/api/options");+ expect(res.body.backendScriptingEnabled).toBe("true");+ expect(res.body.sqlConsoleEnabled).toBe("true");+ expect(res.body.allowLanAccess).toBe("true");+ } finally {+ initConfig(original);+ }+ });++ it("flags backend scripts, ignoring #run labels on frontend scripts", async () => {+ expect((await api.get<Record<string, string>>("/api/options")).body.hasUserBackendScripts).toBe("false");++ // #run also appears on frontend scripts, so only the backend MIME type counts.+ await createCodeNote("Frontend script", "application/javascript;env=frontend");+ expect((await api.get<Record<string, string>>("/api/options")).body.hasUserBackendScripts).toBe("false");++ await createCodeNote("Backend script", "application/javascript;env=backend");+ expect((await api.get<Record<string, string>>("/api/options")).body.hasUserBackendScripts).toBe("true");+ });++ it("accepts write-only secrets but reports them only as a boolean flag", async () => {+ expect((await api.put("/api/options/openaiApiKey/sk-secret-value")).status).toBe(204);+ // openNoteContexts skips the logging branch entirely+ expect((await api.put("/api/options/openNoteContexts/%5B%5D")).status).toBe(204);++ const res = await api.get<Record<string, string>>("/api/options");+ expect(res.body.openaiApiKey).toBeUndefined();+ expect(res.body.isOpenaiApiKeySet).toBe("true");+ // the other secret was never written+ expect(res.body.isAnthropicApiKeySet).toBe("false");+ });+it("updates a single allowed option via PUT /api/options/:name/:value", async () => {const res = await api.put("/api/options/zoomFactor/1.5");expect(res.status).toBe(204);diff --git a/packages/trilium-core/src/services/backup.spec.ts b/packages/trilium-core/src/services/backup.spec.tsindex 9a5fe3ebfe..006c27001a 100644--- a/packages/trilium-core/src/services/backup.spec.ts+++ b/packages/trilium-core/src/services/backup.spec.ts@@ -98,6 +98,13 @@ describe("BackupService singleton (getBackup / initBackup)", () => {});});+describe("BackupService.getBackupFolderPath", () => {+ it("defaults to null when the implementation exposes no user-accessible location", () => {+ // e.g. the standalone provider, which stores backups in OPFS.+ expect(new TestBackupService(new FakeOptions()).getBackupFolderPath()).toBeNull();+ });+});+describe("BackupService.isBackupEnabled", () => {it("maps each backup type to the matching boolean option", () => {const service = new TestBackupService(diff --git a/packages/trilium-core/src/services/erase.spec.ts b/packages/trilium-core/src/services/erase.spec.tsindex 96410477ec..7f7003b916 100644--- a/packages/trilium-core/src/services/erase.spec.ts+++ b/packages/trilium-core/src/services/erase.spec.ts@@ -1,11 +1,13 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import becca from "../becca/becca.js";import type BNote from "../becca/entities/bnote.js";import { getContext } from "./context.js";import eraseService from "./erase.js";import noteService from "./notes.js";+import optionService from "./options.js";import { getSql } from "./sql/index.js";+import { dbReady } from "./sql_init.js";let counter = 0;@@ -217,4 +219,47 @@ describe("erase service (real DB)", () => {expect(rowCount("notes", "noteId", noteId)).toBe(1);});});++ describe("startScheduledCleanup", () => {+ // Kept last in the file: it erases everything already soft-deleted in the shared+ // fixture DB, which would otherwise pull the ground out from under the tests above.+ it("erases due notes and scheduled attachments once the periodic timers fire", async () => {+ const note = createNote();+ const noteId = note.noteId;+ getContext().init(() => note.deleteNote());++ const attachmentOwner = createNote();+ const attachment = getContext().init(() =>+ attachmentOwner.saveAttachment({ role: "file", mime: "text/plain", title: "cron", content: "x" })+ );+ getContext().init(() =>+ getSql().execute(+ "UPDATE attachments SET utcDateScheduledForErasureSince = ? WHERE attachmentId = ?",+ ["2000-01-01 00:00:00.000Z", attachment.attachmentId]+ )+ );++ const previousEraseAfter = optionService.getOption("eraseEntitiesAfterTimeInSeconds");+ getContext().init(() => optionService.setOption("eraseEntitiesAfterTimeInSeconds", "0"));+ vi.useFakeTimers();++ try {+ eraseService.startScheduledCleanup();+ // The timers are only registered once the DB is ready.+ await dbReady;+ // Long enough for both kickoff timeouts (5/6 min) and the first tick of the+ // 4-hour note interval and the 1-hour attachment interval.+ await vi.advanceTimersByTimeAsync(4 * 3600 * 1000);++ expect(rowCount("notes", "noteId", noteId)).toBe(0);+ expect(rowCount("attachments", "attachmentId", attachment.attachmentId)).toBe(0);+ } finally {+ // Dropping the fake clock also discards the intervals, so nothing keeps running.+ vi.useRealTimers();+ getContext().init(() =>+ optionService.setOption("eraseEntitiesAfterTimeInSeconds", previousEraseAfter)+ );+ }+ });+ });});diff --git a/packages/trilium-core/src/services/one_time_timer.spec.ts b/packages/trilium-core/src/services/one_time_timer.spec.tsindex c659ffa666..b9de733b26 100644--- a/packages/trilium-core/src/services/one_time_timer.spec.ts+++ b/packages/trilium-core/src/services/one_time_timer.spec.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { getLog } from "./log.js";import oneTimeTimer from "./one_time_timer.js";describe("oneTimeTimer", () => {@@ -86,6 +87,35 @@ describe("oneTimeTimer", () => {expect(next).toHaveBeenCalledTimes(1);});+ it("falls back to console.error when the log service itself throws", () => {+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const logSpy = vi.spyOn(getLog(), "error").mockImplementation(() => {+ throw new Error("log service unavailable");+ });+ const stackless = new Error("stackless failure");+ delete stackless.stack;++ try {+ // A non-Error rejection value and an Error without a stack both have to be+ // rendered into the message without the handler throwing.+ oneTimeTimer.scheduleExecution("log-broken-string", 100, () => {+ throw "plain string failure";+ });+ oneTimeTimer.scheduleExecution("log-broken-stackless", 100, () => {+ throw stackless;+ });++ expect(() => vi.advanceTimersByTime(100)).not.toThrow();++ expect(logSpy).toHaveBeenCalledTimes(2);+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("plain string failure"));+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("stackless failure"));+ } finally {+ logSpy.mockRestore();+ consoleSpy.mockRestore();+ }+ });+it("allows re-scheduling the same name from within the callback", () => {const inner = vi.fn();const outer = vi.fn(() => {diff --git a/packages/trilium-core/src/services/options.spec.ts b/packages/trilium-core/src/services/options.spec.tsindex 598ad21b12..bd94e8be3b 100644--- a/packages/trilium-core/src/services/options.spec.ts+++ b/packages/trilium-core/src/services/options.spec.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import becca from "../becca/becca.js";import { getContext } from "./context.js";@@ -34,6 +34,23 @@ describe("options service (real DB)", () => {expect(optionService.getOptionOrNull("doesNotExistOption" as any)).toBeNull();});+ it("returns null when becca is not loaded and the DB query fails", () => {+ // Before becca is loaded (e.g. during initial sync) the value is read straight+ // from the DB, which is not necessarily initialized yet.+ const getRowSpy = vi.spyOn(getSql(), "getRow").mockImplementation(() => {+ throw new Error("DB is not initialized");+ });+ const wasLoaded = becca.loaded;+ becca.loaded = false;++ try {+ expect(optionService.getOptionOrNull("mainFontSize" as any)).toBeNull();+ } finally {+ becca.loaded = wasLoaded;+ getRowSpy.mockRestore();+ }+ });+it("throws from getOption for a non-existent option", () => {expect(() => optionService.getOption("doesNotExistOption" as any)).toThrow(/doesn't exist/diff --git a/packages/trilium-core/src/services/sanitizer.spec.ts b/packages/trilium-core/src/services/sanitizer.spec.tsindex 9b01e9f476..a10a4da29b 100644--- a/packages/trilium-core/src/services/sanitizer.spec.ts+++ b/packages/trilium-core/src/services/sanitizer.spec.ts@@ -1,5 +1,6 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import { sanitizeHtml } from "./sanitizer.js";+import optionService from "./options.js";import { trimIndentation } from "@triliumnext/commons";describe("sanitize", () => {@@ -77,6 +78,18 @@ describe("sanitize", () => {expect(sanitizeHtml(`<img style="aspect-ratio:auto" src="x.png" />`)).not.toContain("aspect-ratio");});+ it("falls back to the default allowed tags when the allowedHtmlTags option is unusable", () => {+ const optionSpy = vi.spyOn(optionService, "getOption").mockReturnValue("{ not json");+ try {+ // The parse failure must not propagate; sanitization still applies the default list.+ const sanitized = sanitizeHtml(`<p>kept</p><script>alert(1)</script>`);+ expect(sanitized).toContain(`<p>kept</p>`);+ expect(sanitized).not.toContain(`<script>`);+ } finally {+ optionSpy.mockRestore();+ }+ });+describe("bookmark anchors", () => {it("preserves id attribute on empty <a> tags (CKEditor bookmarks)", () => {const dirty = `<a id="my-bookmark"></a>`;diff --git a/packages/trilium-core/src/services/script_context.spec.ts b/packages/trilium-core/src/services/script_context.spec.tsindex 512a73ec10..87a3e79676 100644--- a/packages/trilium-core/src/services/script_context.spec.ts+++ b/packages/trilium-core/src/services/script_context.spec.ts@@ -83,6 +83,16 @@ describe("ScriptContext", () => {expect(typeof (lodash as { join?: unknown }).join).toBe("function");});+ it("require() refuses blocked OS-level modules before consulting the whitelist", () => {+ const moduleNote = buildNote({ title: "myModule" });+ const ctx = new ScriptContext([moduleNote], { startNote: moduleNote });+ const require = ctx.require([moduleNote.noteId]);++ for (const blocked of ["child_process", "fs", "net", "os"]) {+ expect(() => require(blocked)).toThrow(/blocked/);+ }+ });+it("require() throws when falling back to a non-existent native module", () => {const moduleNote = buildNote({ title: "myModule" });const ctx = new ScriptContext([moduleNote], { startNote: moduleNote });diff --git a/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.spec.ts b/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.spec.tsindex e0390e861b..889f0f99af 100644--- a/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.spec.ts+++ b/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.spec.ts@@ -39,6 +39,27 @@ describe("Canvas preprocessing", () => {});});+describe("Spreadsheet preprocessing", () => {+ const type: NoteType = "spreadsheet";+ const mime = "application/json";++ it("supports empty / invalid JSON", () => {+ expect(preprocessContent("{}", type, mime)).toEqual("");+ expect(preprocessContent("", type, mime)).toEqual("");+ });++ it("reads visible cell values", () => {+ const workbook = JSON.stringify({+ workbook: {+ sheets: {+ s1: { cellData: { 0: { 0: { v: "Revenue" }, 1: { v: 42 } } } }+ }+ }+ });+ expect(preprocessContent(workbook, type, mime)).toEqual("revenue 42");+ });+});+describe("Text (HTML) preprocessing", () => {const type: NoteType = "text";const mime = "text/html";@@ -51,6 +72,19 @@ describe("Text (HTML) preprocessing", () => {expect(result).toContain("https://en.wikipedia.org/wiki/the_terminator");expect(result).toContain("a 1984 science fiction film.");});++ it("keeps the markup but still unescapes entities when raw is requested", () => {+ const result = preprocessContent("<p>Hello world</p>", type, mime, true);+ expect(result).toEqual("<p>hello world</p>");+ });+});++describe("Unhandled type/mime combinations", () => {+ it("returns the normalized content untouched", () => {+ // Neither the type nor the mime matches any branch, so no extractor runs.+ expect(preprocessContent("Plain Text", "code", "text/plain")).toEqual("plain text");+ expect(preprocessContent("{}", "llmChat", "text/plain")).toEqual("{}");+ });});describe("LLM chat preprocessing", () => {diff --git a/packages/trilium-core/src/services/search/search_result.spec.ts b/packages/trilium-core/src/services/search/search_result.spec.tsindex 83091e3d33..cdae87b36f 100644--- a/packages/trilium-core/src/services/search/search_result.spec.ts+++ b/packages/trilium-core/src/services/search/search_result.spec.ts@@ -214,5 +214,21 @@ describe("SearchResult", () => {expect(exactResult.score).toBeGreaterThan(fuzzyResult.score);});++ it("suppresses the fuzzy title score once the cumulative fuzzy budget is exhausted", () => {+ const target = note("Vienna");+ rootNote.child(target);++ const result = resultFor(target);+ const fuzzyTitleScore = () => result["calculateFuzzyTitleScore"]("vienna", "vienne");++ expect(fuzzyTitleScore()).toBeGreaterThan(0);++ // Every near-miss token chunk consumes the shared fuzzy budget; once it is spent,+ // further fuzzy title scoring returns 0. computeScore() resets that budget before+ // scoring the title, so the cap is only observable on a directly driven instance.+ result.addScoreForStrings(["vienna"], new Array(80).fill("vienne").join(" "), 10, true);+ expect(fuzzyTitleScore()).toBe(0);+ });});});diff --git a/packages/trilium-core/src/test/api_fixtures.spec.ts b/packages/trilium-core/src/test/api_fixtures.spec.tsnew file mode 100644index 0000000000..10532bfcb0--- /dev/null+++ b/packages/trilium-core/src/test/api_fixtures.spec.ts@@ -0,0 +1,21 @@+import { beforeAll, describe, expect, it } from "vitest";++import { createTextNote } from "./api_fixtures";+import { CoreApiTester } from "./api_tester";++let api: CoreApiTester;++describe("createTextNote fixture", () => {+ beforeAll(() => {+ api = CoreApiTester.build();+ });++ it("creates a note under root and surfaces the API failure when the parent is unusable", async () => {+ const { noteId, branchId } = await createTextNote(api, { title: "Fixture note" });+ expect(noteId).toBeTruthy();+ expect(branchId).toBeTruthy();++ await expect(createTextNote(api, { parentNoteId: "missingParent123" }))+ .rejects.toThrow(/createTextNote failed/);+ });+});