Файли
openidea/src/features/debugger/__tests__/expressionCompletion.test.tsx
T
LU XIANGRUIтаwildcatDownstairs a3c819e064 feat(debugger): complete breakpoint conditions from the language server (#6509)
The Condition field and the {...} parts of the log message in breakpoint properties offer code completion without a debug session. The expression is spliced on its own line before the breakpoint's line, indented like it, and a new lsp_snapshot_completion command asks the language server on a transient snapshot of the file, so locals in scope, fields and members after . are offered while the open document and its diagnostics stay untouched. The popup and keys are those of Evaluate; the field claims Ctrl+Space so the non-modal popover doesn't also run the editor's completion.

Fixes #6403

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 22:05:41 +08:00

160 рядки
6.4 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
const { completions } = vi.hoisted(() => ({ completions: vi.fn() }));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return { ...real, commands: { ...real.commands, debugCompletions: completions } };
});
import { registerAction } from "@/platform/actions";
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
import { useDebug, type DebugSession } from "../state";
import { DebuggerOverlays } from "../ui/Overlays";
import { applyCompletion, completionPrefix, matchingCompletions } from "../ui/ExpressionCompletion";
import { expressionItem, spliceExpression } from "../conditionCompletion";
import { openEvaluateDialog, useOverlays } from "../ui/popoverStore";
const session: DebugSession = {
id: 1,
name: "main",
adapter: "java",
parent: null,
launch: null,
process: null,
status: "paused",
stoppedThread: 1,
stopReason: "breakpoint",
stopDescription: null,
threads: [{ id: 1, name: "main" }],
selectedThread: 1,
frames: [{ id: 7, name: "run", path: "/p/App.java", line: 11, column: 0, presentationHint: null }],
selectedFrame: 7,
hits: 1,
stops: 0,
exitCode: null,
caps: null,
};
afterEach(() => {
act(() => useOverlays.setState({ evaluate: null }));
completions.mockReset();
vi.useRealTimers();
});
describe("expression completion", () => {
it("replaces the identifier before the caret and keeps matching as more is typed", () => {
expect(completionPrefix("request.getHe", 13)).toBe("getHe");
expect(completionPrefix("request.", 8)).toBe("");
const items = [
{ label: "getHeader(String)", text: "getHeader(", kind: "method", detail: null, sortText: null },
{ label: "getMethod()", text: null, kind: "method", detail: null, sortText: null },
];
expect(matchingCompletions(items, "getHe").map((i) => i.label)).toEqual(["getHeader(String)"]);
expect(applyCompletion("request.getHe + 1", 13, items[0]!)).toEqual({ text: "request.getHeader( + 1", caret: 18 });
const members = ["__init__", "name", "_cache", "age", "name"].map((label) => ({
label,
text: null,
kind: null,
detail: null,
sortText: null,
}));
expect(matchingCompletions(members, "").map((i) => i.label)).toEqual(["age", "name", "__init__", "_cache"]);
expect(matchingCompletions(members, "_").map((i) => i.label)).toEqual(["__init__", "_cache"]);
const named = ["Request", "request"].map((label) => ({
label,
text: null,
kind: null,
detail: null,
sortText: null,
}));
expect(matchingCompletions(named, "requ").map((i) => i.label)).toEqual(["request", "Request"]);
});
it("offers the adapter's completions in Evaluate for the selected frame and inserts the chosen one", async () => {
vi.useFakeTimers();
completions.mockResolvedValue({
status: "ok",
data: [
{ label: "clientId", text: null, kind: "variable", detail: "String", sortText: null },
{ label: "clone()", text: "clone()", kind: "method", detail: null, sortText: null },
],
});
useDebug.setState({ sessions: { 1: session }, active: 1 });
render(<DebuggerOverlays />);
act(() => openEvaluateDialog());
const field = screen.getByRole("textbox", { name: "Expression" }) as HTMLTextAreaElement;
fireEvent.change(field, { target: { value: "cl", selectionStart: 2, selectionEnd: 2 } });
await act(() => vi.advanceTimersByTimeAsync(200));
expect(completions).toHaveBeenCalledWith(1, 7, "cl", 0, 2);
const options = screen.getAllByRole("option");
expect(options.map((o) => o.textContent)).toEqual(["clientIdString", "clone()"]);
fireEvent.keyDown(field, { key: "ArrowDown" });
fireEvent.keyDown(field, { key: "Enter" });
expect(field.value).toBe("clone()");
expect(screen.queryByRole("option")).toBeNull();
// The dialog stays open: Enter went to the completion, not to Evaluate.
expect(useOverlays.getState().evaluate).not.toBeNull();
});
it("keeps ⌃Space in the field instead of running the keymap's completion for an editor", async () => {
completions.mockResolvedValue({ status: "ok", data: [] });
useDebug.setState({ sessions: { 1: session }, active: 1 });
const editorCompletion = vi.fn();
useKeymap.setState({ preset: "intellij-macos", overrides: { "test.completion": ["Ctrl+Space"] } });
const dispose = [
registerAction({ id: "test.completion", title: "Completion", run: editorCompletion }),
installKeyboardDispatcher(),
];
try {
render(<DebuggerOverlays />);
act(() => openEvaluateDialog());
const field = screen.getByRole("textbox", { name: "Expression" });
field.focus();
await act(async () => {
fireEvent.keyDown(field, { key: " ", code: "Space", ctrlKey: true });
});
expect(editorCompletion).not.toHaveBeenCalled();
expect(completions).toHaveBeenCalled();
} finally {
dispose.forEach((d) => d());
useKeymap.setState({ overrides: {} });
}
});
it("splices a breakpoint's expression before its line, indented like it, for the language server", () => {
const text = "class A {\n void run(int count) {\n go(count);\n }\n}";
expect(spliceExpression(text, 2, "order.")).toEqual({
text: "class A {\n void run(int count) {\n order.\n go(count);\n }\n}",
pos: { line: 2, col: 10 },
});
expect(spliceExpression("a\r\n\tb\r\n", 1, "x").text).toBe("a\r\n\tx\n\tb\r\n");
});
it("inserts a language server item as plain text with the caret at its first argument", () => {
const item = (insertText: string, isSnippet: boolean) =>
expressionItem({
label: "equals",
labelDetail: "(Object obj)",
labelDescription: "boolean",
detail: null,
kind: "method",
sortText: "1",
insertText,
isSnippet,
} as never);
expect(item("equals(${1:obj})", true)).toEqual({
label: "equals(Object obj)",
text: "equals()",
caret: 7,
kind: "method",
detail: "boolean",
sortText: "1",
});
expect(item("equals($0)", true)).toMatchObject({ text: "equals()", caret: 7 });
expect(item("total", false)).toMatchObject({ text: "total", caret: 5 });
expect(applyCompletion("o.eq", 4, item("equals(${1:obj})", true))).toEqual({ text: "o.equals()", caret: 9 });
});
});