diff --git a/src/features/http-client/store.test.ts b/src/features/http-client/store.test.ts new file mode 100644 index 000000000..aaedff599 --- /dev/null +++ b/src/features/http-client/store.test.ts @@ -0,0 +1,97 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import type { HttpExchange, HttpRequestBlock } from "@/platform/ipc"; +import { runAll, runRequest, setEnvironment, useHttpClient } from "./store"; + +const backend = vi.hoisted(() => ({ + httpEnvironments: vi.fn(), + httpExecute: vi.fn(), + httpRequests: vi.fn(), +})); +vi.mock("@/platform/ipc", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, commands: { ...actual.commands, ...backend } }; +}); +vi.mock("@/workbench/contributions", async (importOriginal) => ({ + ...(await importOriginal()), + showServiceView: vi.fn(), +})); + +const path = "/project/batch.http"; +const text = "### First\nGET {{baseUrl}}/first\n\n### Second\nGET {{baseUrl}}/second\n"; +const blocks: HttpRequestBlock[] = [ + { index: 0, name: "First", method: "GET", url: "{{baseUrl}}/first", line: 1, startLine: 1, endLine: 2 }, + { index: 1, name: "Second", method: "GET", url: "{{baseUrl}}/second", line: 4, startLine: 4, endLine: 4 }, +]; +const exchange: HttpExchange = { + entry: { + id: "test", + timeMs: null, + name: null, + method: "GET", + url: "http://127.0.0.1/first", + status: 200, + totalMs: null, + file: path, + error: null, + }, + request: { name: null, method: "GET", url: "http://127.0.0.1/first", headers: [], body: null }, + response: null, +}; +const ok = (data: T) => ({ status: "ok" as const, data }); +const initial = useHttpClient.getState(); + +beforeEach(() => { + localStorage.clear(); + useHttpClient.setState(initial); + vi.resetAllMocks(); + backend.httpEnvironments.mockResolvedValue(ok(["A", "B"])); + backend.httpExecute.mockResolvedValue(ok(exchange)); + backend.httpRequests.mockResolvedValue(blocks); +}); + +it.each(["A", null])("keeps the starting environment %s throughout a batch", async (startingEnvironment) => { + useHttpClient.setState({ environments: { [path]: ["A", "B"] } }); + setEnvironment(path, startingEnvironment); + let releaseFirst!: () => void; + const holdFirst = new Promise((resolve) => { + releaseFirst = resolve; + }); + backend.httpExecute.mockImplementationOnce(async () => { + await holdFirst; + return ok(exchange); + }); + + const batch = runAll(path, text); + await vi.waitFor(() => + expect(backend.httpExecute).toHaveBeenCalledExactlyOnceWith(expect.any(Number), path, text, 0, startingEnvironment), + ); + setEnvironment(path, "B"); + releaseFirst(); + await batch; + expect(backend.httpExecute).toHaveBeenNthCalledWith(2, expect.any(Number), path, text, 1, startingEnvironment); + + await runAll(path, text); + expect(backend.httpExecute).toHaveBeenNthCalledWith(3, expect.any(Number), path, text, 0, "B"); + expect(backend.httpExecute).toHaveBeenNthCalledWith(4, expect.any(Number), path, text, 1, "B"); + await runRequest(path, text, 1); + expect(backend.httpExecute).toHaveBeenNthCalledWith(5, expect.any(Number), path, text, 1, "B"); +}); + +it.each(["A", "missing"])("validates the starting choice %s once when environments load", async (choice) => { + setEnvironment(path, choice); + let finishLoading!: (value: ReturnType>) => void; + backend.httpEnvironments.mockImplementationOnce( + () => + new Promise((resolve) => { + finishLoading = resolve; + }), + ); + const batch = runAll(path, text); + await vi.waitFor(() => expect(backend.httpEnvironments).toHaveBeenCalledExactlyOnceWith(path)); + setEnvironment(path, "B"); + finishLoading(ok(["A", "B"])); + await batch; + const environment = choice === "A" ? "A" : null; + expect(backend.httpExecute).toHaveBeenNthCalledWith(1, expect.any(Number), path, text, 0, environment); + expect(backend.httpExecute).toHaveBeenNthCalledWith(2, expect.any(Number), path, text, 1, environment); +}); diff --git a/src/features/http-client/store.ts b/src/features/http-client/store.ts index 5a67ad075..57576bba0 100644 --- a/src/features/http-client/store.ts +++ b/src/features/http-client/store.ts @@ -86,11 +86,11 @@ export async function loadEnvironments(path: string): Promise { } } -/** The environment a run of `path` uses: the chosen one if it still exists. */ -export function effectiveEnvironment(path: string | null): string | null { +/** The environment a run of `path` uses: the selected one if it still exists. */ +function effectiveEnvironment(path: string | null, selection?: string | null): string | null { if (!path) return null; const s = useHttpClient.getState(); - const chosen = s.envByFile[path]; + const chosen = selection === undefined ? s.envByFile[path] : selection; const available = s.environments[path]; if (chosen && (!available || available.includes(chosen))) return chosen; return null; @@ -133,7 +133,12 @@ export function parseRequests(text: string): Promise { * Sends request `index` of `text` (the buffer of `path`). The response opens * in the HTTP Client tool window. Returns false when cancelled or failed early. */ -export async function runRequest(path: string | null, text: string, index: number): Promise { +export async function runRequest( + path: string | null, + text: string, + index: number, + batchEnvironment?: string | null, +): Promise { const busy = useHttpClient.getState().running; if (busy) void commands.cancelRequest(busy.request); const request = nextRequestId(); @@ -149,8 +154,10 @@ export async function runRequest(path: string | null, text: string, index: numbe }) .catch(() => {}); try { - if (path && !useHttpClient.getState().environments[path]) await loadEnvironments(path); - const ex = await call(commands.httpExecute(request, path, text, index, effectiveEnvironment(path))); + if (batchEnvironment === undefined && path && !useHttpClient.getState().environments[path]) + await loadEnvironments(path); + const env = batchEnvironment === undefined ? effectiveEnvironment(path) : batchEnvironment; + const ex = await call(commands.httpExecute(request, path, text, index, env)); useHttpClient.setState((s) => ({ history: [ex.entry, ...s.history.filter((h) => h.id !== ex.entry.id)], exchanges: { ...s.exchanges, [ex.entry.id]: ex }, @@ -208,11 +215,15 @@ export async function openEnvironmentFile(path: string, isPrivate: boolean): Pro } } -/** Runs every request of the file in order; stops when one is cancelled. */ +/** Runs every request of the file in order with the starting environment. */ export async function runAll(path: string | null, text: string): Promise { + const selection = path ? (useHttpClient.getState().envByFile[path] ?? null) : null; const blocks = await parseRequests(text); + if (!blocks.length) return; + if (path && !useHttpClient.getState().environments[path]) await loadEnvironments(path); + const environment = effectiveEnvironment(path, selection); for (const b of blocks) { - if (!(await runRequest(path, text, b.index))) return; + if (!(await runRequest(path, text, b.index, environment))) return; } }