// 本地服务的失败测试:端口 0、假网关、临时目录,不发任何真实请求。 // 覆盖:静态首页注入 boot JSON、鉴权(token/Host/Origin)、CRUD 与立即发送往返、 // 状态文件损坏(fatal)、单实例锁被占(lockedBy)。 import { afterAll, beforeAll, expect, test } from "bun:test"; import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join, posix, win32 } from "node:path"; import plugin from "../src/plugin"; import { alreadyServing, insideDir, loadOrCreateToken, startService, TOKEN_FILE, type ServiceHandle } from "../src/server"; import { fakeGateway, type FakeGateway } from "./fake-gateway"; import { pinMagpieDirsForTest } from "./test-env"; const restoreMagpieDirs = pinMagpieDirsForTest(); const services: ServiceHandle[] = []; const gateways: FakeGateway[] = []; const dirs: string[] = []; afterAll(async () => { try { while (services.length) await services.pop()!.stop(); for (const gw of gateways.splice(0)) gw.stop(); while (dirs.length) await rm(dirs.pop()!, { recursive: true, force: true }); } finally { restoreMagpieDirs(); } }); const MODELS = [{ id: "p1/m1", owned_by: "p1", reasoning: false }]; interface Harness { svc: ServiceHandle; token: string; boot: Record; dir: string; gw: FakeGateway; api: (path: string, init?: RequestInit) => Promise; } async function harness( opts: { state?: string; lockPid?: number; confirmLockAlive?: (pid: number) => Promise; } = {}, ): Promise { const gw = fakeGateway({ models: MODELS }); gateways.push(gw); const dir = await mkdtemp(join(tmpdir(), "sm-server-test-")); dirs.push(dir); if (opts.state !== undefined) await writeFile(join(dir, "state.json"), opts.state); if (opts.lockPid !== undefined) await writeFile(join(dir, "service.lock"), String(opts.lockPid)); const svc = await startService({ port: 0, dir, base: gw.base, confirmLockAlive: opts.confirmLockAlive, }); services.push(svc); const base = `http://127.0.0.1:${svc.port}`; const html = await (await fetch(base)).text(); const m = /