Skip to content

Build your personal knowledge base with Trilium Notes

start again: improve test coverage

Adorian Doran97bf5bbc6537
diff --git a/apps/client/src/services/setup_auth.spec.ts b/apps/client/src/services/setup_auth.spec.ts
new file mode 100644
index 0000000000..fb6821ee4b
--- /dev/null
+++ b/apps/client/src/services/setup_auth.spec.ts
@@ -0,0 +1,38 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+/** A fresh module each time, since what it holds is deliberately process-wide. */
+async function freshModule() {
+ vi.resetModules();
+ return import("./setup_auth.js");
+}
+
+beforeEach(() => vi.resetModules());
+
+describe("the token that unlocks a wizard standing over a knowledge base", () => {
+ it("holds nothing until the password has bought one", async () => {
+ // What the request layer puts on every call, and `null` is what keeps the header off every
+ // page but an unlocked wizard.
+ const { getSetupAuthToken } = await freshModule();
+
+ expect(getSetupAuthToken()).toBeNull();
+ });
+
+ it("hands back what it was given, for as long as the page lives", async () => {
+ const { getSetupAuthToken, setSetupAuthToken } = await freshModule();
+
+ setSetupAuthToken("a-token");
+
+ expect(getSetupAuthToken()).toBe("a-token");
+ });
+
+ it("keeps nothing across a reload, which asks for the password again", async () => {
+ // Held in memory only, which is the right answer for a screen that can erase a knowledge
+ // base and is often left open on a shared machine.
+ const first = await freshModule();
+ first.setSetupAuthToken("a-token");
+
+ const reloaded = await freshModule();
+
+ expect(reloaded.getSetupAuthToken()).toBeNull();
+ });
+});
diff --git a/apps/client/src/setup.spec.tsx b/apps/client/src/setup.spec.tsx
index 9c6ad4f47e..c45be401e3 100644
--- a/apps/client/src/setup.spec.tsx
+++ b/apps/client/src/setup.spec.tsx
@@ -8,6 +8,15 @@ vi.mock("./services/i18n", () => ({
getCurrentLanguage: () => "en"
}));
+// The language screen reads its own `t` off the react-i18next context, which no provider supplies
+// here. Mocked to the same key-echo, so it renders rather than throwing on a null context.
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ i18n: { language: "en", changeLanguage: vi.fn(async () => {}) }
+ })
+}));
+
const serverMock = vi.hoisted(() => ({
// Default implementation serves the module-load-time requests transitively imported
// modules fire (e.g. keyboard_actions fetches its shortcut list on import) — the
@@ -18,7 +27,7 @@ const serverMock = vi.hoisted(() => ({
}
return {};
}),
- post: vi.fn(async (): Promise<unknown> => ({}))
+ post: vi.fn(async (_url: string, _data?: unknown): Promise<unknown> => ({}))
}));
vi.mock("./services/server", () => ({ default: serverMock }));
@@ -80,6 +89,203 @@ describe("the unlock screen, as the wizard renders it", () => {
});
});
+describe("the menu, and what each way out of it commits to", () => {
+ /** Renders the menu as the wizard does, so the wiring between the two is covered as well. */
+ function renderMenu(setState = vi.fn()) {
+ renderInto(renderState("firstOptions", setState));
+ return setState;
+ }
+
+ function card(title: string) {
+ return [ ...container.querySelectorAll<HTMLElement>(".setup-option-card") ]
+ .find((element) => element.querySelector("h3")?.textContent === title);
+ }
+
+ beforeEach(() => {
+ window.glob.hasExistingData = undefined;
+ vi.stubGlobal("confirm", vi.fn(() => true));
+ });
+
+ afterEach(() => {
+ window.glob.hasExistingData = undefined;
+ vi.unstubAllGlobals();
+ });
+
+ it("offers the way back only while there is something to go back to", async () => {
+ renderMenu();
+ await flushEffects();
+ expect(card("setup.keep-existing")).toBeUndefined();
+
+ render(null, container);
+ window.glob.hasExistingData = true;
+ renderMenu();
+ await flushEffects();
+ expect(card("setup.keep-existing")).toBeDefined();
+ });
+
+ it("leaves the knowledge base alone and reopens it when that way back is taken", async () => {
+ window.glob.hasExistingData = true;
+ renderMenu();
+ await flushEffects();
+
+ card("setup.keep-existing")?.click();
+ await flushEffects();
+
+ expect(serverMock.post).toHaveBeenCalledWith("setup/existing/keep");
+ expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/delete");
+ });
+
+ it("walks a first run straight to the screen it picked, with nothing to erase", async () => {
+ const setState = renderMenu();
+ await flushEffects();
+
+ card("setup.new-document")?.click();
+ expect(setState).toHaveBeenCalledWith("createNewDocumentOptions");
+
+ card("setup.restore-from-backup")?.click();
+ expect(setState).toHaveBeenCalledWith("restoreFromBackup");
+
+ card("setup.sync-from-server")?.click();
+ expect(setState).toHaveBeenCalledWith("syncFromServer");
+
+ expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/delete");
+ });
+
+ describe("connecting a desktop app, the one path that erases from here", () => {
+ // Every other path erases at the moment it creates a database, server-side. This one waits
+ // for another device to push one, and decides it has arrived by seeing a schema appear —
+ // which the knowledge base already here would satisfy on its own. So arriving on the screen
+ // is what commits, and the erasure happens on the way in.
+ it("asks with the browser's own dialog before erasing, then waits for the push", async () => {
+ window.glob.hasExistingData = true;
+ const setState = renderMenu();
+ await flushEffects();
+
+ card("setup.sync-from-desktop")?.click();
+ await flushEffects();
+
+ expect(window.confirm).toHaveBeenCalledWith("setup.existing-data-erase-confirm");
+ expect(serverMock.post).toHaveBeenCalledWith("setup/existing/delete");
+ expect(setState).toHaveBeenCalledWith("syncFromDesktop");
+ });
+
+ it("erases nothing and goes nowhere when that dialog is answered no", async () => {
+ window.glob.hasExistingData = true;
+ vi.stubGlobal("confirm", vi.fn(() => false));
+ const setState = renderMenu();
+ await flushEffects();
+
+ card("setup.sync-from-desktop")?.click();
+ await flushEffects();
+
+ expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/delete");
+ expect(setState).not.toHaveBeenCalled();
+ });
+
+ it("asks nothing on a first run, which has nothing to clear out of the way", async () => {
+ const setState = renderMenu();
+ await flushEffects();
+
+ card("setup.sync-from-desktop")?.click();
+ await flushEffects();
+
+ expect(window.confirm).not.toHaveBeenCalled();
+ expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/delete");
+ expect(setState).toHaveBeenCalledWith("syncFromDesktop");
+ });
+
+ it("stays put and says why when the erasure fails, rather than waiting on a push it cannot take", async () => {
+ window.glob.hasExistingData = true;
+ serverMock.post.mockImplementation(async (url: string) => {
+ if (url === "setup/existing/delete") {
+ throw new Error("the database is in use");
+ }
+ return {};
+ });
+ const setState = renderMenu();
+ await flushEffects();
+
+ card("setup.sync-from-desktop")?.click();
+ await flushEffects();
+
+ expect(container.querySelector(".page-error")?.textContent).toContain("the database is in use");
+ expect(setState).not.toHaveBeenCalled();
+ });
+ });
+});
+
+describe("the language step, as the wizard renders it", () => {
+ it("leads to the offer of a copy, or past it where there is nothing to copy", async () => {
+ // The step it leads to is worked out rather than named, and was a hardcoded state before
+ // the language moved in front of the offer — so the wiring is worth asserting, not just
+ // the function behind it.
+ const setState = vi.fn();
+ window.glob.hasExistingData = true;
+ renderInto(renderState("selectLanguage", setState));
+ await flushEffects();
+
+ container.querySelector<HTMLElement>("footer button")?.click();
+ expect(setState).toHaveBeenCalledWith("existingData");
+
+ render(null, container);
+ window.glob.hasExistingData = undefined;
+ const firstRun = vi.fn();
+ renderInto(renderState("selectLanguage", firstRun));
+ await flushEffects();
+
+ container.querySelector<HTMLElement>("footer button")?.click();
+ expect(firstRun).toHaveBeenCalledWith("firstOptions");
+ });
+});
+
+describe("creating the knowledge base", () => {
+ it("asks for the demo content or not, and finishes when the server is done", async () => {
+ renderInto(renderState("createNewDocumentWithDemo", vi.fn()));
+ await flushEffects();
+ expect(serverMock.post).toHaveBeenCalledWith("setup/new-document", { locale: "en" });
+
+ render(null, container);
+ serverMock.post.mockClear();
+ renderInto(renderState("createNewDocumentEmpty", vi.fn()));
+ await flushEffects();
+ expect(serverMock.post).toHaveBeenCalledWith("setup/new-document?skipDemoDb", { locale: "en" });
+ });
+
+ it("says what stopped it instead of spinning, and offers a way back", async () => {
+ // This screen has nothing to poll and no other way of ending, so a request that comes back
+ // with an error would otherwise leave it turning for as long as anyone watched it.
+ const setState = vi.fn();
+ serverMock.post.mockRejectedValue('{"message":"DB not open."}');
+ renderInto(renderState("createNewDocumentEmpty", setState));
+ await flushEffects();
+
+ expect(container.querySelector(".page-error")?.textContent).toContain("DB not open.");
+ expect(container.textContent).toContain("setup.create-new-document-failed");
+
+ container.querySelector<HTMLElement>(".back-button")?.click();
+ expect(setState).toHaveBeenCalledWith("createNewDocumentOptions");
+ });
+
+ it("reads whatever the failure had to say, in each of the shapes one arrives in", async () => {
+ // A rejected request is not an Error: the client's own layer rejects with the response body
+ // as a string, which is JSON for a server error and a bare word when the browser dropped it.
+ for (const [ rejection, expected ] of [
+ [ new Error("an Error"), "an Error" ],
+ [ '{"message":"a JSON body"}', "a JSON body" ],
+ [ "rejected by browser", "rejected by browser" ],
+ [ 42, "42" ]
+ ] as const) {
+ serverMock.post.mockRejectedValue(rejection);
+ renderInto(renderState("createNewDocumentEmpty", vi.fn()));
+ await flushEffects();
+
+ expect(container.querySelector(".page-error")?.textContent).toContain(expected);
+ render(null, container);
+ container.remove();
+ }
+ });
+});
+
describe("SyncInProgress", () => {
it("switches to the failure screen when the server reports a failed sync", async () => {
const setState = vi.fn();
diff --git a/apps/client/src/setup_existing.spec.tsx b/apps/client/src/setup_existing.spec.tsx
index ce452d2759..c39cfb52c3 100644
--- a/apps/client/src/setup_existing.spec.tsx
+++ b/apps/client/src/setup_existing.spec.tsx
@@ -179,6 +179,43 @@ describe("offering a copy of the existing knowledge base", () => {
expect(serverMock.post).toHaveBeenCalledWith("setup/existing/keep");
expect(onKept).toHaveBeenCalled();
});
+
+ it("stays put and says why when the database will not reopen", async () => {
+ // Cancel is the way out of every screen here, so a failure in it has to be visible: the
+ // alternative is a button that does nothing and a user with no idea why.
+ serverMock.post.mockRejectedValue('{"message":"the database would not open"}');
+ renderScreens();
+ await settle();
+
+ button("setup.existing-data-cancel")?.click();
+ await settle();
+
+ expect(container.querySelector(".page-error")?.textContent).toContain("the database would not open");
+ expect(onKept).not.toHaveBeenCalled();
+ expect(container.querySelector("input[type=radio]")).not.toBeNull();
+ });
+
+ it("reads whatever the failure had to say, in each of the shapes one arrives in", async () => {
+ // A rejected request is not an Error: the client's own layer rejects with the response body
+ // as a string, which is JSON for a server error and a bare word when the browser dropped it.
+ for (const [ rejection, expected ] of [
+ [ new Error("an Error"), "an Error" ],
+ [ "rejected by browser", "rejected by browser" ],
+ [ { message: "an object carrying one" }, "an object carrying one" ],
+ [ 42, "setup.existing-data-keep-failed" ]
+ ] as const) {
+ serverMock.post.mockRejectedValue(rejection);
+ renderScreens();
+ await settle();
+
+ button("setup.existing-data-cancel")?.click();
+ await settle();
+
+ expect(container.querySelector(".page-error")?.textContent).toContain(expected);
+ render(null, container);
+ container.remove();
+ }
+ });
});
describe("backing it up first", () => {
@@ -200,6 +237,24 @@ describe("backing it up first", () => {
await settle();
}
+ it("still offers the plainest backup there is when the instance's own answers cannot be read", async () => {
+ // Losing the prefilled answers is not worth losing the backup over.
+ serverMock.get.mockImplementation(async (url: string) =>
+ (url === "setup/existing/backup-defaults" ? Promise.reject(new Error("no answer")) : {}));
+ renderScreens();
+ await settle();
+
+ choose("back-up");
+ await settle();
+ button("setup.continue")?.click();
+ await settle();
+
+ expect(container.textContent).toContain("setup.backup-name");
+ // Offered, and off: the fallback is a backup with nothing switched on.
+ expect(container.textContent).toContain("setup.backup-compress");
+ expect(container.textContent).not.toContain("setup.backup-use-stored-password");
+ });
+
it("asks what the backup should be before taking it, and sends those answers", async () => {
serverMock.get.mockImplementation(async (url: string) =>
(url === "setup/existing/backup-defaults"
diff --git a/apps/client/src/setup_existing.tsx b/apps/client/src/setup_existing.tsx
index 614c774ba9..21afdc55b4 100644
--- a/apps/client/src/setup_existing.tsx
+++ b/apps/client/src/setup_existing.tsx
@@ -509,7 +509,10 @@ export async function getBackupDefaults(): Promise<SetupBackupDefaults> {
*/
export async function deleteExistingData(): Promise<void> {
await server.post("setup/existing/delete");
- discarded = true;
+ // The wizard's own account of what is behind it, kept in step with what now is. Written back
+ // onto the bootstrap's own answer rather than tracked beside it: the two can never disagree,
+ // since the only erasure any of these screens can cause is the one just above.
+ window.glob.hasExistingData = false;
}
/** Leaves it alone and opens it, which is what every Cancel in the wizard does. */
@@ -520,12 +523,10 @@ export function keepExistingData(): Promise<void> {
/**
* Whether there is still a knowledge base behind the wizard.
*
- * What the start of the wizard reported, minus anything erased since. The flag is not re-read from
- * the server because the two answers cannot disagree: the only erasure this page can cause is the
- * one below.
+ * What the start of the wizard reported, until something here erases it. Not re-read from the
+ * server: a reload would ask the server again anyway, and within one run of the wizard this is the
+ * only thing that changes the answer.
*/
export function hasExistingData(): boolean {
- return !discarded && window.glob.hasExistingData === true;
+ return window.glob.hasExistingData === true;
}
-
-let discarded = false;
diff --git a/apps/client/src/setup_unlock.spec.tsx b/apps/client/src/setup_unlock.spec.tsx
index d104522155..cb1c92dcb4 100644
--- a/apps/client/src/setup_unlock.spec.tsx
+++ b/apps/client/src/setup_unlock.spec.tsx
@@ -95,6 +95,53 @@ describe("unlocking a wizard that is standing over a knowledge base", () => {
expect(password()).not.toBeNull();
});
+ it("says so on a connection that failed, which a wrong password never looks like", async () => {
+ // A refused password is answered, not thrown. Anything landing here is the connection, or
+ // the rate limiter counting the attempts.
+ serverMock.post.mockRejectedValue(new Error("network down"));
+ renderScreen();
+ await settle();
+
+ submit();
+ await settle();
+
+ expect(container.querySelector(".page-error")?.textContent).toContain("login.connection-error");
+ expect(onUnlocked).not.toHaveBeenCalled();
+ });
+
+ it("refuses the answer where the server said yes but handed nothing over", async () => {
+ serverMock.post.mockResolvedValue({ authenticated: true });
+ renderScreen();
+ await settle();
+
+ submit();
+ await settle();
+
+ expect(setSetupAuthToken).not.toHaveBeenCalled();
+ expect(onUnlocked).not.toHaveBeenCalled();
+ });
+
+ it("does not ask twice over while an answer is still coming", async () => {
+ // The button is disabled while it runs, but Enter in the field is a second way in.
+ let answer: (value: unknown) => void = () => {};
+ serverMock.post.mockImplementation(() => new Promise((resolve) => {
+ answer = resolve;
+ }));
+ renderScreen();
+ await settle();
+
+ submit();
+ await settle();
+ submit();
+ await settle();
+
+ expect(serverMock.post).toHaveBeenCalledOnce();
+
+ answer({ authenticated: true, token: "a-token" });
+ await settle();
+ expect(onUnlocked).toHaveBeenCalled();
+ });
+
it("reads the password off the field at submit time, not from state", async () => {
// A controlled value of "" overwrites what the browser autofilled, so the first press would
// submit an empty password — the "incorrect password, press again" bug the login screen hit.
diff --git a/apps/server/src/services/setup_marker.spec.ts b/apps/server/src/services/setup_marker.spec.ts
index c611546daf..46475c9920 100644
--- a/apps/server/src/services/setup_marker.spec.ts
+++ b/apps/server/src/services/setup_marker.spec.ts
@@ -2,7 +2,7 @@ import { SETUP_MARKER_FILE_NAME } from "@triliumnext/commons";
import { getSql } from "@triliumnext/core";
import fs from "fs";
import path from "path";
-import { afterAll, afterEach, describe, expect, it } from "vitest";
+import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
import dataDirs from "./data_dir.js";
import { consumeSetupMarker, setupPlatform } from "./setup_marker.js";
@@ -28,6 +28,23 @@ describe("the marker a start finds", () => {
expect(consumeSetupMarker()).toBeNull();
});
+ it("still acts on one it could not delete, and says so", async () => {
+ // A marker left behind sends the next start into the wizard as well, which is exactly the
+ // trap deleting it on read avoids — so it is worth a line in the log rather than a silence.
+ const { getLog } = await import("@triliumnext/core");
+ writeMarkerFile(JSON.stringify({ lang: "de" }));
+ const error = vi.spyOn(getLog(), "error").mockImplementation(() => {});
+ vi.spyOn(fs, "rmSync").mockImplementation(() => {
+ throw new Error("EACCES");
+ });
+
+ // What it asked for still stands: the start it belongs to should act on it either way.
+ expect(consumeSetupMarker()).toEqual({ lang: "de" });
+ expect(error).toHaveBeenCalledWith(expect.stringContaining("Could not remove the setup marker"));
+
+ vi.restoreAllMocks();
+ });
+
it("is removed even when it could not be read, so a bad one cannot trap the instance", () => {
writeMarkerFile("half a file, written by a start that was interrupted");
diff --git a/packages/trilium-core/src/routes/api/setup.spec.ts b/packages/trilium-core/src/routes/api/setup.spec.ts
index cd28610f63..b3a1008767 100644
--- a/packages/trilium-core/src/routes/api/setup.spec.ts
+++ b/packages/trilium-core/src/routes/api/setup.spec.ts
@@ -1,9 +1,12 @@
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import appInfo from "../../services/app_info";
+import { getBackup } from "../../services/backup";
import * as passwordService from "../../services/encryption/password";
+import passwordEncryptionService from "../../services/encryption/password_encryption";
import optionService from "../../services/options";
import setupService from "../../services/setup";
+import { isSetupAuthorized, resetSetupAuth } from "../../services/setup_auth";
import {
enterSetupMode,
initSetupPlatform,
@@ -222,6 +225,176 @@ describe("Setup API with a knowledge base behind the wizard (core)", () => {
});
});
+describe("asking the next start to be the wizard (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ beforeEach(() => initSetupPlatform(platform));
+
+ afterEach(() => {
+ Object.values(platform).forEach((fn) => fn.mockClear());
+ vi.restoreAllMocks();
+ });
+
+ it("writes a marker carrying the instance's own language, and no screen unless one was named", async () => {
+ // The language cannot be read from the marker's own request: by the time it is acted on the
+ // database it came from is deliberately closed, so it has to be carried across.
+ vi.spyOn(optionService, "getOptionOrNull").mockImplementation((name) => (name === "locale" ? "ro" : null));
+
+ const res = await api.post("/api/setup/boot");
+
+ expect(res.status).toBe(204);
+ expect(platform.writeMarker).toHaveBeenCalledWith({ lang: "ro" });
+ });
+
+ it("falls back to English where the instance has no language of its own recorded", async () => {
+ vi.spyOn(optionService, "getOptionOrNull").mockReturnValue(null);
+
+ await api.post("/api/setup/boot");
+
+ expect(platform.writeMarker).toHaveBeenCalledWith({ lang: "en" });
+ });
+
+ it("carries a screen the caller named, and drops one it made up", async () => {
+ vi.spyOn(optionService, "getOptionOrNull").mockReturnValue("en");
+
+ await api.post("/api/setup/boot", { body: { targetScreen: "restore-backup" } });
+ expect(platform.writeMarker).toHaveBeenLastCalledWith({ lang: "en", targetScreen: "restore-backup" });
+
+ // Two of the wizard's screens create a database the moment they are shown. A request must
+ // not be able to name one, so anything unrecognised is dropped rather than carried.
+ await api.post("/api/setup/boot", { body: { targetScreen: "createNewDocumentEmpty" } });
+ expect(platform.writeMarker).toHaveBeenLastCalledWith({ lang: "en" });
+ });
+});
+
+describe("unlocking the wizard (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ beforeEach(() => {
+ resetSetupAuth();
+ initSetupPlatform(platform);
+ enterSetupMode({ lang: "en" });
+ vi.spyOn(passwordService, "isPasswordSet").mockReturnValue(true);
+ });
+
+ afterEach(() => {
+ leaveSetupMode();
+ resetSetupAuth();
+ vi.restoreAllMocks();
+ });
+
+ it("hands back a token for the right password", async () => {
+ vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(true);
+
+ const res = await api.post<{ authenticated: boolean; token?: string }>(
+ "/api/setup/auth", { body: { password: "hunter2" } });
+
+ expect(res.status).toBe(200);
+ expect(res.body.authenticated).toBe(true);
+ expect(isSetupAuthorized(res.body.token)).toBe(true);
+ });
+
+ it("says only no for the wrong one, and hands back nothing to go on", async () => {
+ vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(false);
+
+ const res = await api.post<{ authenticated: boolean; token?: string }>(
+ "/api/setup/auth", { body: { password: "wrong" } });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ authenticated: false });
+ });
+
+ it("treats a body that carries no password as an empty one rather than failing on it", async () => {
+ // The body arrives from a client and may be anything at all, including nothing.
+ const verify = vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(false);
+
+ await api.post("/api/setup/auth", { body: {} });
+ await api.post("/api/setup/auth", { body: { password: 42 } });
+
+ expect(verify).toHaveBeenNthCalledWith(1, "");
+ expect(verify).toHaveBeenNthCalledWith(2, "");
+ });
+});
+
+describe("what becomes of the knowledge base behind the wizard (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ beforeEach(() => {
+ initSetupPlatform(platform);
+ enterSetupMode({ lang: "en" });
+ });
+
+ afterEach(() => {
+ leaveSetupMode();
+ Object.values(platform).forEach((fn) => fn.mockClear());
+ vi.restoreAllMocks();
+ });
+
+ it("starts a backup and follows it through the status, rather than waiting on the request", async () => {
+ // The write runs for minutes on a large knowledge base, and on standalone a request rides
+ // the service worker, whose fetches the browser reclaims long before that.
+ const written = { fileName: "b.tnbackup", filePath: "/b/b.tnbackup", directoryPath: "/b", fileSize: 12 };
+ const backup = getBackup() as { backupAs?: unknown };
+ const previous = backup.backupAs;
+ backup.backupAs = async () => written;
+
+ const started = await api.post("/api/setup/existing/backup", { body: { name: "Before the change" } });
+ expect(started.status).toBe(204);
+
+ await vi.waitFor(async () => {
+ const res = await api.get<{ state: string; result?: typeof written }>("/api/setup/existing/status");
+ expect(res.body.state).toBe("done");
+ expect(res.body.result).toEqual(written);
+ });
+
+ backup.backupAs = previous;
+ });
+
+ it("offers back the answers this instance already backs up under", async () => {
+ vi.spyOn(optionService, "getOptionOrNull").mockImplementation((name) =>
+ (name === "backupEnableCompression" ? "true" : "false"));
+
+ const res = await api.get<{ compress: boolean; encrypt: boolean; storedPassphrase: boolean }>(
+ "/api/setup/existing/backup-defaults");
+
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ compress: true, encrypt: false });
+ // Whether there is a passphrase, never what it is: a screen that could read it could be
+ // made to hand it over.
+ expect(typeof res.body.storedPassphrase).toBe("boolean");
+ });
+
+ it("erases it when that is what was asked for, and refuses to a second time", async () => {
+ const erased = await api.post("/api/setup/existing/delete");
+
+ expect(erased.status).toBe(204);
+ expect(platform.removeDatabase).toHaveBeenCalledOnce();
+
+ // Asked again, there is nothing left to act on and the route says so rather than erasing a
+ // file that is already gone.
+ const again = await api.post<{ message?: string }>("/api/setup/existing/delete");
+ expect(again.status).toBe(500);
+ expect(platform.removeDatabase).toHaveBeenCalledOnce();
+ });
+
+ it("puts the instance back on the database it was booted away from", async () => {
+ vi.spyOn(sqlInit, "initDbConnection").mockResolvedValue(undefined);
+
+ const res = await api.post("/api/setup/existing/keep");
+
+ expect(res.status).toBe(204);
+ // The marker goes first: a start that finds one comes up as the wizard all over again.
+ expect(platform.removeMarker).toHaveBeenCalled();
+ expect(platform.removeDatabase).not.toHaveBeenCalled();
+ });
+});
+
/** A platform whose marker and database are only ever written down as having been asked for. */
const platform = {
writeMarker: vi.fn(async () => {}),
diff --git a/packages/trilium-core/src/services/setup_existing.spec.ts b/packages/trilium-core/src/services/setup_existing.spec.ts
index 0fa26eadbb..794fa8c8e7 100644
--- a/packages/trilium-core/src/services/setup_existing.spec.ts
+++ b/packages/trilium-core/src/services/setup_existing.spec.ts
@@ -129,6 +129,20 @@ describe("what becomes of the existing database", () => {
expect(platform.removeDatabase).not.toHaveBeenCalled();
});
+ it("says so rather than half-starting where the platform cannot write a backup at all", async () => {
+ // The standalone platform streams its backup into a download and has no `backupAs`. Both
+ // ways in have to refuse, and the one that answers before it starts has to refuse loudest:
+ // the screen behind it waits on a status that would otherwise never change.
+ const backup = getBackup() as { backupAs?: unknown };
+ const previous = backup.backupAs;
+ backup.backupAs = undefined;
+
+ await expect(backUpExistingData(ANY_SETTINGS)).rejects.toThrow(/cannot write a backup/);
+ expect(() => startBackUpExistingData(new Date())).toThrow(/cannot write a backup/);
+
+ backup.backupAs = previous;
+ });
+
it("refuses every one of them where there is no existing database to act on", async () => {
leaveSetupMode();