/** * Tests of deployment (G17): reading untrusted servers, progress, log * lines and test-connection answers; the save params (no read-only * fields); the status-bar item (progress with Cancel); upload and download * through the UI commands with their toasts (no default server opens the * dialog); the servers dialog (save with a write-only secret that is never * shown again, test connection, the unknown and the changed host key, and * remove after asking); the Deployment log; and the registration of the * UI commands. The engine is a fake behind the mocked Tauri `invoke` and * `listen`. */ import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; import { createPinia, setActivePinia, type Pinia } from "pinia"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const invoke = vi.hoisted(() => vi.fn()); const listen = vi.hoisted(() => vi.fn()); vi.mock("@tauri-apps/api/core", () => ({ invoke })); vi.mock("@tauri-apps/api/event", () => ({ listen })); import { useCommandsStore } from "../../src/commands/store"; import { UI_COMMANDS } from "../../src/commands/uiCommands"; import DeployStatusItem from "../../src/components/deploy/DeployStatusItem.vue"; import DeploymentLogToolWindow from "../../src/components/deploy/DeploymentLogToolWindow.vue"; import { blankServer, toEntry, toProgress, toSaveParams, toServer, toTest, useDeployStore, } from "../../src/components/deploy/deploy"; import { useNotificationsStore } from "../../src/stores/notifications"; import { useProjectStore } from "../../src/stores/project"; /** The test password; it must never show anywhere. */ const SECRET = "Otter-UI-Pa55!"; /** A recorded engine call. */ interface Call { /** Command id. */ command: string; /** Its params. */ params: Record; } let calls: Call[]; let servers: unknown; let testAnswer: unknown; let failures: Record; let listeners: ((event: { payload: unknown }) => void)[]; let pinia: Pinia; let mounted: VueWrapper[]; /** The calls of a command. */ function callsOf(command: string): Call[] { return calls.filter((c) => c.command === command); } /** Sends an engine event to every listener. */ async function emit(payload: unknown): Promise { for (const listener of listeners) { listener({ payload }); } await flushPromises(); } /** The texts of the toasts shown. */ function toasts(): string[] { return useNotificationsStore(pinia).toasts.map((toast) => toast.text); } /** A server as the engine lists it. */ const STAGING = { id: "s1", name: "Staging", kind: "sftp", host: "staging.example", user: "deploy", root: "/var/www", auth: "password", mappings: [{ local: "public", remote: "html" }], excluded: [".env"], uploadOnSave: false, secretKind: "password", hasSecret: true, }; /** Mounts the status-bar item with a project open. */ async function mountItem(): Promise { useProjectStore(pinia).root = { root: "C:/p", name: "p" } as never; const wrapper = mount(DeployStatusItem, { attachTo: document.body, global: { plugins: [pinia] } }); mounted.push(wrapper); await useCommandsStore(pinia).start(); await flushPromises(); return wrapper; } beforeEach(() => { pinia = createPinia(); setActivePinia(pinia); calls = []; mounted = []; failures = {}; listeners = []; servers = { servers: [STAGING], defaultServer: "s1" }; testAnswer = { ok: true, message: "Connected to Staging; the root folder /var/www exists." }; invoke.mockReset(); listen.mockReset(); listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => { listeners.push(callback); return Promise.resolve(() => { listeners = listeners.filter((l) => l !== callback); }); }); invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { if (cmd === "engine_list_commands") { return Promise.resolve( ["deploy.servers", "deploy.upload", "deploy.download"].map((id) => ({ id, label: id, enabled: true })), ); } if ((cmd !== "engine_execute" && cmd !== "engine_execute_waiting") || !args) { return Promise.resolve(null); } calls.push({ command: args.command, params: args.params }); const failure = failures[args.command]; if (failure) { return Promise.reject(Object.assign(new Error(failure.message), failure)); } switch (args.command) { case "deploy.servers": return Promise.resolve(servers); case "deploy.saveServer": return Promise.resolve({ server: { ...STAGING, ...(args.params.server as object), id: "s1" } }); case "deploy.testConnection": return Promise.resolve(testAnswer); case "deploy.upload": return Promise.resolve({ files: 3, bytes: 10, skipped: 1, failed: 0 }); case "deploy.download": return Promise.resolve({ files: 1, bytes: 10, skipped: 0, failed: 0 }); case "deploy.log": return Promise.resolve({ entries: [{ id: 1, time: 0, level: "info", server: "Staging", message: "public/index.php → html/index.php" }], }); default: return Promise.resolve({}); } }); }); afterEach(() => { for (const wrapper of mounted) { wrapper.unmount(); } document.body.innerHTML = ""; }); describe("reading the engine's answers", () => { it("reads servers and drops malformed ones", () => { expect(toServer(STAGING)?.mappings).toEqual([{ local: "public", remote: "html" }]); expect(toServer({ ...STAGING, kind: "gopher" })).toBeNull(); expect(toServer({ ...STAGING, id: "" })).toBeNull(); expect(toServer({ ...STAGING, auth: "magic", port: 2.5 })).toMatchObject({ auth: "password", port: null }); expect(toServer(null)).toBeNull(); }); it("reads progress, log lines and test answers", () => { expect( toProgress({ kind: "deployProgress", active: true, operation: "upload", server: "S", filesDone: 2, filesTotal: 5, file: "a.php" }), ).toMatchObject({ operation: "upload", filesDone: 2, filesTotal: 5, file: "a.php" }); expect(toProgress({ kind: "deployProgress", active: false, operation: "upload" })).toBeNull(); expect(toProgress({ kind: "deployProgress", active: true, operation: "rm" })).toBeNull(); expect(toEntry({ id: 1, time: 5, level: "error", server: "S", message: "x" })).toMatchObject({ level: "error" }); expect(toEntry({ id: 1, level: "loud" })).toBeNull(); const asked = toTest("s1", { ok: false, message: "unknown", hostKey: { status: "unknown", host: "h:22", algorithm: "ssh-ed25519", fingerprint: "SHA256:abc" }, }); expect(asked.question).toMatchObject({ serverId: "s1", status: "unknown", fingerprint: "SHA256:abc" }); expect(toTest("s1", { ok: false, needsSecret: "passphrase" }).outcome.needsSecret).toBe("passphrase"); expect(toTest("s1", null).outcome.ok).toBe(false); }); it("sends only editable fields when saving", () => { const params = toSaveParams({ ...blankServer(), name: "New", host: "h", user: "u", hasSecret: true, mappings: [{ local: " public ", remote: "html" }, { local: "", remote: " " }], excluded: [" .env ", ""], }); expect(params).not.toHaveProperty("id"); expect(params).not.toHaveProperty("hasSecret"); expect(params).not.toHaveProperty("secretKind"); expect(params.mappings).toEqual([{ local: "public", remote: "html" }]); expect(params.excluded).toEqual([".env"]); expect(toSaveParams({ ...blankServer(), kind: "ftp", auth: "agent" }).auth).toBe("password"); }); }); describe("status bar and commands", () => { it("shows progress with Cancel and hides when done", async () => { const wrapper = await mountItem(); expect(wrapper.find("[data-test='deploy-progress']").exists()).toBe(false); await emit({ kind: "deployProgress", active: true, operation: "upload", server: "Staging", filesDone: 1, filesTotal: 4, phase: "transferring" }); expect(wrapper.find("[data-test='deploy-progress']").text()).toContain("1/4"); await wrapper.find("[data-test='deploy-cancel']").trigger("click"); await flushPromises(); expect(callsOf("deploy.cancel")).toHaveLength(1); await emit({ kind: "deployProgress", active: false, operation: "upload" }); expect(wrapper.find("[data-test='deploy-progress']").exists()).toBe(false); }); it("uploads and downloads a path through the UI commands", async () => { await mountItem(); const commands = useCommandsStore(pinia); await commands.execute("deployment.upload", { path: "public" }); await flushPromises(); expect(callsOf("deploy.upload")[0]?.params).toEqual({ paths: ["public"] }); expect(toasts().some((t) => t.includes("3 files") && t.includes("Staging"))).toBe(true); await commands.execute("deployment.download", { path: "public/index.php" }); await flushPromises(); expect(callsOf("deploy.download")[0]?.params).toEqual({ paths: ["public/index.php"] }); expect(toasts().some((t) => t.includes("1 file from"))).toBe(true); await commands.execute("deployment.uploadProject"); await flushPromises(); expect(callsOf("deploy.upload")[1]?.params).toEqual({ paths: [""] }); }); it("explains a failed upload and opens the dialog without a default server", async () => { failures["deploy.upload"] = { code: "failed", message: "the host key of h:22 is not known yet" }; await mountItem(); const commands = useCommandsStore(pinia); await commands.execute("deployment.upload", { path: "a.php" }); await flushPromises(); expect(toasts().some((t) => t.includes("host key"))).toBe(true); servers = { servers: [], defaultServer: null }; await useDeployStore(pinia).load(); await commands.execute("deployment.upload", { path: "a.php" }); await flushPromises(); expect(callsOf("deploy.upload")).toHaveLength(1); expect(useDeployStore(pinia).dialogOpen).toBe(true); }); it("registers the UI commands with menu paths and without shortcuts", () => { for (const id of ["deployment.upload", "deployment.download", "deployment.uploadProject", "deployment.testConnection", "deployment.servers", "deployment.showLog"]) { const spec = UI_COMMANDS.find((c) => c.id === id); expect(spec?.menuPath?.startsWith("Tools/Deployment/")).toBe(true); expect(spec?.defaultShortcut).toBeUndefined(); } }); }); describe("servers dialog", () => { it("saves with a write-only secret and tests the connection", async () => { const wrapper = await mountItem(); await useDeployStore(pinia).showDialog(); await flushPromises(); expect(wrapper.find("[data-test='deploy-dialog']").exists()).toBe(true); const secret = wrapper.find("[data-test='deploy-secret']"); expect(secret.attributes("type")).toBe("password"); expect(secret.element.value).toBe(""); expect(secret.attributes("placeholder")).toContain("keychain"); await secret.setValue(SECRET); await wrapper.find("[data-test='deploy-upload-on-save']").setValue(true); await wrapper.find("[data-test='deploy-test']").trigger("click"); await flushPromises(); const saved = callsOf("deploy.saveServer")[0]?.params; expect(saved?.secret).toBe(SECRET); expect((saved?.server as Record).uploadOnSave).toBe(true); expect(callsOf("deploy.testConnection")[0]?.params).toEqual({ id: "s1" }); expect(wrapper.find("[data-test='deploy-tested']").text()).toContain("exists"); expect(wrapper.find("[data-test='deploy-secret']").element.value).toBe(""); expect(document.body.innerHTML).not.toContain(SECRET); }); it("asks about an unknown host key and trusts it", async () => { testAnswer = { ok: false, message: "unknown", hostKey: { status: "unknown", host: "staging.example:22", algorithm: "ssh-ed25519", fingerprint: "SHA256:fp1" }, }; const wrapper = await mountItem(); await useDeployStore(pinia).showDialog(); await flushPromises(); await wrapper.find("[data-test='deploy-test']").trigger("click"); await flushPromises(); expect(wrapper.find("[data-test='deploy-hostkey']").text()).toContain("SHA256:fp1"); testAnswer = { ok: true, message: "Connected." }; await wrapper.find("[data-test='deploy-trust']").trigger("click"); await flushPromises(); expect(callsOf("deploy.trustHostKey")[0]?.params).toEqual({ id: "s1", algorithm: "ssh-ed25519", fingerprint: "SHA256:fp1", replace: false, }); expect(callsOf("deploy.testConnection")).toHaveLength(2); expect(wrapper.find("[data-test='deploy-hostkey']").exists()).toBe(false); }); it("warns about a changed host key and replaces it only on the explicit button", async () => { testAnswer = { ok: false, message: "changed", hostKey: { status: "changed", host: "h:22", algorithm: "ssh-ed25519", fingerprint: "SHA256:new", known: "SHA256:old" }, }; const wrapper = await mountItem(); await useDeployStore(pinia).showDialog(); await flushPromises(); await wrapper.find("[data-test='deploy-test']").trigger("click"); await flushPromises(); const box = wrapper.find("[data-test='deploy-hostkey']"); expect(box.text()).toContain("SHA256:old"); expect(box.text()).toContain("SHA256:new"); expect(wrapper.find("[data-test='deploy-trust']").exists()).toBe(false); await wrapper.find("[data-test='deploy-replace']").trigger("click"); await flushPromises(); expect(callsOf("deploy.trustHostKey")[0]?.params).toMatchObject({ replace: true }); }); it("removes a server only after asking", async () => { const wrapper = await mountItem(); await useDeployStore(pinia).showDialog(); await flushPromises(); await wrapper.find("[data-test='deploy-remove']").trigger("click"); expect(callsOf("deploy.removeServer")).toHaveLength(0); await wrapper.find("[data-test='deploy-remove']").trigger("click"); await flushPromises(); expect(callsOf("deploy.removeServer")[0]?.params).toEqual({ id: "s1" }); }); }); describe("deployment log", () => { it("shows the kept log and new lines, and clears", async () => { await mountItem(); const deploy = useDeployStore(pinia); deploy.showLog(); const wrapper = mount(DeploymentLogToolWindow, { global: { plugins: [pinia] } }); mounted.push(wrapper); await flushPromises(); expect(wrapper.findAll("[data-test='deploy-log-line']")).toHaveLength(1); await emit({ kind: "deployLog", entry: { id: 2, time: 0, level: "error", server: "Staging", message: "a.php: denied" } }); const lines = wrapper.findAll("[data-test='deploy-log-line']"); expect(lines).toHaveLength(2); expect(lines[1]?.classes()).toContain("deploy-log__line--error"); await wrapper.find("[data-test='deploy-log-clear']").trigger("click"); await flushPromises(); expect(callsOf("deploy.clearLog")).toHaveLength(1); expect(wrapper.findAll("[data-test='deploy-log-line']")).toHaveLength(0); }); });