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): automated review
Elian Doran696a4d1e14aa
diff --git a/packages/trilium-core/src/services/hidden_subtree.spec.ts b/packages/trilium-core/src/services/hidden_subtree.spec.tsindex 927b6b0976..79a2fc1d4f 100644--- a/packages/trilium-core/src/services/hidden_subtree.spec.ts+++ b/packages/trilium-core/src/services/hidden_subtree.spec.ts@@ -13,6 +13,25 @@ import hiddenSubtreeService, {LBTPL_SPACER,LBTPL_WIDGET} from "./hidden_subtree.js";+import noteService from "./notes.js";++/**+ * Re-create a deprecated hidden-subtree note under its declared parent so the+ * enforceDeleted branch in checkHiddenSubtree has something to delete. Both+ * deprecated entries live directly under "_options" in the definition.+ */+function materialiseDeprecatedNote(noteId: string) {+ withContext(() =>+ noteService.createNewNote({+ noteId,+ title: `deprecated-${noteId}`,+ type: "contentWidget",+ parentNoteId: "_options",+ content: "",+ ignoreForbiddenParents: true+ })+ );+}/*** Entity mutations performed by checkHiddenSubtree (createNewNote, save,@@ -139,8 +158,19 @@ describe("hidden_subtree (real DB)", () => {describe("enforceDeleted", () => {it("removes deprecated notes marked enforceDeleted", () => {- // _optionsImages and _optionsAi are declared with enforceDeleted: true,- // so they must never survive an integrity check.+ // _optionsImages and _optionsAi are declared with enforceDeleted: true.+ // Materialise them first so checkHiddenSubtree actually has a note to+ // delete — otherwise the assertion would pass vacuously even if the+ // enforceDeleted branch were removed.+ for (const deprecatedId of ["_optionsImages", "_optionsAi"]) {+ materialiseDeprecatedNote(deprecatedId);+ const note = becca.notes[deprecatedId] as BNote | undefined;+ expect(note, `${deprecatedId} should have been created`).toBeDefined();+ }++ checkHiddenSubtree();++ // The enforceDeleted branch must purge each materialised note.for (const deprecatedId of ["_optionsImages", "_optionsAi"]) {const note = becca.notes[deprecatedId] as BNote | undefined;expect(note, `${deprecatedId} should have been deleted`).toBeUndefined();@@ -149,10 +179,19 @@ describe("hidden_subtree (real DB)", () => {it("re-deletes a deprecated note if it reappears", () => {const deprecatedId = "_optionsImages";++ // First reappearance: recreate the note and confirm a check deletes it.+ materialiseDeprecatedNote(deprecatedId);+ expect(becca.notes[deprecatedId]).toBeDefined();++ checkHiddenSubtree();expect(becca.notes[deprecatedId]).toBeUndefined();- // The recursion still visits the deprecated entry and calls deleteNote- // even on a fresh run, so a second check stays stable.+ // Second reappearance: the deletion path must run again, not just rely+ // on the note already being absent.+ materialiseDeprecatedNote(deprecatedId);+ expect(becca.notes[deprecatedId]).toBeDefined();+checkHiddenSubtree();expect(becca.notes[deprecatedId]).toBeUndefined();});diff --git a/packages/trilium-core/src/services/image.spec.ts b/packages/trilium-core/src/services/image.spec.tsindex 3de43c7e9a..9459c1428d 100644--- a/packages/trilium-core/src/services/image.spec.ts+++ b/packages/trilium-core/src/services/image.spec.ts@@ -194,11 +194,11 @@ describe("image service (real DB)", () => {});it("saves a revision, sets the originalFileName label, and updates mime/content on resolve", async () => {- // The persisted content is the provider's *processed* output, so drive- // it with a distinct buffer. Stub before creating so the note-creation's- // own async branch also resolves to png and doesn't clobber the mime.- const processedBuffer = new Uint8Array([1, 2, 3]);- stubProcessImage({ ext: "png" }, processedBuffer);+ // The persisted content is the provider's *processed* output. Drive the+ // initial saveImage with a PNG so the note settles into a known state we+ // can later prove updateImage moves away from.+ const createdBuffer = new Uint8Array([1, 2, 3]);+ stubProcessImage({ ext: "png" }, createdBuffer);// Start from a freshly created image note we can mutate.counter++;@@ -207,6 +207,18 @@ describe("image service (real DB)", () => {);await flushAsync();+ // Sanity-check the pre-update state so the post-update assertions below+ // genuinely discriminate updateImage's effect (and aren't already true).+ const beforeUpdate = becca.getNote(noteId)!;+ expect(beforeUpdate.mime).toBe("image/png");+ expect(bytesOf(beforeUpdate.getContent())).toEqual(Array.from(createdBuffer));++ // Re-point the provider so updateImage resolves to a DIFFERENT mime and+ // buffer than saveImage left behind; otherwise the assertions would pass+ // on the saveImage state regardless of whether updateImage ran.+ const updatedBuffer = new Uint8Array([9, 8, 7, 6]);+ stubProcessImage({ ext: "jpg" }, updatedBuffer);+const revisionSpy = vi.spyOn(becca.getNote(noteId)!, "saveRevision");withContext(() => imageService.updateImage(noteId, fakeBuffer, "renamed.png"));@@ -215,25 +227,57 @@ describe("image service (real DB)", () => {const note = becca.getNote(noteId)!;expect(revisionSpy).toHaveBeenCalledTimes(1);expect(note.getOwnedLabelValue("originalFileName")).toBe("renamed.png");- expect(note.mime).toBe("image/png");- // Content is the processed buffer the provider returned, not the raw upload.- expect(bytesOf(note.getContent())).toEqual(Array.from(processedBuffer));+ // Mime/content now reflect updateImage's distinct provider output, which+ // differs from the PNG/[1,2,3] state saveImage produced.+ expect(note.mime).toBe("image/jpg");+ expect(bytesOf(note.getContent())).toEqual(Array.from(updatedBuffer));});});describe("protected note handling in saveImage", () => {- it("creates a protected image note only when a protected session is available", () => {- // Build a protected parent so the protection inheritance branch is taken.- vi.spyOn(protectedSessionService, "isProtectedSessionAvailable").mockReturnValue(false);- counter++;-- const result = withContext(() =>- imageService.saveImage("root", fakeBuffer, `prot-${counter}.png`, false)- );-- // Parent (root) is not protected and no session is available, so the- // child must not be protected either.- expect(becca.getNote(result.noteId)!.isProtected).toBe(false);+ it("creates a protected image note only when a protected session is available", async () => {+ // The child inherits protection only via+ // `parentNote.isProtected && isProtectedSessionAvailable()`, so the+ // parent MUST be protected for the session flag to matter at all.+ const root = becca.getNote("root")!;+ const originalRootProtected = root.isProtected;+ root.isProtected = true;++ // Keep async image processing deterministic; saving a protected note's+ // content requires encryption, so return a fake ciphertext instead of+ // standing up a real protected session/data key.+ stubProcessImage({ ext: "png" });+ vi.spyOn(protectedSessionService, "encrypt").mockReturnValue("fake-ciphertext");++ const sessionSpy = vi.spyOn(protectedSessionService, "isProtectedSessionAvailable");++ try {+ // Session available -> protected parent yields a protected child.+ sessionSpy.mockReturnValue(true);+ counter++;+ const whenAvailable = withContext(() =>+ imageService.saveImage("root", fakeBuffer, `prot-on-${counter}.png`, false)+ );+ expect(becca.getNote(whenAvailable.noteId)!.isProtected).toBe(true);+ // Let the protected note's fire-and-forget content save settle while+ // the session is still "available", so its encryption branch doesn't+ // run after we flip the mock below.+ await flushAsync();++ // Session unavailable -> even a protected parent yields an+ // unprotected child, proving the result tracks the session mock.+ sessionSpy.mockReturnValue(false);+ counter++;+ const whenUnavailable = withContext(() =>+ imageService.saveImage("root", fakeBuffer, `prot-off-${counter}.png`, false)+ );+ expect(becca.getNote(whenUnavailable.noteId)!.isProtected).toBe(false);+ await flushAsync();+ } finally {+ // Restore the shared fixture's root so sibling tests still attach+ // under an unprotected parent.+ root.isProtected = originalRootProtected;+ }});});});diff --git a/packages/trilium-core/src/services/notes.spec.ts b/packages/trilium-core/src/services/notes.spec.tsindex 6d4e9e69dd..f405db4132 100644--- a/packages/trilium-core/src/services/notes.spec.ts+++ b/packages/trilium-core/src/services/notes.spec.ts@@ -1,10 +1,11 @@-import { beforeAll, describe, expect, it } from "vitest";+import { afterAll, beforeAll, describe, expect, it } from "vitest";import becca from "../becca/becca.js";import type BBranch from "../becca/entities/bbranch.js";import type BNote from "../becca/entities/bnote.js";import { getContext } from "./context.js";import noteService, { saveLinks } from "./notes.js";+import optionService from "./options.js";import { getSql } from "./sql/index.js";/**@@ -279,6 +280,40 @@ describe("notes service (real DB)", () => {});describe("saveRevisionIfNeeded", () => {+ // saveRevisionIfNeeded only creates a revision once the note is at least+ // `revisionSnapshotTimeInterval` seconds old (default 600s). A freshly+ // created note is ~0s old, so with the default interval the revision+ // branch is unreachable and the `disableVersioning` guard would never be+ // exercised. Force the interval to 0 so the branch becomes reachable, and+ // restore the original value afterwards so sibling tests are unaffected.+ let originalInterval: string;++ beforeAll(() => {+ originalInterval = optionService.getOption("revisionSnapshotTimeInterval");+ withContext(() => optionService.setOption("revisionSnapshotTimeInterval", "0"));+ });++ afterAll(() => {+ withContext(() => optionService.setOption("revisionSnapshotTimeInterval", originalInterval));+ });++ function revisionCount(note: BNote): number {+ return getSql().getValue<number>("SELECT COUNT(*) FROM revisions WHERE noteId = ?", [note.noteId]);+ }++ it("creates a revision for an eligible note without disableVersioning", () => {+ const note = createNote("root", {+ title: "spec-revision-eligible",+ content: "<p>x</p>"+ }).note;++ const before = revisionCount(note);+ withContext(() => noteService.saveRevisionIfNeeded(note));+ const after = revisionCount(note);++ expect(after).toBe(before + 1);+ });+it("does nothing for notes with disableVersioning", () => {const note = createNote("root", {title: "spec-no-revision",@@ -288,13 +323,9 @@ describe("notes service (real DB)", () => {]}).note;- const before = getSql().getValue<number>("SELECT COUNT(*) FROM revisions WHERE noteId = ?", [- note.noteId- ]);+ const before = revisionCount(note);withContext(() => noteService.saveRevisionIfNeeded(note));- const after = getSql().getValue<number>("SELECT COUNT(*) FROM revisions WHERE noteId = ?", [- note.noteId- ]);+ const after = revisionCount(note);expect(after).toBe(before);});diff --git a/packages/trilium-core/src/services/script_context.spec.ts b/packages/trilium-core/src/services/script_context.spec.tsindex 416e27604e..f79479a9a0 100644--- a/packages/trilium-core/src/services/script_context.spec.ts+++ b/packages/trilium-core/src/services/script_context.spec.ts@@ -50,13 +50,14 @@ describe("ScriptContext", () => {it("require() only considers note ids passed in moduleNoteIds", () => {const included = buildNote({ title: "shared" });const excluded = buildNote({ title: "shared" });- const ctx = new ScriptContext([included, excluded], { startNote: included });+ // `excluded` is placed first in allNotes so that, if the whitelist+ // filter were dropped, find() would match it first. Only `included`+ // is whitelisted, so its exports must still be returned.+ const ctx = new ScriptContext([excluded, included], { startNote: included });ctx.modules[included.noteId] = { exports: ["included-exports"] };ctx.modules[excluded.noteId] = { exports: ["excluded-exports"] };- // Only `included` is whitelisted, so its exports must be returned even- // though both notes share the same title.const resolved = ctx.require([included.noteId])("shared");expect(resolved).toEqual(["included-exports"]);});diff --git a/packages/trilium-core/src/services/search/expressions/order_by_and_limit.spec.ts b/packages/trilium-core/src/services/search/expressions/order_by_and_limit.spec.tsindex 0fb76b524c..2a6925c33e 100644--- a/packages/trilium-core/src/services/search/expressions/order_by_and_limit.spec.ts+++ b/packages/trilium-core/src/services/search/expressions/order_by_and_limit.spec.ts@@ -94,10 +94,14 @@ describe("OrderByAndLimitExp", () => {it("parses numeric strings for numerical (not lexicographic) comparison", () => {const a = note("A").note;const b = note("B").note;- // Lexicographically "10" < "9", but numerically 9 < 10.- const exp = new OrderByAndLimitExp([{ direction: "asc", valueExtractor: { extract: (n) => (n.title === "A" ? "10" : "9") } }]);+ // "20" and "123.45" are both rejected by isDate() but accepted by isNumber(), so the+ // comparator genuinely takes the parseFloat numeric branch (unlike "10"/"9", which+ // new Date() accepts and would route through the date branch instead). Numerically+ // 20 < 123.45, but lexicographically "123.45" < "20" — so a string sort would yield+ // ["B", "A"] and only a numeric sort yields ["A", "B"].+ const exp = new OrderByAndLimitExp([{ direction: "asc", valueExtractor: { extract: (n) => (n.title === "A" ? "20" : "123.45") } }]);- expect(run(exp, [a, b]).notes.map((n) => n.title)).toEqual(["B", "A"]);+ expect(run(exp, [a, b]).notes.map((n) => n.title)).toEqual(["A", "B"]);});it("parses date strings for chronological comparison", () => {diff --git a/packages/trilium-core/src/services/utils/date.spec.ts b/packages/trilium-core/src/services/utils/date.spec.tsindex ce61bd2b9f..6fa844eac9 100644--- a/packages/trilium-core/src/services/utils/date.spec.ts+++ b/packages/trilium-core/src/services/utils/date.spec.ts@@ -145,7 +145,11 @@ describe("date utils", () => {describe("localNowDateTime", () => {it("falls back to the current local time when no CLS value is set", () => {- const result = date.localNowDateTime();+ // Run inside a fresh context that does NOT set "localNowDateTime" so the fallback+ // path runs deterministically. Relying on the absence of any active context is fragile:+ // the standalone provider defers context cleanup ~1s, so a value set by a preceding+ // test would otherwise leak in and be returned verbatim instead of the live fallback.+ const result = cls.init(() => date.localNowDateTime());expect(result).toMatch(/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}[+-][0-9]{4}$/);@@ -163,7 +167,11 @@ describe("date utils", () => {describe("localNowDate", () => {it("derives today's date in YYYY-MM-DD form when no CLS value is set", () => {- const result = date.localNowDate();+ // Run inside a fresh context that does NOT set "localNowDateTime" so the fallback+ // path runs deterministically. Relying on the absence of any active context is fragile:+ // the standalone provider defers context cleanup ~1s, so a value set by a preceding+ // test would otherwise leak in and yield a stale date instead of today's date.+ const result = cls.init(() => date.localNowDate());expect(result).toMatch(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/);const now = new Date();