/** * Tests of the remotes feature (M4.10): reading untrusted `gitProgress` * and `git.remotes`, the repository name and folder of a clone, the * status-bar item (progress with Cancel, ahead/behind, hidden when in * step), fetch / pull / push through the UI commands with their toasts * (pull saves first, a failed save cancels it, git's explained refusal, * a cancelled call), the Clone dialog (Browse…, the folder following the * URL, the clone then `project.open`, git's refusal in the dialog), the * Manage Remotes dialog (list, add, edit without the redacted URL, remove * after asking), 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 RemoteStatusItem from "../../src/components/vcs/remote/RemoteStatusItem.vue"; import { joinPath, repoName, toProgress, toRemotes, useRemoteStore } from "../../src/components/vcs/remote/remote"; import { useNotificationsStore } from "../../src/stores/notifications"; import { useVcsStatusStore } from "../../src/stores/vcsStatus"; /** A recorded engine call. */ interface Call { /** `engine_execute` or `engine_execute_waiting`. */ via: string; /** Command id. */ command: string; /** Its params. */ params: Record; } /** Every engine call, in order. */ let calls: Call[]; /** What `git.status` answers. */ let gitStatus: unknown; /** What `git.remotes` answers. */ let gitRemotes: unknown; /** Errors to throw, by command id. */ let failures: Record; /** What `file.saveAll` answers. */ let saveAll: unknown; /** What `pick_dir` answers. */ let picked: string | null; /** Event listeners registered through `listen`. */ let listeners: ((event: { payload: unknown }) => void)[]; /** Pinia of the current test. */ let pinia: Pinia; /** Mounted components, unmounted after each test. */ let mounted: VueWrapper[]; /** * The calls of a command. * * @param command - the command id. */ function callsOf(command: string): Call[] { return calls.filter((c) => c.command === command); } /** * Sends an engine event to every listener. * * @param payload - the event. */ 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); } /** Mounts the status-bar item with started stores. */ async function mountItem(): Promise { useVcsStatusStore(pinia).start(); const wrapper = mount(RemoteStatusItem, { 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 = []; picked = null; gitStatus = { available: true, repo: { root: "C:/p", branch: "main", detached: false, head: "0123", upstream: "origin/main", ahead: 0, behind: 0 }, files: [], }; gitRemotes = { remotes: [ { name: "origin", fetchUrl: "https://***@github.com/a/b.git", pushUrl: "git@github.com:a/b.git" }, { name: "fork", fetchUrl: "git@forgejo.example:me/b.git" }, ], }; saveAll = { saved: [], failed: [], skipped: [] }; 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( ["git.status", "git.fetch", "git.pull", "git.push", "git.remotes", "git.clone"].map((id) => ({ id, label: id, enabled: true, })), ); } if (cmd === "pick_dir") { return Promise.resolve(picked); } if ((cmd !== "engine_execute" && cmd !== "engine_execute_waiting") || !args) { return Promise.resolve(null); } calls.push({ via: cmd, 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 "git.status": return Promise.resolve(gitStatus); case "git.remotes": return Promise.resolve(gitRemotes); case "git.push": return Promise.resolve({ remote: "origin", branch: "feature", upstreamSet: true }); case "git.clone": return Promise.resolve({ root: String(args.params.dir) }); case "git.cancel": return Promise.resolve({ cancelled: true }); case "file.saveAll": return Promise.resolve(saveAll); default: return Promise.resolve({}); } }); }); afterEach(() => { for (const wrapper of mounted) { wrapper.unmount(); } useVcsStatusStore(pinia).stop(); document.body.innerHTML = ""; }); describe("reading the engine's answers", () => { it("reads gitProgress and drops what is not running or malformed", () => { expect( toProgress({ kind: "gitProgress", active: true, operation: "push", phase: "Writing objects", percent: 42.4 }), ).toEqual({ operation: "push", phase: "Writing objects", percent: 42 }); expect(toProgress({ kind: "gitProgress", active: true, operation: "clone", percent: 300 })).toEqual({ operation: "clone", phase: "", percent: 100, }); expect(toProgress({ kind: "gitProgress", active: false, operation: "fetch" })).toBeNull(); expect(toProgress({ kind: "gitProgress", active: true, operation: "rm -rf" })).toBeNull(); expect(toProgress({ kind: "projectClosed" })).toBeNull(); }); it("reads git.remotes and drops malformed entries", () => { expect( toRemotes({ remotes: [{ name: "o", fetchUrl: "u", pushUrl: "" }, { name: "" }, null, "x", { name: "p", fetchUrl: 3 }] }), ).toEqual([ { name: "o", fetchUrl: "u", pushUrl: null }, { name: "p", fetchUrl: "", pushUrl: null }, ]); expect(toRemotes(null)).toEqual([]); expect(toRemotes({ remotes: "no" })).toEqual([]); }); it("names the clone folder after the repository", () => { expect(repoName("https://github.com/owner/lutra.git")).toBe("lutra"); expect(repoName("git@forgejo.example:me/site.GIT/")).toBe("site"); expect(repoName("C:\\repos\\tool")).toBe("tool"); expect(repoName("")).toBe(""); expect(joinPath("C:\\src", "lutra")).toBe("C:\\src\\lutra"); expect(joinPath("/home/me/", "lutra")).toBe("/home/me/lutra"); expect(joinPath("C:/src", "lutra")).toBe("C:/src/lutra"); }); }); describe("the status-bar item", () => { it("shows the running call with Cancel, then ahead and behind", async () => { const wrapper = await mountItem(); expect(wrapper.find("[data-test=remote-progress]").exists()).toBe(false); expect(wrapper.find("[data-test=remote-sync]").exists()).toBe(false); await emit({ kind: "gitProgress", active: true, operation: "fetch", phase: "Receiving objects", percent: 45 }); expect(wrapper.get("[data-test=remote-progress]").text()).toBe("Fetching: Receiving objects 45%"); expect(useRemoteStore(pinia).busy).toBe(true); expect(useCommandsStore(pinia).isEnabled("vcs.push")).toBe(false); await wrapper.get("[data-test=remote-cancel]").trigger("click"); await flushPromises(); expect(callsOf("git.cancel")).toHaveLength(1); expect(callsOf("git.cancel")[0]?.via).toBe("engine_execute"); await emit({ kind: "gitProgress", active: false, operation: "fetch" }); expect(wrapper.find("[data-test=remote-progress]").exists()).toBe(false); expect(useCommandsStore(pinia).isEnabled("vcs.push")).toBe(true); gitStatus = { available: true, repo: { root: "C:/p", branch: "main", detached: false, upstream: "origin/main", ahead: 2, behind: 1 }, files: [], }; await useVcsStatusStore(pinia).refresh(); await flushPromises(); expect(wrapper.get("[data-test=remote-sync]").text().replace(/\s+/g, "")).toBe("21"); expect(wrapper.get("[data-test=remote-sync]").attributes("aria-label")).toBe( "2 commits to push and 1 to pull (origin/main)", ); }); }); describe("fetch, pull and push", () => { it("pushes and says when the upstream was set", async () => { await mountItem(); await useCommandsStore(pinia).execute("vcs.push"); await flushPromises(); expect(callsOf("git.push")).toEqual([{ via: "engine_execute_waiting", command: "git.push", params: {} }]); expect(toasts()).toContain("Pushed feature to origin and set it as the upstream"); }); it("saves before a pull and cancels it when a save fails", async () => { await mountItem(); await useCommandsStore(pinia).execute("vcs.pull"); await flushPromises(); const order = calls.map((c) => c.command).filter((c) => c === "file.saveAll" || c === "git.pull"); expect(order).toEqual(["file.saveAll", "git.pull"]); expect(toasts()).toContain("Pulled the current branch"); saveAll = { saved: [], failed: [{ id: 3, path: "a.php", message: "denied" }], skipped: [] }; calls = []; await useCommandsStore(pinia).execute("vcs.pull"); await flushPromises(); expect(callsOf("git.pull")).toHaveLength(0); expect(toasts()).toContain("Pull cancelled: not every file could be saved first."); }); it("shows git's explained refusal, and a cancelled call as information", async () => { await mountItem(); failures["git.push"] = { code: "failed", message: "The push was rejected: the remote branch has commits that your branch does not have.", }; await useCommandsStore(pinia).execute("vcs.push"); await flushPromises(); expect(toasts().at(-1)).toBe( "Push failed: The push was rejected: the remote branch has commits that your branch does not have.", ); expect(useNotificationsStore(pinia).toasts.at(-1)?.level).toBe("error"); failures["git.fetch"] = { code: "failed", message: "the Git operation was cancelled" }; await useCommandsStore(pinia).execute("vcs.fetch"); await flushPromises(); expect(toasts().at(-1)).toBe("Git operation cancelled"); expect(useNotificationsStore(pinia).toasts.at(-1)?.level).toBe("info"); }); }); describe("Clone Repository", () => { it("proposes the folder from Browse… and the URL, clones and opens the project", async () => { const wrapper = await mountItem(); await useCommandsStore(pinia).execute("vcs.clone"); await flushPromises(); const dialog = wrapper.get("[data-test=clone-dialog]"); expect(document.activeElement).toBe(dialog.get("[data-test=clone-url]").element); await dialog.get("[data-test=clone-url]").setValue("https://github.com/owner/lutra.git"); picked = "C:\\src"; await dialog.get("[data-test=clone-browse]").trigger("click"); await flushPromises(); expect((dialog.get("[data-test=clone-dir]").element as HTMLInputElement).value).toBe("C:\\src\\lutra"); await dialog.get("[data-test=clone-url]").setValue("git@forgejo.example:me/site.git"); await flushPromises(); expect((dialog.get("[data-test=clone-dir]").element as HTMLInputElement).value).toBe("C:\\src\\site"); await dialog.get("[data-test=clone-run]").trigger("click"); await flushPromises(); expect(callsOf("git.clone")[0]?.params).toEqual({ url: "git@forgejo.example:me/site.git", dir: "C:\\src\\site" }); expect(callsOf("project.open")[0]?.params).toEqual({ path: "C:\\src\\site" }); expect(wrapper.find("[data-test=clone-dialog]").exists()).toBe(false); expect(toasts()).toContain("Cloned into C:\\src\\site"); }); it("keeps the dialog with git's refusal and asks for both fields", async () => { const wrapper = await mountItem(); await useCommandsStore(pinia).execute("vcs.clone"); await flushPromises(); await wrapper.get("[data-test=clone-run]").trigger("click"); await flushPromises(); expect(wrapper.get("[data-test=clone-error]").text()).toBe("Enter a URL and a folder."); expect(callsOf("git.clone")).toHaveLength(0); failures["git.clone"] = { code: "failed", message: "The remote repository was not found. Check the URL and that you have access to it.", }; await wrapper.get("[data-test=clone-url]").setValue("https://github.com/nope/nope.git"); await wrapper.get("[data-test=clone-dir]").setValue("C:/src/nope"); await wrapper.get("[data-test=clone-url]").trigger("keydown", { key: "Enter" }); await flushPromises(); expect(wrapper.get("[data-test=clone-error]").text()).toContain("was not found"); expect(callsOf("project.open")).toHaveLength(0); await wrapper.get("[data-test=clone-url]").trigger("keydown", { key: "Escape" }); expect(wrapper.find("[data-test=clone-dialog]").exists()).toBe(false); }); }); describe("Manage Remotes", () => { it("lists, adds, edits and removes remotes", async () => { const wrapper = await mountItem(); await useCommandsStore(pinia).execute("vcs.manageRemotes"); await flushPromises(); const origin = wrapper.get("[data-test=remote-origin]"); expect(origin.text()).toContain("https://***@github.com/a/b.git"); expect(origin.text()).toContain("push: git@github.com:a/b.git"); expect(wrapper.get("[data-test=remote-fork]").text()).toContain("git@forgejo.example:me/b.git"); await wrapper.get("[data-test=remote-new-name]").setValue("upstream"); await wrapper.get("[data-test=remote-new-url]").setValue(" https://gitlab.com/x/b.git "); await wrapper.get("[data-test=remote-add]").trigger("submit"); await flushPromises(); expect(callsOf("git.remoteAdd")[0]?.params).toEqual({ name: "upstream", url: "https://gitlab.com/x/b.git" }); expect(callsOf("git.remotes")).toHaveLength(2); await origin.get("[data-test=remote-edit]").trigger("click"); const field = wrapper.get("[data-test=remote-edit-url]"); expect((field.element as HTMLInputElement).value).toBe(""); await field.setValue("https://bitbucket.org/a/b.git"); await wrapper.get("[data-test=remote-save]").trigger("click"); await flushPromises(); expect(callsOf("git.remoteSetUrl")[0]?.params).toEqual({ name: "origin", url: "https://bitbucket.org/a/b.git" }); failures["git.remoteRemove"] = { code: "failed", message: "error: No such remote: 'fork'" }; await wrapper.get("[data-test=remote-fork]").get("[data-test=remote-remove]").trigger("click"); await wrapper.get("[data-test=remote-remove-yes]").trigger("click"); await flushPromises(); expect(callsOf("git.remoteRemove")[0]?.params).toEqual({ name: "fork" }); expect(wrapper.get("[data-test=remotes-error]").text()).toBe("error: No such remote: 'fork'"); }); }); describe("registration", () => { it("adds the remote commands to the Git menu without default shortcuts", () => { const ids = ["vcs.clone", "vcs.fetch", "vcs.manageRemotes", "vcs.pull", "vcs.push"]; for (const id of ids) { const spec = UI_COMMANDS.find((c) => c.id === id); expect(spec?.menuPath?.startsWith("Git/")).toBe(true); expect(spec?.defaultShortcut).toBeUndefined(); } }); });