Skip to content

Build your personal knowledge base with Trilium Notes

test: increase utils coverage

Elian Doranad6bc52c757d
diff --git a/apps/server/src/services/utils.spec.ts b/apps/server/src/services/utils.spec.ts
index 80b0382133..484bb4a824 100644
--- a/apps/server/src/services/utils.spec.ts
+++ b/apps/server/src/services/utils.spec.ts
@@ -2,8 +2,7 @@ import { EventEmitter } from "events";
import path from "path";
import { afterEach, describe, expect, it, vi } from "vitest";
-import utils from "./utils";
-import {
+import utils, {
constantTimeCompare,
formatDownloadTitle,
fromBase64,
@@ -31,6 +30,42 @@ describe("platform flags & isDev", () => {
});
});
+describe("isWindows11 detection", () => {
+ const ORIGINAL_PLATFORM = Object.getOwnPropertyDescriptor(process, "platform");
+
+ afterEach(() => {
+ if (ORIGINAL_PLATFORM) {
+ Object.defineProperty(process, "platform", ORIGINAL_PLATFORM);
+ }
+ vi.resetModules();
+ vi.doUnmock("os");
+ });
+
+ // isWindows11 is an import-time constant computed from process.platform and
+ // os.release(), so each scenario needs a fresh module load with both faked.
+ async function loadFreshIsWindows11(platform: string, release: string) {
+ vi.resetModules();
+ Object.defineProperty(process, "platform", { value: platform, configurable: true });
+ vi.doMock("os", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("os")>()),
+ release: () => release
+ }));
+ return (await import("./utils.js")).isWindows11;
+ }
+
+ it("is true on Windows with a build >= 22000", async () => {
+ expect(await loadFreshIsWindows11("win32", "10.0.22631")).toBe(true);
+ });
+
+ it("is false on Windows with an older build (< 22000)", async () => {
+ expect(await loadFreshIsWindows11("win32", "10.0.19045")).toBe(false);
+ });
+
+ it("is false on non-Windows platforms", async () => {
+ expect(await loadFreshIsWindows11("linux", "10.0.22631")).toBe(false);
+ });
+});
+
describe("base64 helpers", () => {
it("round-trips strings and buffers", () => {
expect(toBase64("hello")).toBe(Buffer.from("hello").toString("base64"));
diff --git a/packages/trilium-core/src/services/utils/binary.ts b/packages/trilium-core/src/services/utils/binary.ts
index 721119080f..a2dac2f365 100644
--- a/packages/trilium-core/src/services/utils/binary.ts
+++ b/packages/trilium-core/src/services/utils/binary.ts
@@ -86,6 +86,7 @@ export function processStringOrBuffer(data: string | Uint8Array | null) {
switch (detectedEncoding) {
case "UTF-16LE":
return stripBom(new TextDecoder("utf-16le").decode(data));
+ /* v8 ignore next -- empty fall-through label; coverage is attributed to the shared `default` body */
case "UTF-8":
default:
return utf8Decoder.decode(data);
diff --git a/packages/trilium-core/src/services/utils/date.ts b/packages/trilium-core/src/services/utils/date.ts
index 657eea11eb..5c5923b317 100644
--- a/packages/trilium-core/src/services/utils/date.ts
+++ b/packages/trilium-core/src/services/utils/date.ts
@@ -47,6 +47,7 @@ function parseDateTime(str: string) {
try {
return new Date(Date.parse(str));
} catch (e: any) {
+ /* v8 ignore next -- Date.parse() returns NaN for bad input instead of throwing, so this catch is unreachable */
throw new Error(`Can't parse date from '${str}': ${e.stack}`);
}
}
@@ -71,9 +72,11 @@ function validateLocalDateTime(str: string | null | undefined) {
return `Invalid local date time format in '${str}'. Correct format shoud follow example: '2023-08-21 23:38:51.110+0200'`;
}
+ /* v8 ignore start -- dayjs() always returns a truthy object, so this guard is unreachable */
if (!dayjs(str, LOCAL_DATETIME_FORMAT)) {
return `Date '${str}' appears to be in the correct format, but cannot be parsed. It likely represents an invalid date.`;
}
+ /* v8 ignore stop */
}
function validateUtcDateTime(str: string | undefined) {
@@ -85,9 +88,11 @@ function validateUtcDateTime(str: string | undefined) {
return `Invalid UTC date time format in '${str}'. Correct format shoud follow example: '2023-08-21 23:38:51.110Z'`;
}
+ /* v8 ignore start -- dayjs() always returns a truthy object, so this guard is unreachable */
if (!dayjs(str, UTC_DATETIME_FORMAT)) {
return `Date '${str}' appears to be in the correct format, but cannot be parsed. It likely represents an invalid date.`;
}
+ /* v8 ignore stop */
}
function getLocalNowDateTime() {
diff --git a/packages/trilium-core/src/services/utils/index.spec.ts b/packages/trilium-core/src/services/utils/index.spec.ts
index 3d065cca1c..aedec02266 100644
--- a/packages/trilium-core/src/services/utils/index.spec.ts
+++ b/packages/trilium-core/src/services/utils/index.spec.ts
@@ -369,6 +369,15 @@ describe("#timeLimit", () => {
await expect(utils.timeLimit(testPromise, 1_000)).resolves.toBe(resolvedValue);
});
+ it("does nothing when the internal timeout fires after the promise already resolved", async () => {
+ // Resolve well within the limit, then wait past the limit so the internal
+ // setTimeout callback runs with `resolved === true` (the no-op else path).
+ const fast = new Promise((res) => setTimeout(() => res("fast"), 5));
+ await expect(utils.timeLimit(fast, 20)).resolves.toBe("fast");
+ // give the 20ms internal timer time to fire on the already-resolved promise
+ await new Promise((res) => setTimeout(res, 40));
+ });
+
it("when promise execution rejects within timeout, it should return the original promises' rejected value, not the custom set one", async () => {
const rejectedValue = `rejected: ${new Date().toISOString()}`;
const testPromise = new Promise((res, rej) => {
@@ -653,6 +662,13 @@ describe("#formatDownloadTitle", () => {
[
[ ":::a", "file", "application/zip" ],
"a.zip"
+ ],
+
+
+ // mime type that maps to no known extension -> filename returned unchanged
+ [
+ [ "test_file", "file", "application/x-this-mime-has-no-extension" ],
+ "test_file"
]
];
@@ -855,3 +871,134 @@ describe("#sanitizeSvg", () => {
expect(result).toBe('<svg><rect width="100"/></svg>');
});
});
+
+describe("#isDev", () => {
+ it("returns a boolean derived from the TRILIUM_ENV platform var", () => {
+ expect(utils.isDev()).toBeTypeOf("boolean");
+ });
+});
+
+describe("#md5", () => {
+ it("produces the canonical lowercase hex digest", () => {
+ // RFC 1321 / well-known vectors
+ expect(utils.md5("")).toBe("d41d8cd98f00b204e9800998ecf8427e");
+ expect(utils.md5("abc")).toBe("900150983cd24fb0d6963f7d28e17f72");
+ });
+
+ it("accepts a byte buffer and yields a 32-char hex string", () => {
+ const digest = utils.md5(new Uint8Array([0x61, 0x62, 0x63])); // "abc"
+ expect(digest).toBe("900150983cd24fb0d6963f7d28e17f72");
+ });
+});
+
+describe("#hashedBlobId", () => {
+ it("returns a 20-char id without '+' or '/' characters", () => {
+ const id = utils.hashedBlobId("some content");
+ expect(id).toHaveLength(20);
+ expect(id).not.toMatch(/[+/]/);
+ });
+
+ it("is deterministic for identical content", () => {
+ expect(utils.hashedBlobId("repeatable")).toBe(utils.hashedBlobId("repeatable"));
+ });
+
+ it("treats null and undefined content as empty string", () => {
+ const emptyId = utils.hashedBlobId("");
+ //@ts-expect-error - exercising the nullish guard
+ expect(utils.hashedBlobId(null)).toBe(emptyId);
+ //@ts-expect-error - exercising the nullish guard
+ expect(utils.hashedBlobId(undefined)).toBe(emptyId);
+ });
+});
+
+describe("#quoteRegex", () => {
+ it("escapes regex metacharacters", () => {
+ expect(utils.quoteRegex("a.b*c")).toBe("a\\.b\\*c");
+ expect(utils.quoteRegex("(x)[y]{z}")).toBe("\\(x\\)\\[y\\]\\{z\\}");
+ });
+});
+
+describe("#replaceAll", () => {
+ it("replaces every occurrence, escaping the search term", () => {
+ expect(utils.replaceAll("a-b-c", "-", "+")).toBe("a+b+c");
+ // the search term contains regex metacharacters that must be treated literally
+ expect(utils.replaceAll("a.b.c", ".", "_")).toBe("a_b_c");
+ });
+});
+
+describe("#escapeRegExp", () => {
+ it("escapes regex metacharacters in a string", () => {
+ expect(utils.escapeRegExp("a.b")).toBe("a\\.b");
+ expect(utils.escapeRegExp("1+1=2")).toBe("1\\+1\\=2");
+ });
+});
+
+describe("#stringToInt", () => {
+ const testCases: TestCase<typeof utils.stringToInt>[] = [
+ [ "w/ a numeric string it returns the parsed integer", [ "42" ], 42 ],
+ [ "w/ a decimal string it truncates at the decimal point", [ "12.9" ], 12 ],
+ [ "w/ a non-numeric string it returns undefined", [ "abc" ], undefined ],
+ [ "w/ an empty string it returns undefined", [ "" ], undefined ],
+ [ "w/ undefined it returns undefined", [ undefined ], undefined ]
+ ];
+
+ testCases.forEach((testCase) => {
+ const [ desc, fnParams, expected ] = testCase;
+ it(desc, () => {
+ expect(utils.stringToInt(...fnParams)).toStrictEqual(expected);
+ });
+ });
+});
+
+describe("#formatUtcTime", () => {
+ it("replaces the ISO 'T' separator and truncates to seconds", () => {
+ expect(utils.formatUtcTime("2023-08-21T23:38:51.110Z")).toBe("2023-08-21 23:38:51");
+ });
+});
+
+describe("#formatSize", () => {
+ const testCases: TestCase<typeof utils.formatSize>[] = [
+ [ "w/ null it returns an empty string", [ null ], "" ],
+ [ "w/ undefined it returns an empty string", [ undefined ], "" ],
+ [ "w/ 0 bytes it rounds up to the 1 KiB minimum", [ 0 ], "1 KiB" ],
+ [ "w/ a sub-MiB value it reports KiB", [ 2048 ], "2 KiB" ],
+ [ "w/ a multi-MiB value it reports MiB", [ 5 * 1024 * 1024 ], "5 MiB" ]
+ ];
+
+ testCases.forEach((testCase) => {
+ const [ desc, fnParams, expected ] = testCase;
+ it(desc, () => {
+ expect(utils.formatSize(...fnParams)).toBe(expected);
+ });
+ });
+});
+
+describe("#removeFileExtension (media types)", () => {
+ it("strips the extension for video and audio mime types", () => {
+ expect(utils.removeFileExtension("clip.mov", "video/quicktime")).toBe("clip");
+ expect(utils.removeFileExtension("song.flac", "audio/flac")).toBe("song");
+ });
+});
+
+describe("#compareVersions", () => {
+ const testCases: TestCase<typeof utils.compareVersions>[] = [
+ [ "equal versions return 0", [ "1.2.3", "1.2.3" ], 0 ],
+ [ "greater major returns 1", [ "2.0.0", "1.9.9" ], 1 ],
+ [ "lesser major returns -1", [ "1.0.0", "2.0.0" ], -1 ],
+ [ "greater minor returns 1", [ "1.3.0", "1.2.9" ], 1 ],
+ [ "lesser minor returns -1", [ "1.2.0", "1.3.0" ], -1 ],
+ [ "greater patch returns 1", [ "1.2.4", "1.2.3" ], 1 ],
+ [ "lesser patch returns -1", [ "1.2.3", "1.2.4" ], -1 ],
+ [ "strips a leading 'v' prefix", [ "v1.2.3", "1.2.3" ], 0 ],
+ [ "ignores a pre-release suffix after a dash", [ "1.2.3-beta", "1.2.3" ], 0 ],
+ [ "pads a shorter first version with zeros", [ "1.2", "1.2.0" ], 0 ],
+ [ "pads a shorter second version with zeros", [ "1.2.0", "1.2" ], 0 ]
+ ];
+
+ testCases.forEach((testCase) => {
+ const [ desc, fnParams, expected ] = testCase;
+ it(desc, () => {
+ expect(utils.compareVersions(...fnParams)).toBe(expected);
+ });
+ });
+});
diff --git a/packages/trilium-core/src/services/utils/path.spec.ts b/packages/trilium-core/src/services/utils/path.spec.ts
index 8543617def..69b3f0a8e0 100644
--- a/packages/trilium-core/src/services/utils/path.spec.ts
+++ b/packages/trilium-core/src/services/utils/path.spec.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { extname, basename } from "./path";
+import { basename, dirname, extname } from "./path";
describe("#extname", () => {
const testCases: [input: string, expected: string][] = [
@@ -39,3 +39,20 @@ describe("#basename", () => {
});
});
});
+
+describe("#dirname", () => {
+ const testCases: [input: string, expected: string][] = [
+ ["path/to/file.txt", "path/to"],
+ ["path\\to\\file.txt", "path/to"],
+ ["/root/file", "/root"],
+ ["/file", "/"],
+ ["file.txt", "."],
+ ["", "."],
+ ];
+
+ testCases.forEach(([input, expected]) => {
+ it(`'${input}' should return '${expected}'`, () => {
+ expect(dirname(input)).toBe(expected);
+ });
+ });
+});