refactor: extracted fetch mocking into reusable hookFetch utility

- Extracted fetch mocking logic into reusable `hookFetch()` utility function with middleware-style handler pattern.
- Replaced manual `globalThis.fetch` assignment and restoration across 10 test files with `hookFetch()` calls using `using` statement for automatic cleanup.
- Implemented Disposable pattern with Symbol.dispose for fetch hook resource management, eliminating try-finally blocks.
- Exported `hookFetch` from utils public API to enable consistent fetch mocking across packages.
This commit is contained in:
can1357
2026-03-08 16:16:54 +01:00
parent e1d8ed2c10
commit 005401e82a
13 changed files with 169 additions and 270 deletions
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "bun:test";
import { type KernelDisplayOutput, PythonKernel } from "@oh-my-pi/pi-coding-agent/ipy/kernel";
import { PYTHON_PRELUDE } from "@oh-my-pi/pi-coding-agent/ipy/prelude";
import { hookFetch } from "@oh-my-pi/pi-utils";
type JupyterMessage = {
channel: string;
@@ -146,7 +147,6 @@ class FakeWebSocket {
describe("PythonKernel (external gateway)", () => {
const originalEnv = { ...Bun.env };
const originalFetch = globalThis.fetch;
const originalWebSocket = globalThis.WebSocket;
beforeEach(() => {
@@ -164,7 +164,6 @@ describe("PythonKernel (external gateway)", () => {
for (const [key, value] of Object.entries(originalEnv)) {
Bun.env[key] = value;
}
globalThis.fetch = originalFetch;
globalThis.WebSocket = originalWebSocket;
FakeWebSocket.lastInstance = null;
vi.restoreAllMocks();
@@ -180,7 +179,7 @@ describe("PythonKernel (external gateway)", () => {
}
return new Response("", { status: 200 });
});
globalThis.fetch = fetchMock as unknown as typeof fetch;
using _hook = hookFetch((input, init) => fetchMock(String(input), init));
let initSeen = false;
let preludeSeen = false;
@@ -309,7 +308,7 @@ describe("PythonKernel (external gateway)", () => {
}
return new Response("", { status: 200 });
});
globalThis.fetch = fetchMock as unknown as typeof fetch;
using _hook = hookFetch((input, init) => fetchMock(String(input), init));
let initSeen = false;
let preludeSeen = false;
@@ -345,7 +344,7 @@ describe("PythonKernel (external gateway)", () => {
}
return new Response("", { status: 200 });
});
globalThis.fetch = fetchMock as unknown as typeof fetch;
using _hook = hookFetch((input, init) => fetchMock(String(input), init));
const docs = [
{