/** * Tests of the diff viewer (M4.3): reading the untrusted params and * `git.show` results, line-break normalisation, `vcs.showDiff` opening a * "Diff: " tab with the index (or HEAD for the staged view) on the * left and the working copy's buffer on the right, edits on the right * reaching the engine through the buffer, engine changes reaching the right * side, left side refresh on `gitChanged`, notices for binary, too large, * failed and deleted files, switching between diff and editor tabs, the * next/previous change commands and the project tree's context menu. The * engine is a fake behind the mocked Tauri `invoke` and `listen`. */ import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; import { EditorView } from "@codemirror/view"; 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 EditorArea from "../../src/components/editor/EditorArea.vue"; import { emitEngineEvent } from "../../src/components/project/engineEvents"; import ProjectToolWindow from "../../src/components/project/ProjectToolWindow.vue"; import { diffKey, normaliseEol, parseShowDiff, refFor, toShowResult, useDiffStore, } from "../../src/components/vcs/diff/diff"; import { currentMerge } from "../../src/components/vcs/diff/navigation"; import { useEditorStore } from "../../src/stores/editor"; import { useNotificationsStore } from "../../src/stores/notifications"; import { useProjectStore } from "../../src/stores/project"; /** A buffer of the fake engine. */ interface FakeBuffer { path: string; text: string; version: number; saved: number; } /** Fake engine buffers by id. */ let buffers: Map; /** Files in the working copy. */ let disk: Record; /** What `git.show` answers, by `ref:path`; missing entries mean "not at that ref". */ let blobs: Record; /** Errors to throw, by command id. */ let failures: Record; /** Next buffer id. */ let nextId: number; /** Every engine call, in order. */ let calls: { via: string; command: string; params: Record }[]; /** Engine event callbacks of every subscription. */ let listeners: ((event: { payload: unknown }) => void)[]; /** Pinia of the current test. */ let pinia: Pinia; /** Mounted components. */ let mounted: VueWrapper[]; /** * Sends an engine event to every subscription. * * @param payload - the event. */ async function emit(payload: unknown): Promise { for (const listener of [...listeners]) { listener({ payload }); } await flushPromises(); } /** * Describes a buffer as `file.open` and `buffer.get` do. * * @param id - buffer id. */ function describeBuffer(id: number): unknown { const b = buffers.get(id); return b ? { id, path: b.path, text: b.text, version: b.version, dirty: b.version !== b.saved, lineEnding: b.text.includes("\r\n") ? "crlf" : "lf" } : null; } /** * Rejects like the shell does with an engine error. * * @param code - error code. * @param message - error text. */ function fail(code: string, message = code): Promise { return Promise.reject(Object.assign(new Error(message), { code, message })); } /** * The fake engine. * * @param command - command id. * @param p - params. */ function execute(command: string, p: Record): Promise { const failure = failures[command]; if (failure) { return fail(failure.code, failure.message); } const id = typeof p.id === "number" ? p.id : -1; const b = buffers.get(id); switch (command) { case "git.show": { const blob = blobs[`${String(p.ref)}:${String(p.path)}`]; return Promise.resolve(blob === undefined ? { text: null, binary: false, tooLarge: false } : blob); } case "file.open": { const path = String(p.path); for (const [existing, buffer] of buffers) { if (buffer.path === path) { return Promise.resolve(describeBuffer(existing)); } } const text = disk[path]; if (text === undefined) { return fail("failed", `${path}: file not found`); } const newId = nextId++; buffers.set(newId, { path, text, version: 1, saved: 1 }); return Promise.resolve(describeBuffer(newId)); } case "buffer.get": return b ? Promise.resolve(describeBuffer(id)) : fail("failed"); case "buffer.edit": { if (!b) { return fail("failed"); } if (p.baseVersion !== b.version) { return fail("stale_version"); } let out = ""; let pos = 0; for (const e of p.edits as { from: number; to: number; insert: string }[]) { out += b.text.slice(pos, e.from) + e.insert; pos = e.to; } b.text = out + b.text.slice(pos); b.version += 1; return Promise.resolve({ id, version: b.version, dirty: true }); } case "project.children": return Promise.resolve({ dir: "", entries: Object.keys(disk).map((path) => ({ name: path, path, kind: "file", ignored: false, role: null })), truncated: false, }); default: return Promise.resolve({}); } } /** * The calls of a command. * * @param command - the command id. */ function callsOf(command: string): { via: string; command: string; params: Record }[] { return calls.filter((c) => c.command === command); } /** jsdom has no layout; CodeMirror measures text ranges, so give ranges empty rectangles. */ function stubRangeGeometry(): void { const empty = (): DOMRectList => Object.assign([] as DOMRect[], { item: () => null }); Range.prototype.getClientRects = empty; Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0); } /** Mounts the editor area with the keymap and an open project. */ async function mountArea(): Promise { await useCommandsStore(pinia).start(); useProjectStore(pinia).root = { path: "/p", name: "p" }; const wrapper = mount(EditorArea, { attachTo: document.body, slots: { default: "empty" }, global: { plugins: [pinia] } }); mounted.push(wrapper); await flushPromises(); return wrapper; } /** * Runs a command through the command store and waits for it. * * @param id - command id. * @param params - its params. */ async function runCommand(id: string, params: Record = {}): Promise { await useCommandsStore(pinia).execute(id, params as never); await vi.dynamicImportSettled(); await flushPromises(); } /** Both sides of the merge view. */ function sides(): { a: EditorView; b: EditorView } { const merge = currentMerge(); if (!merge) { throw new Error("no merge view"); } return { a: merge.a, b: merge.b }; } beforeEach(() => { stubRangeGeometry(); Element.prototype.scrollIntoView = () => undefined; pinia = createPinia(); setActivePinia(pinia); buffers = new Map(); disk = { "a.php": " 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([]); } if ((cmd === "engine_execute" || cmd === "engine_execute_waiting") && args) { calls.push({ via: cmd, command: args.command, params: args.params }); return execute(args.command, args.params); } return Promise.resolve(null); }); }); afterEach(async () => { await flushPromises(); useCommandsStore(pinia).stop(); for (const wrapper of mounted) { wrapper.unmount(); } document.body.innerHTML = ""; }); describe("helpers", () => { it("normalises every line break to LF", () => { expect(normaliseEol("a\r\nb\rc\nd")).toBe("a\nb\nc\nd"); expect(normaliseEol("")).toBe(""); }); it("reads the params of vcs.showDiff", () => { expect(parseShowDiff({})).toEqual({ path: null, staged: false }); expect(parseShowDiff({ path: "a.php", staged: true })).toEqual({ path: "a.php", staged: true }); expect(parseShowDiff(null)).toEqual({ path: null, staged: false }); expect(parseShowDiff({ path: 3 })).toBeNull(); expect(parseShowDiff({ path: "" })).toBeNull(); expect(parseShowDiff({ path: "a", staged: "yes" })).toBeNull(); }); it("reads git.show results and picks the ref", () => { expect(toShowResult({ text: "x", binary: false, tooLarge: false })).toEqual({ text: "x", binary: false, tooLarge: false }); expect(toShowResult({ text: null, binary: true })).toEqual({ text: null, binary: true, tooLarge: false }); expect(toShowResult({ text: 5 })).toBeNull(); expect(toShowResult([])).toBeNull(); expect(toShowResult("x")).toBeNull(); expect(refFor(true)).toBe("HEAD"); expect(refFor(false)).toBe("index"); expect(diffKey("a", true)).not.toBe(diffKey("a", false)); }); }); describe("vcs.showDiff", () => { it("opens a diff tab: index on the left (CRLF normalised), the working copy's buffer on the right", async () => { const area = await mountArea(); await runCommand("vcs.showDiff", { path: "a.php", staged: false }); expect(callsOf("git.show")).toEqual([{ via: "engine_execute_waiting", command: "git.show", params: { path: "a.php", ref: "index" } }]); expect(area.findAll("[data-test=diff-tab]").map((t) => t.text())).toEqual(["Diff: a.php"]); expect(area.find("[data-test=diff-tab]").attributes("aria-selected")).toBe("true"); expect(area.find("[data-test=editor-tab]").attributes("aria-selected")).toBe("false"); expect(area.find("[data-test=code-editor]").exists()).toBe(false); expect(area.find("[data-test=diff-caption]").text()).toContain("staged version"); const { a, b } = sides(); expect(a.state.doc.toString()).toBe(" { const area = await mountArea(); await runCommand("vcs.showDiff", { path: "a.php", staged: true }); expect(callsOf("git.show")[0]?.params).toEqual({ path: "a.php", ref: "HEAD" }); expect(sides().a.state.doc.toString()).toBe(" { await mountArea(); await useEditorStore(pinia).openFile("a.php"); await runCommand("vcs.showDiff"); expect(callsOf("git.show")[0]?.params).toEqual({ path: "a.php", ref: "index" }); expect(useDiffStore(pinia).activeTab?.path).toBe("a.php"); }); it("refuses bad params and a missing file with an error toast", async () => { await mountArea(); await runCommand("vcs.showDiff", { path: 7 }); await runCommand("vcs.showDiff"); const texts = useNotificationsStore(pinia).toasts.map((toast) => toast.text); expect(texts.some((text) => text.includes("{path?: string"))).toBe(true); expect(texts.some((text) => text.includes("Open a file"))).toBe(true); expect(callsOf("git.show")).toHaveLength(0); }); it("is disabled without a project", async () => { await mountArea(); useProjectStore(pinia).root = null; expect(useCommandsStore(pinia).isEnabled("vcs.showDiff")).toBe(false); }); }); describe("editing and refreshing", () => { it("sends edits on the right through the buffer", async () => { await mountArea(); await runCommand("vcs.showDiff", { path: "a.php" }); const { b } = sides(); b.dispatch({ changes: { from: 0, insert: "// x\n" }, userEvent: "input.type" }); await flushPromises(); const edits = callsOf("buffer.edit"); expect(edits).toHaveLength(1); expect(edits[0]?.params.edits).toEqual([{ from: 0, to: 0, insert: "// x\n" }]); expect(buffers.get(1)?.text).toBe("// x\n { await mountArea(); await runCommand("vcs.showDiff", { path: "a.php" }); const buffer = buffers.get(1); if (!buffer) { throw new Error("no buffer"); } buffer.text = " { await mountArea(); await runCommand("vcs.showDiff", { path: "a.php" }); blobs["index:a.php"] = { text: " { const area = await mountArea(); await runCommand("vcs.showDiff", { path: "a.php" }); await emit({ kind: "bufferClosed", id: 1 }); await flushPromises(); expect(area.findAll("[data-test=diff-tab]")).toHaveLength(0); }); }); describe("notices", () => { it("shows a notice for binary and too large files without opening the file", async () => { blobs["index:img.png"] = { text: null, binary: true, tooLarge: false }; blobs["index:big.sql"] = { text: null, binary: false, tooLarge: true }; const area = await mountArea(); await runCommand("vcs.showDiff", { path: "img.png" }); expect(area.find("[data-test=diff-notice]").text()).toContain("Binary file"); await runCommand("vcs.showDiff", { path: "big.sql" }); expect(area.find("[data-test=diff-notice]").text()).toContain("too large"); expect(callsOf("file.open")).toHaveLength(0); expect(currentMerge()).toBeNull(); }); it("shows git's error", async () => { failures["git.show"] = { code: "failed", message: "fatal: bad object" }; const area = await mountArea(); await runCommand("vcs.showDiff", { path: "a.php" }); expect(area.find("[data-test=diff-notice]").text()).toContain("fatal: bad object"); }); it("shows a deleted working copy as an empty read-only side with a notice", async () => { blobs["index:gone.php"] = { text: " { await mountArea(); await runCommand("vcs.showDiff", { path: "b.txt" }); const { a, b } = sides(); expect(a.state.doc.toString()).toBe(""); expect(b.state.doc.toString()).toBe("bee\n"); }); }); describe("tabs and navigation", () => { it("switches between the diff and the editor tab, and closes the diff tab", async () => { const area = await mountArea(); await runCommand("vcs.showDiff", { path: "a.php" }); await area.find("[data-test=editor-tab]").trigger("click"); expect(area.find("[data-test=diff-view]").exists()).toBe(false); expect(area.find("[data-test=code-editor]").exists()).toBe(true); await area.find("[data-test=diff-tab]").trigger("click"); await flushPromises(); expect(area.find("[data-test=diff-view]").exists()).toBe(true); await area.find("[data-test=diff-tab-close]").trigger("click"); await flushPromises(); expect(area.findAll("[data-test=diff-tab]")).toHaveLength(0); expect(area.find("[data-test=code-editor]").exists()).toBe(true); expect(area.findAll("[data-test=editor-tab]")).toHaveLength(1); }); it("moves to the next and previous change, wrapping around", async () => { blobs["index:a.php"] = { text: "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n", binary: false, tooLarge: false }; disk["a.php"] = "1\nX\n3\n4\n5\n6\n7\n8\n9\n10\nY\n12\n"; await mountArea(); await runCommand("vcs.showDiff", { path: "a.php" }); const { b } = sides(); expect(currentMerge()?.chunks).toHaveLength(2); const lineOfCursor = (): number => b.state.doc.lineAt(b.state.selection.main.head).number; expect(useCommandsStore(pinia).isEnabled("vcs.nextChange")).toBe(true); await runCommand("vcs.nextChange"); expect(lineOfCursor()).toBe(2); await runCommand("vcs.nextChange"); expect(lineOfCursor()).toBe(11); await runCommand("vcs.nextChange"); expect(lineOfCursor()).toBe(2); await runCommand("vcs.previousChange"); expect(lineOfCursor()).toBe(11); }); it("disables next/previous change without a visible diff", async () => { await mountArea(); expect(useCommandsStore(pinia).isEnabled("vcs.nextChange")).toBe(false); expect(useCommandsStore(pinia).isEnabled("vcs.previousChange")).toBe(false); }); }); describe("project tree context menu", () => { it("opens on a right click and runs Show Diff for the file", async () => { const area = await mountArea(); const tree = mount(ProjectToolWindow, { attachTo: document.body, global: { plugins: [pinia] } }); mounted.push(tree); emitEngineEvent({ kind: "projectOpened", root: "/p", name: "p" }); await flushPromises(); useProjectStore(pinia).root = { path: "/p", name: "p" }; await tree.find("[data-path='a.php']").trigger("contextmenu", { clientX: 40, clientY: 50 }); const menu = document.querySelector("[data-test=tree-menu]"); expect(menu).not.toBeNull(); expect([...document.querySelectorAll("[data-test=tree-menu-item]")].map((item) => item.textContent.trim())).toEqual(["Open", "Show Diff", "Show History", "Show Local History", "Upload to Server", "Compare with Server", "Download from Server"]); (document.querySelector("[data-item=showDiff]") as HTMLElement).click(); await flushPromises(); await flushPromises(); expect(document.querySelector("[data-test=tree-menu]")).toBeNull(); expect(callsOf("git.show")[0]?.params).toEqual({ path: "a.php", ref: "index" }); expect(area.findAll("[data-test=diff-tab]").map((t) => t.text())).toEqual(["Diff: a.php"]); }); it("opens from the keyboard with Shift+F10 and closes with Escape", async () => { await mountArea(); const tree = mount(ProjectToolWindow, { attachTo: document.body, global: { plugins: [pinia] } }); mounted.push(tree); emitEngineEvent({ kind: "projectOpened", root: "/p", name: "p" }); await flushPromises(); useProjectStore(pinia).select("a.php"); await tree.find("[data-test=project-tree]").trigger("keydown", { key: "F10", shiftKey: true }); await flushPromises(); const menu = document.querySelector("[data-test=tree-menu]"); expect(menu).not.toBeNull(); expect(document.activeElement).toBe(menu); menu?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await flushPromises(); expect(document.querySelector("[data-test=tree-menu]")).toBeNull(); expect(callsOf("git.show")).toHaveLength(0); }); });