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(server): medium items to handle
Elian Doranc46b65c59bc7
diff --git a/apps/server/src/services/encryption/open_id_encryption.spec.ts b/apps/server/src/services/encryption/open_id_encryption.spec.tsindex 2ca5393872..da3200f195 100644--- a/apps/server/src/services/encryption/open_id_encryption.spec.ts+++ b/apps/server/src/services/encryption/open_id_encryption.spec.ts@@ -104,6 +104,9 @@ describe("open_id_encryption", () => {sql.upsert("user_data", "tmpID", { tmpID: 0, isSetup: "false" });});expect(openIDEncryption.verifyOpenIDSubjectIdentifier("subject")).toBeUndefined();+ // Disambiguate from the other undefined-returning branch (hash undefined):+ // this must be the missing-salt branch.+ expect(logSpy).toHaveBeenCalledWith("Salt undefined");logSpy.mockRestore();});diff --git a/apps/server/src/services/export/zip/factory.spec.ts b/apps/server/src/services/export/zip/factory.spec.tsindex 5456a9d505..796a336925 100644--- a/apps/server/src/services/export/zip/factory.spec.ts+++ b/apps/server/src/services/export/zip/factory.spec.ts@@ -67,7 +67,9 @@ describe("serverZipExportProviderFactory", () => {const readPath = readFileSyncSpy.mock.calls[0][0] as string;expect(readPath).toContain("ckeditor5-content.css");- expect(readPath).toContain("ckeditor5");+ // dev resolves the file from the ckeditor5 package (under node_modules),+ // unlike the production path which reads from the resource dir.+ expect(readPath).toContain("node_modules");});it("builds a Markdown provider without reading any CSS", async () => {diff --git a/apps/server/src/services/image_provider.spec.ts b/apps/server/src/services/image_provider.spec.tsindex ebb6fcab98..37325e30d9 100644--- a/apps/server/src/services/image_provider.spec.ts+++ b/apps/server/src/services/image_provider.spec.ts@@ -169,17 +169,24 @@ describe('serverImageProvider.processImage', () => {expect(result.format).toEqual({ ext: 'png', mime: 'image/png' });});- it('clamps an out-of-range (too low) JPEG quality to the default', async () => {- setOptions({ imageMaxWidthHeight: '100', imageJpegQuality: '5' });-+ async function shrunkSize(jpegQuality: string): Promise<number> {+ setOptions({ imageMaxWidthHeight: '100', imageJpegQuality: jpegQuality });const result = await serverImageProvider.processImage(noisyPng, 'wide.png', true);expect(result.format).toEqual({ ext: 'jpg', mime: 'image/jpeg' });- });-- it('clamps an out-of-range (too high) JPEG quality to the default', async () => {- setOptions({ imageMaxWidthHeight: '100', imageJpegQuality: '150' });+ return result.buffer.byteLength;+ }- const result = await serverImageProvider.processImage(noisyPng, 'wide.png', true);- expect(result.format).toEqual({ ext: 'jpg', mime: 'image/jpeg' });+ it('clamps out-of-range JPEG quality to the default (75)', async () => {+ // An out-of-range quality must produce byte-identical output to an explicit+ // quality of 75, and differ from a valid in-range quality — proving the clamp+ // actually ran (and the bad value was not passed through).+ const at75 = await shrunkSize('75');+ const valid = await shrunkSize('30');+ const tooLow = await shrunkSize('5');+ const tooHigh = await shrunkSize('150');++ expect(tooLow).toBe(at75);+ expect(tooHigh).toBe(at75);+ expect(valid).not.toBe(at75);});});diff --git a/apps/server/src/services/llm/tools/note_tools.spec.ts b/apps/server/src/services/llm/tools/note_tools.spec.tsindex 4128864ae3..c07a1983f6 100644--- a/apps/server/src/services/llm/tools/note_tools.spec.ts+++ b/apps/server/src/services/llm/tools/note_tools.spec.ts@@ -278,7 +278,7 @@ describe("note_tools — write tools return post-write content", () => {});describe("search_notes", () => {- it("maps results to note summaries, applies the limit, and skips stale ids", () => {+ it("maps results to note summaries and skips stale ids", () => {const parent = buildNote({ id: "sp", title: "Search parent" });const a = buildNote({ id: "sa", title: "Alpha", type: "code", mime: "text/plain", content: "body" });withMutableContent(a, "body");@@ -299,6 +299,25 @@ describe("note_tools — write tools return post-write content", () => {expect(result.results[0]).toMatchObject({ noteId: "sa", title: "Alpha", parentTitle: "Search parent" });});+ it("truncates the mapped results to the limit", () => {+ for (const id of ["t1", "t2", "t3"]) {+ const n = buildNote({ id, title: id, type: "code", mime: "text/plain", content: "c" });+ withMutableContent(n, "c");+ n.getParentNotes = () => [];+ }+ // More results than the limit: slice(0, limit) must drop the rest,+ // while totalResults still reflects the full result count.+ findResultsMock.mockReturnValue([{ noteId: "t1" }, { noteId: "t2" }, { noteId: "t3" }]);++ const result = getTool("search_notes").execute({ query: "x", limit: 2 }) as {+ totalResults: number;+ results: any[];+ };+ expect(result.totalResults).toBe(3);+ expect(result.results).toHaveLength(2);+ expect(result.results.map((r) => r.noteId)).toEqual(["t1", "t2"]);+ });+it("defaults the limit to 10 and tolerates results with no parent", () => {const n = buildNote({ id: "np", title: "No parent", type: "code", mime: "text/plain", content: "c" });withMutableContent(n, "c");diff --git a/apps/server/src/services/ocr/ocr_service.spec.ts b/apps/server/src/services/ocr/ocr_service.spec.tsindex f9665841fa..8c21888413 100644--- a/apps/server/src/services/ocr/ocr_service.spec.ts+++ b/apps/server/src/services/ocr/ocr_service.spec.ts@@ -131,6 +131,10 @@ describe('OCRService', () => {expect(result).toBeDefined();expect(result.text).toBe('Extracted text from image');expect(result.extractedAt).toEqual(expect.any(String));+ // Tesseract's 0-100 confidence is normalized to 0-1, and the processor+ // tags the result with its processing type.+ expect(result.confidence).toBeCloseTo(0.95, 2);+ expect(result.processingType).toBe('image');});it('should handle OCR recognition errors', async () => {diff --git a/apps/server/src/services/special_notes.spec.ts b/apps/server/src/services/special_notes.spec.tsindex dec9bc29c8..3349764a42 100644--- a/apps/server/src/services/special_notes.spec.ts+++ b/apps/server/src/services/special_notes.spec.ts@@ -133,23 +133,41 @@ describe("special_notes (LLM chat, real DB)", () => {.toThrow(/workspace note/);});- // A real workspace note (under root, labelled #workspace) used as the clone target.+ // A real workspace note (under root, labelled #workspace) plus two DISTINCT+ // child notes used as the clone targets, so each short-circuit operand of+ // `#workspaceLlmChatHome || #llmChatHome || workspaceNote` resolves to a+ // different note and the chosen target can be asserted unambiguously.let workspaceId: string;+ let workspaceHomeId: string;+ let genericHomeId: string;beforeAll(() => {- workspaceId = cls.init(() => {+ cls.init(() => {const workspace = noteService.createNewNote({parentNoteId: "root", title: "Workspace", content: "", type: "book"}).note;workspace.addLabel("workspace");- return workspace.noteId;+ workspaceId = workspace.noteId;+ workspaceHomeId = noteService.createNewNote({+ parentNoteId: workspaceId, title: "Workspace LLM Home", content: "", type: "book"+ }).note.noteId;+ genericHomeId = noteService.createNewNote({+ parentNoteId: workspaceId, title: "Generic LLM Home", content: "", type: "book"+ }).note.noteId;});});- function expectClonedOutOfHidden(branchId: string | undefined, chat: ReturnType<typeof specialNotes.createLlmChat>) {+ function expectClonedUnder(+ result: ReturnType<typeof specialNotes.saveLlmChat>,+ chat: ReturnType<typeof specialNotes.createLlmChat>,+ expectedParentId: string+ ) {+ expect(result.success).toBe(true);+ // The chat was cloned to the chosen target and detached from _hidden.+ const branch = becca.getBranch(result.branchId!);+ expect(branch).toBeTruthy();+ expect(branch!.parentNoteId).toBe(expectedParentId);const liveParents = chat.getParentBranches().filter((b) => !b.isDeleted);- expect(liveParents.length).toBeGreaterThan(0);expect(liveParents.some((b) => b.parentNote?.hasAncestor("_hidden"))).toBe(false);- expect(becca.getBranch(branchId!)).toBeTruthy();}/**@@ -172,25 +190,24 @@ describe("special_notes (LLM chat, real DB)", () => {}it("uses the #workspaceLlmChatHome target when present", () => {- const home = becca.getNoteOrThrow(workspaceId);- vi.spyOn(hoistedNoteService, "getWorkspaceNote")- .mockReturnValue(workspaceStub({ "#workspaceLlmChatHome": home }) as any);+ vi.spyOn(hoistedNoteService, "getWorkspaceNote").mockReturnValue(+ workspaceStub({ "#workspaceLlmChatHome": becca.getNoteOrThrow(workspaceHomeId) }) as any+ );const chat = cls.init(() => specialNotes.createLlmChat());const result = cls.init(() => specialNotes.saveLlmChat(chat.noteId));- expect(result.success).toBe(true);- expectClonedOutOfHidden(result.branchId, chat);+ expectClonedUnder(result, chat, workspaceHomeId);});it("falls back to #llmChatHome when #workspaceLlmChatHome is absent", () => {- const home = becca.getNoteOrThrow(workspaceId);- vi.spyOn(hoistedNoteService, "getWorkspaceNote")- .mockReturnValue(workspaceStub({ "#llmChatHome": home }) as any);+ vi.spyOn(hoistedNoteService, "getWorkspaceNote").mockReturnValue(+ workspaceStub({ "#llmChatHome": becca.getNoteOrThrow(genericHomeId) }) as any+ );const chat = cls.init(() => specialNotes.createLlmChat());const result = cls.init(() => specialNotes.saveLlmChat(chat.noteId));- expect(result.success).toBe(true);- expectClonedOutOfHidden(result.branchId, chat);+ // Distinct from the #workspaceLlmChatHome target above.+ expectClonedUnder(result, chat, genericHomeId);});it("falls back to the workspace note itself when no chat-home label exists", () => {@@ -199,8 +216,7 @@ describe("special_notes (LLM chat, real DB)", () => {const chat = cls.init(() => specialNotes.createLlmChat());const result = cls.init(() => specialNotes.saveLlmChat(chat.noteId));- expect(result.success).toBe(true);- expectClonedOutOfHidden(result.branchId, chat);+ expectClonedUnder(result, chat, workspaceId);});});diff --git a/apps/server/src/services/utils.spec.ts b/apps/server/src/services/utils.spec.tsindex 6547782bc8..80b0382133 100644--- a/apps/server/src/services/utils.spec.ts+++ b/apps/server/src/services/utils.spec.ts@@ -1,4 +1,3 @@-import { utils as coreUtils } from "@triliumnext/core";import { EventEmitter } from "events";import path from "path";import { afterEach, describe, expect, it, vi } from "vitest";@@ -65,21 +64,26 @@ describe("hmac", () => {});describe("deprecated core delegations", () => {+ // Assert concrete outputs (not equality with the core fn they delegate to,+ // which would pass even if the wrapper were wired to the wrong function).it("forward to the equivalent core utility", () => {expect(newEntityId()).toBeTypeOf("string");expect(randomString(10)).toHaveLength(10);- expect(hashedBlobId("content")).toBe(coreUtils.hashedBlobId("content"));- expect(getContentDisposition("file.txt")).toBe(coreUtils.getContentDisposition("file.txt"));- expect(isStringNote("text", "text/html")).toBe(coreUtils.isStringNote("text", "text/html"));- expect(quoteRegex("a.b")).toBe(coreUtils.quoteRegex("a.b"));- expect(replaceAll("a-b-c", "-", "+")).toBe(coreUtils.replaceAll("a-b-c", "-", "+"));- expect(formatDownloadTitle("name", "text", "text/html"))- .toBe(coreUtils.formatDownloadTitle("name", "text", "text/html"));- expect(removeDiacritic("café")).toBe(coreUtils.removeDiacritic("café"));- expect(normalize("ABC")).toBe(coreUtils.normalize("ABC"));+ expect(hashedBlobId("content")).toBe("stHShbUZnIX5iNA2ScNX");+ expect(getContentDisposition("file.txt"))+ .toBe("file; filename=\"file.txt\"; filename*=UTF-8''file.txt");+ expect(isStringNote("text", "text/html")).toBe(true);+ expect(quoteRegex("a.b")).toBe("a\\.b");+ expect(replaceAll("a-b-c", "-", "+")).toBe("a+b+c");+ expect(formatDownloadTitle("name", "text", "text/html")).toBe("name.html");+ expect(removeDiacritic("café")).toBe("cafe");+ expect(normalize("ABC")).toBe("abc");const list = [{ id: "a", v: 1 }, { id: "b", v: 2 }];- expect(toMap(list, "id")).toEqual(coreUtils.toMap(list, "id"));+ expect(toMap(list, "id")).toEqual(new Map([+ ["a", { id: "a", v: 1 }],+ ["b", { id: "b", v: 2 }]+ ]));});});