Skip to content

Build your personal knowledge base with Trilium Notes

test(server): address low reviews

Elian Doran73e5a49b3d25
diff --git a/apps/server/src/services/anonymization.spec.ts b/apps/server/src/services/anonymization.spec.ts
index 5567df245e..47c80d6013 100644
--- a/apps/server/src/services/anonymization.spec.ts
+++ b/apps/server/src/services/anonymization.spec.ts
@@ -1,4 +1,5 @@
import { BUILTIN_ATTRIBUTES } from "@triliumnext/commons";
+import path from "path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// --- Mocks (hoisted above the module-under-test import) ---
@@ -139,7 +140,9 @@ describe("getExistingAnonymizedDatabases", () => {
"anonymized-light-y.db"
]);
for (const entry of result) {
- expect(entry.filePath).toContain(entry.fileName);
+ // filePath must be the fully-resolved path under the anonymized-db dir,
+ // not merely a string that happens to contain the file name.
+ expect(entry.filePath).toBe(path.resolve(dataDir.ANONYMIZED_DB_DIR, entry.fileName));
}
});
});
diff --git a/apps/server/src/services/auth.spec.ts b/apps/server/src/services/auth.spec.ts
index b27ed11433..219cf49cb4 100644
--- a/apps/server/src/services/auth.spec.ts
+++ b/apps/server/src/services/auth.spec.ts
@@ -368,6 +368,8 @@ describe("Auth", () => {
const res4 = makeRes();
auth.checkCredentials(makeReq({ headers: { "trilium-cred": cred } }), res4 as never, vi.fn());
expect(res4.statusCode).toBe(401);
+ // The username before the colon is stripped; only the password is verified.
+ expect(verifySpy).toHaveBeenLastCalledWith("wrongpass");
// correct password (no colon in decoded cred path also exercised) -> next
verifySpy.mockReturnValue(true as never);
@@ -375,6 +377,8 @@ describe("Auth", () => {
const next = vi.fn();
auth.checkCredentials(makeReq({ headers: { "trilium-cred": credNoColon } }), makeRes() as never, next);
expect(next).toHaveBeenCalled();
+ // No colon → the whole cred is treated as username and the password is "".
+ expect(verifySpy).toHaveBeenLastCalledWith("");
// missing trilium-cred header -> falls back to "" -> next (with verify mocked true)
const nextNoHeader = vi.fn();
diff --git a/apps/server/src/services/data_dir.spec.ts b/apps/server/src/services/data_dir.spec.ts
index e61a9922b8..e4066eda46 100644
--- a/apps/server/src/services/data_dir.spec.ts
+++ b/apps/server/src/services/data_dir.spec.ts
@@ -393,8 +393,11 @@ describe("data_dir.ts unit tests", () => {
try {
expect(() => getTriliumDataDir("trilium-data")).toThrow(err);
- expect(console.error).toHaveBeenCalled();
expect(mockFn.statSyncMock).toHaveBeenCalledTimes(1);
+ // Confirm the owner/permissions diagnostics branch actually ran.
+ expect(console.error).toHaveBeenCalledWith("Process running as UID:GID = 1000:1000");
+ expect(console.error).toHaveBeenCalledWith(" Owner UID:GID = 1000:1000");
+ expect(console.error).toHaveBeenCalledWith(" Permissions = 755 (octal)");
} finally {
if (!hadGetuid) {
delete proc.getuid;
@@ -408,7 +411,10 @@ describe("data_dir.ts unit tests", () => {
mockFn.statSyncMock.mockImplementation(() => { throw new Error("no access"); });
expect(() => getTriliumDataDir("trilium-data")).toThrow(err);
- expect(console.error).toHaveBeenCalled();
+ // The inaccessible-parent branch (not the owner/permissions one) ran.
+ expect(console.error).toHaveBeenCalledWith(
+ expect.stringContaining("is not accessible")
+ );
});
it("EEXIST but target is not a directory – rethrows", () => {
diff --git a/apps/server/src/services/llm/providers/anthropic.spec.ts b/apps/server/src/services/llm/providers/anthropic.spec.ts
index 0f4cef3d15..bbaee44462 100644
--- a/apps/server/src/services/llm/providers/anthropic.spec.ts
+++ b/apps/server/src/services/llm/providers/anthropic.spec.ts
@@ -195,11 +195,10 @@ describe("AnthropicProvider tool handling", () => {
* The system prompt carries the ephemeral cache breakpoint, so Anthropic can only
* reuse the cached system+tools prefix when that string is byte-stable across turns.
*
- * These tests assert the *desired* invariant: editing the context note must not
- * disturb the cached system prompt. They currently FAIL because the live note
- * metadata is embedded directly into the cache-controlled system string — that
- * red state is the confirmation that the note hint busts the prompt cache. Once
- * the hint is moved out of the cached prefix, they turn green.
+ * These tests assert the enforced invariant: editing the context note must not
+ * disturb the cache-controlled system prompt. The volatile note metadata is
+ * delivered on the last user message instead of being embedded in the cached
+ * system prefix (verified by the last test in this block).
*/
describe("AnthropicProvider prompt cache stability", () => {
beforeEach(() => {
diff --git a/apps/server/src/services/llm/providers/base_provider.spec.ts b/apps/server/src/services/llm/providers/base_provider.spec.ts
index 16e379776a..8ba2124922 100644
--- a/apps/server/src/services/llm/providers/base_provider.spec.ts
+++ b/apps/server/src/services/llm/providers/base_provider.spec.ts
@@ -388,9 +388,11 @@ describe("BaseProvider chat / pricing / models / title", () => {
it("invokes the no-op base addWebSearchTool when web search is enabled (adds nothing)", () => {
const provider = new TestProvider();
- // Base addWebSearchTool is a no-op, so the tool set stays empty and no
- // agentic options are attached.
+ // Spy through to the real no-op: it MUST be invoked (the claim of the test),
+ // and because it adds nothing the tool set stays empty.
+ const addWebSearchSpy = vi.spyOn(provider as unknown as { addWebSearchTool: () => void }, "addWebSearchTool");
provider.chat([{ role: "user", content: "hi" }], { enableWebSearch: true });
+ expect(addWebSearchSpy).toHaveBeenCalledOnce();
const opts = streamTextMock.mock.calls[0][0] as any;
expect(opts.tools).toBeUndefined();
expect(opts.toolChoice).toBeUndefined();
diff --git a/apps/server/src/services/ocr/processors/office_processor.spec.ts b/apps/server/src/services/ocr/processors/office_processor.spec.ts
index c3e10e74cf..e1b87aad2c 100644
--- a/apps/server/src/services/ocr/processors/office_processor.spec.ts
+++ b/apps/server/src/services/ocr/processors/office_processor.spec.ts
@@ -55,7 +55,12 @@ describe('OfficeProcessor', () => {
expect(result.confidence).toBe(0.99);
expect(result.pageCount).toBe(1);
expect(result.language).toBe('deu');
- expect(mockParseOffice).toHaveBeenCalledWith(buffer, expect.any(Object));
+ expect(mockParseOffice).toHaveBeenCalledWith(buffer, {
+ outputErrorToConsole: false,
+ newlineDelimiter: '\n',
+ ignoreNotes: false,
+ putNotesAtLast: false
+ });
});
it('reports zero confidence and defaults language when no text is extracted', async () => {
diff --git a/apps/server/src/services/ocr/processors/pdf_processor.spec.ts b/apps/server/src/services/ocr/processors/pdf_processor.spec.ts
index 14ca32d18c..48fa740550 100644
--- a/apps/server/src/services/ocr/processors/pdf_processor.spec.ts
+++ b/apps/server/src/services/ocr/processors/pdf_processor.spec.ts
@@ -56,8 +56,10 @@ describe('PDFProcessor', () => {
{ proxy: true },
{ mergePages: true }
);
- // buffer is wrapped into a Uint8Array before being passed to unpdf
- expect(mockGetDocumentProxy).toHaveBeenCalledWith(expect.any(Uint8Array));
+ // buffer is wrapped into a Uint8Array carrying the SAME bytes before being passed to unpdf
+ const [docArg] = mockGetDocumentProxy.mock.calls[0];
+ expect(docArg).toBeInstanceOf(Uint8Array);
+ expect(Buffer.from(docArg as Uint8Array).toString()).toBe('%PDF-1.4 fake');
});
it('reports zero confidence and defaults language when no text is extracted', async () => {
diff --git a/apps/server/src/services/request.spec.ts b/apps/server/src/services/request.spec.ts
index 2b7012d16a..722e60cc82 100644
--- a/apps/server/src/services/request.spec.ts
+++ b/apps/server/src/services/request.spec.ts
@@ -396,11 +396,14 @@ describe("NodeRequestProvider.getImage", () => {
expect(state.requests[0].opts.agent).toBeNull();
});
- it("rejects non-2xx image responses", async () => {
+ it("rejects non-2xx image responses, and a late body does not override the rejection", async () => {
state.onEnd = (req) => {
const res = makeResponse(404, "Not Found");
req.triggerResponse(res);
- // Still resolves end after rejecting on the status code.
+ // getImage rejects on the status code but does not `return`, so it still
+ // wires up data/end handlers. A body arriving afterwards must NOT cause a
+ // late resolve that masks the rejection.
+ res.emitData(Buffer.from([1, 2, 3]));
res.emitEnd();
};
await expect(provider.getImage("http://img.example.com/missing.png")).rejects.toThrow(
diff --git a/apps/server/src/services/session_secret.spec.ts b/apps/server/src/services/session_secret.spec.ts
index 96aacc63e5..ec46a71345 100644
--- a/apps/server/src/services/session_secret.spec.ts
+++ b/apps/server/src/services/session_secret.spec.ts
@@ -20,7 +20,9 @@ describe("session_secret", () => {
}));
vi.doMock("./data_dir.js", () => ({ default: { TRILIUM_DATA_DIR: "/test/data" } }));
vi.doMock("./utils.js", () => ({
- randomSecureToken: (len: number) => "g".repeat(len)
+ // Return MORE than `len` chars so the source's `.slice(0, 64)` is
+ // actually exercised (real randomSecureToken returns a longer hex string).
+ randomSecureToken: (len: number) => "g".repeat(len * 2)
}));
vi.doMock("@triliumnext/core", () => ({ getLog: () => ({ info }) }));
@@ -30,6 +32,7 @@ describe("session_secret", () => {
it("generates, logs and persists a 64-char secret when none exists", async () => {
const { secret, writeFileSync, info } = await loadSecret({ exists: false });
+ // Truncated from the longer token to exactly 64 chars by the slice.
expect(secret).toHaveLength(64);
expect(info).toHaveBeenCalledOnce();
expect(writeFileSync).toHaveBeenCalledWith(
diff --git a/apps/server/src/services/special_notes.spec.ts b/apps/server/src/services/special_notes.spec.ts
index 3349764a42..d0429345b8 100644
--- a/apps/server/src/services/special_notes.spec.ts
+++ b/apps/server/src/services/special_notes.spec.ts
@@ -45,6 +45,12 @@ describe("special_notes (LLM chat, real DB)", () => {
});
describe("getMostRecentLlmChat / getRecentLlmChats", () => {
+ // Self-contained: don't rely on chats created by a sibling describe block
+ // (the in-memory DB is shared per file, so test order must not matter).
+ beforeAll(() => {
+ cls.init(() => specialNotes.createLlmChat());
+ });
+
it("returns the most recently modified chat and a mapped recent list", () => {
const recent = specialNotes.getRecentLlmChats(5);
expect(Array.isArray(recent)).toBe(true);