A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
core: add more tests
Abdullah Atta84d68ca67be0
diff --git a/packages/core/__tests__/logger.test.ts b/packages/core/__tests__/logger.test.tsnew file mode 100644index 000000000..a2964ec5a--- /dev/null+++ b/packages/core/__tests__/logger.test.ts@@ -0,0 +1,86 @@+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2023 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++import { describe, it, expect } from "vitest";+import { initialize, logManager, logger } from "../src/logger";+import { SqliteDialect } from "kysely";+import BetterSQLite3 from "better-sqlite3-multiple-ciphers";+import { NoopLogger } from "@notesnook/logger";+import { delay } from "./utils";++async function initializeLogger() {+ await initialize(+ {+ dialect: (name) =>+ new SqliteDialect({+ database: BetterSQLite3(":memory:").unsafeMode(true)+ }),+ journalMode: "WAL",+ lockingMode: "exclusive",+ tempStore: "memory",+ synchronous: "normal",+ pageSize: 8192,+ cacheSize: -32000+ },+ true+ );+}++describe("Logger", () => {+ it("should initialize the logger", async () => {+ await initializeLogger();+ expect(logger).not.toBeInstanceOf(NoopLogger);+ expect(logManager).toBeDefined();+ });++ it("should log messages to the database", async () => {+ await initializeLogger();+ logger.log("Test message");+ await delay(500);+ const logs = await logManager?.get();+ expect(logs).toBeDefined();+ expect(logs?.length).toBe(1);+ expect(logs?.[0].logs[0].message).toBe("Test message");+ });++ it("should clear all logs from the database", async () => {+ await initializeLogger();+ logger.log("Test message 1");+ logger.log("Test message 2");+ logger.log("Test message 3");+ await delay(500);+ await logManager?.clear();+ const logs = await logManager?.get();+ expect(logs).toBeDefined();+ expect(logs?.length).toBe(0);+ });++ it("should delete logs with a specific key from the database", async () => {+ await initializeLogger();+ logger.log("Test message 1");+ logger.log("Test message 2");+ logger.log("Test message 3");+ await delay(500);+ const keyToDelete = (await logManager?.get())?.[0]?.key;+ await logManager?.delete(keyToDelete!);+ const logsAfterDeletion = await logManager?.get();+ expect(logsAfterDeletion).toBeDefined();+ expect(logsAfterDeletion?.length).toBe(0);+ });+});diff --git a/packages/core/src/api/sync/utils.ts b/packages/core/src/api/__tests__/healthcheck.test.tssimilarity index 54%rename from packages/core/src/api/sync/utils.tsrename to packages/core/src/api/__tests__/healthcheck.test.tsindex dd8cace8a..d3b12f8da 100644--- a/packages/core/src/api/sync/utils.ts+++ b/packages/core/src/api/__tests__/healthcheck.test.ts@@ -17,10 +17,25 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-export function areAllEmpty(obj: Record<string, unknown>) {- for (const key in obj) {- const value = obj[key];- if (Array.isArray(value) && value.length > 0) return false;- }- return true;-}+import { HealthCheck, check } from "../healthcheck";+import { describe } from "vitest";++describe.concurrent("Health check", (test) => {+ test("Auth", async (t) => {+ const result = await HealthCheck.auth();+ t.expect(result).toBe(true);+ });++ test("Healthy host", async (t) => {+ const host = "https://api.notesnook.com";+ const result = await check(host);+ t.expect(result).toBe(true);+ });++ test("Unhealthy host", async (t) => {+ const host = "https://example.com";+ // Simulate an error by passing an invalid host+ const result = await check(host);+ t.expect(result).toBe(false);+ });+});diff --git a/packages/core/src/api/healthcheck.ts b/packages/core/src/api/healthcheck.tsindex e0298a1e9..729d4fbab 100644--- a/packages/core/src/api/healthcheck.ts+++ b/packages/core/src/api/healthcheck.ts@@ -26,7 +26,7 @@ export class HealthCheck {}}-async function check(host: string) {+export async function check(host: string) {try {const response = await http.get(`${host}/health`);return response.trim() === "Healthy";diff --git a/packages/core/src/logger.ts b/packages/core/src/logger.tsindex ea6d0f5ca..c9988259e 100644--- a/packages/core/src/logger.ts+++ b/packages/core/src/logger.ts@@ -92,15 +92,18 @@ class DatabaseLogWriter {private hasCleared = false;constructor(private readonly db: Kysely<LogDatabaseSchema>) {- setInterval(() => {- setTimeout(() => {- if (!this.hasCleared) {- this.hasCleared = true;- this.rotate();- }- this.flush();- });- }, 10000);+ setInterval(+ () => {+ setTimeout(() => {+ if (!this.hasCleared) {+ this.hasCleared = true;+ this.rotate();+ }+ this.flush();+ });+ },+ process.env.NODE_ENV === "test" ? 200 : 10000+ );}push(message: LogMessage) {diff --git a/packages/core/src/utils/__tests__/content-block.test.ts b/packages/core/src/utils/__tests__/content-block.test.tsnew file mode 100644index 000000000..eb6d3a5f1--- /dev/null+++ b/packages/core/src/utils/__tests__/content-block.test.ts@@ -0,0 +1,120 @@+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2023 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++import { describe, it, expect } from "vitest";+import {+ extractInternalLinks,+ highlightInternalLinks,+ ellipsize+} from "../content-block";+import { ContentBlock } from "../../types";++describe("ContentBlock Utils", () => {+ describe("extractInternalLinks", () => {+ it("should extract internal links from a block", () => {+ const block: ContentBlock = {+ type: "someType",+ id: "someId",+ content: "This is a test [[nn://note/123|link]]"+ };+ const links = extractInternalLinks(block);+ expect(links).toHaveLength(1);+ expect(links[0].id).toBe("123");+ expect(links[0].text).toBe("link");+ });++ it("should return an empty array if no internal links are present", () => {+ const block: ContentBlock = {+ type: "someType",+ id: "someId",+ content: "This is a test with no links"+ };+ const links = extractInternalLinks(block);+ expect(links).toHaveLength(0);+ });++ it("should skip links with no noteId", () => {+ const block: ContentBlock = {+ type: "someType",+ id: "someId",+ content: "This is a test [[nn://note/|link]] with undefined URL"+ };+ const links = extractInternalLinks(block);+ expect(links).toHaveLength(0);+ });++ it("should extract internal links with '|' in id", () => {+ const block: ContentBlock = {+ type: "someType",+ id: "someId",+ content: "This is a test [[nn://note/myid|ofmyid|actualtext]]"+ };+ const links = extractInternalLinks(block);+ expect(links).toHaveLength(1);+ expect(links[0].id).toBe("myid|ofmyid");+ expect(links[0].text).toBe("actualtext");+ });+ });++ describe("highlightInternalLinks", () => {+ it("should highlight internal links in a block", () => {+ const block: ContentBlock = {+ type: "someType",+ id: "someId",+ content: "This is a test [[nn://note/123|link]]"+ };+ const noteId = "123";+ const highlighted = highlightInternalLinks(block, noteId);+ expect(highlighted).toHaveLength(1);+ expect(highlighted[0][1].highlighted).toBe(true);+ expect(highlighted[0][1].text).toBe("link");+ });++ it("should not highlight links with a different noteId", () => {+ const block: ContentBlock = {+ type: "someType",+ id: "someId",+ content: "This is a test [[nn://note/123|link]]"+ };+ const noteId = "456";+ const highlighted = highlightInternalLinks(block, noteId);+ expect(highlighted).toHaveLength(0);+ });+ });++ describe("ellipsize", () => {+ it("should ellipsize text from the start", () => {+ const text = "This is a long text that needs to be truncated";+ const result = ellipsize(text, 10, "start");+ expect(result).toBe("... truncated");+ });++ it("should ellipsize text from the end", () => {+ const text = "This is a long text that needs to be truncated";+ const result = ellipsize(text, 10, "end");+ expect(result).toBe("This is a ...");+ });++ it("should not ellipsize text if it is shorter than maxLength", () => {+ const text = "Short text";+ const result = ellipsize(text, 20, "end");+ expect(result).toBe("Short text");+ });+ });+});diff --git a/packages/core/src/utils/content-block.ts b/packages/core/src/utils/content-block.tsindex d38d4242b..82214aff8 100644--- a/packages/core/src/utils/content-block.ts+++ b/packages/core/src/utils/content-block.ts@@ -25,10 +25,10 @@ export function extractInternalLinks(block: ContentBlock) {const matches = block.content.matchAll(INTERNAL_LINK_REGEX);const links: InternalLinkWithOffset[] = [];- for (const match of matches || []) {+ for (const match of matches) {if (match.index === undefined) continue;- const url = match[1].slice(0, match[1].indexOf("|"));- const text = match[1].slice(match[1].indexOf("|") + 1);+ const url = match[1].slice(0, match[1].lastIndexOf("|"));+ const text = match[1].slice(match[1].lastIndexOf("|") + 1);const link = parseInternalLink(url);if (!link) continue;links.push({@@ -44,7 +44,6 @@ export function extractInternalLinks(block: ContentBlock) {function normalize(block: ContentBlock, links: InternalLinkWithOffset[]) {let diff = 0;- console.log(links);for (const link of links) {link.start -= diff;link.end -= diff;