Файли
openidea/src/features/http-client/variableNavigation.test.ts
T
Orca 43c9053624 fix(http-client): open the variable of the selected environment (#7681)
Go to Declaration on {{name}} in a .http file listed the key of every environment. The lookup now receives the environment picked in Run with and follows the order a run reads it: the private file, the public file, $shared, then the last @name line of the file. With No Environment it still lists every key. Keys whose value is an object, an array or null are not variables and are skipped; escaped key names and a key written twice (the last one wins) are handled.

Closes #7672

Co-authored-by: og-orca <[email protected]>
2026-12-03 14:29:18 +08:00

137 рядки
5.6 KiB
TypeScript

import { EditorState, Text } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { contributedNavigation } from "@/editor/navigationProviders";
import type { Location } from "@/platform/ipc";
import { HTTP_LANGUAGE } from "./editor";
import { setEnvironment, useHttpClient } from "./store";
import { fileVariableDefinitions, registerVariableNavigation, variableAt } from "./variableNavigation";
const path = "/p/a.http";
const backend = vi.hoisted(() => ({ httpVariableDefinitions: vi.fn() }));
vi.mock("@/platform/ipc", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/platform/ipc")>();
return { ...actual, commands: { ...actual.commands, ...backend } };
});
vi.mock("@/editor/lsp/lsp", async (importOriginal) => ({
...(await importOriginal<typeof import("@/editor/lsp/lsp")>()),
docOf: () => ({ path, language: HTTP_LANGUAGE }),
}));
const doc = Text.of([
"@host = localhost:8080",
" @token=abc",
"@hostname = other",
"GET http://{{host}}/a?t={{ token }}&id={{$uuid}}",
"Authorization: Bearer {{token}}",
]);
const offsetOf = (line: number, needle: string, delta = 0) =>
doc.line(line).from + doc.line(line).text.indexOf(needle) + delta;
describe("http variable navigation", () => {
it("finds the name of the {{variable}} under the caret", () => {
expect(variableAt(doc, offsetOf(4, "host", 1))).toEqual({
name: "host",
from: offsetOf(4, "host"),
to: offsetOf(4, "host") + 4,
});
// Spaces inside the braces are not part of the name.
expect(variableAt(doc, offsetOf(4, "token", 2))?.name).toBe("token");
expect(variableAt(doc, offsetOf(4, "{{ token", 2))).toBeNull();
expect(variableAt(doc, offsetOf(4, "GET"))).toBeNull();
// Dynamic variables have no definition.
expect(variableAt(doc, offsetOf(4, "$uuid", 1))).toBeNull();
});
it("lists the file's @name definitions", () => {
expect(fileVariableDefinitions(doc, "/p/a.http", "host")).toEqual([
{ path: "/p/a.http", range: { start: { line: 0, col: 1 }, end: { line: 0, col: 5 } } },
]);
expect(fileVariableDefinitions(doc, "/p/a.http", "token")).toEqual([
{ path: "/p/a.http", range: { start: { line: 1, col: 3 }, end: { line: 1, col: 8 } } },
]);
expect(fileVariableDefinitions(doc, "/p/a.http", "missing")).toEqual([]);
});
});
describe("Go to Declaration on a variable", () => {
const key = (line: number): Location => ({
path: "/p/http-client.env.json",
range: { start: { line, col: 4 }, end: { line, col: 10 } },
});
// What the backend finds: the key of each environment, or the one a run in `env` reads.
const inEnvironments: Record<string, Record<string, Location>> = {
host: { dev: key(2), prod: key(6) },
url: { dev: key(3), prod: key(7) },
token: { prod: key(8), stage: key(11) },
secret: { prod: key(9), stage: key(12) },
};
const view = new EditorView({ state: EditorState.create({ doc }) });
const targets = async (name: string) => {
const at = view.state.doc.toString().indexOf(`{{${name}}}`) + 2;
const found = await contributedNavigation(view, at);
return found?.targets.map((t) => `${t.path.split("/").pop()}:${t.range.start.line}`);
};
let unregister: () => void;
beforeEach(() => {
useHttpClient.setState({ envByFile: {}, environments: { [path]: ["dev", "prod", "stage"] } });
view.dispatch({
changes: {
from: 0,
to: view.state.doc.length,
insert:
"@host = localhost\nGET {{url}}/{{host}}?secret={{secret}}&token={{token}}\n@token = abc\n@token = def\n",
},
});
backend.httpVariableDefinitions
.mockReset()
.mockImplementation(async (_path: string, name: string, env: string | null) => {
const keys = inEnvironments[name] ?? {};
return { status: "ok", data: env ? (keys[env] ? [keys[env]] : []) : Object.values(keys) };
});
unregister = registerVariableNavigation();
});
afterEach(() => {
unregister();
setEnvironment(path, null);
});
it("lists every environment when none is selected", async () => {
expect(await targets("url")).toEqual(["http-client.env.json:3", "http-client.env.json:7"]);
expect(await targets("host")).toEqual(["http-client.env.json:2", "http-client.env.json:6", "a.http:0"]);
});
it("goes to the definition of the selected environment", async () => {
setEnvironment(path, "prod");
expect(await targets("url")).toEqual(["http-client.env.json:7"]);
expect(await targets("host")).toEqual(["http-client.env.json:6"]);
expect(await targets("token")).toEqual(["http-client.env.json:8"]);
});
it("goes to the last @name line when the selected environment lacks the variable", async () => {
setEnvironment(path, "dev");
expect(await targets("token")).toEqual(["a.http:3"]);
});
it("follows the selection when it changes", async () => {
setEnvironment(path, "dev");
expect(await targets("url")).toEqual(["http-client.env.json:3"]);
setEnvironment(path, "prod");
expect(await targets("url")).toEqual(["http-client.env.json:7"]);
setEnvironment(path, null);
expect(await targets("url")).toHaveLength(2);
});
it("lists the other environments when nothing else defines the variable", async () => {
setEnvironment(path, "dev");
expect(await targets("secret")).toEqual(["http-client.env.json:9", "http-client.env.json:12"]);
});
it("ignores a selected environment that no longer exists", async () => {
setEnvironment(path, "gone");
expect(await targets("url")).toHaveLength(2);
expect(backend.httpVariableDefinitions).not.toHaveBeenCalledWith(path, "url", "gone");
});
});