Files
hose-use/src/cli/service.test.ts
T
gitea c1dc9f1616
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
feat: release v0.5.0 with embedded HTTP server and resident daemon service
2026-09-03 15:19:12 +08:00

84 lines
2.5 KiB
TypeScript

import { describe, expect, test, beforeEach, afterEach } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync, existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
serviceStatus,
getPidFile,
getLogFile,
isHoseServiceProcess,
ServiceConfig,
} from "./service.js";
describe("cli/service - 守护进程状态与自愈管理", () => {
let tempDir: string;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "hose-service-test-"));
});
afterEach(() => {
try {
rmSync(tempDir, { recursive: true, force: true });
} catch {
// ignore
}
});
test("服务未运行时返回 running: false 并生成规范状态对象", () => {
const config: ServiceConfig = {
appRoot: tempDir,
entryFile: join(tempDir, "entry.js"),
stateDir: tempDir,
version: "0.5.0",
port: 8888,
host: "127.0.0.1",
};
const status = serviceStatus(config);
expect(status.running).toBe(false);
expect(status.pid).toBeUndefined();
expect(status.version).toBe("0.5.0");
expect(status.port).toBe(8888);
expect(status.pidFile).toBe(join(tempDir, "service.pid"));
expect(status.logFile).toBe(join(tempDir, "service.log"));
});
test("发现失效的孤儿 PID 时自动自愈清理 pidFile", () => {
const config: ServiceConfig = {
appRoot: tempDir,
entryFile: join(tempDir, "entry.js"),
stateDir: tempDir,
version: "0.5.0",
};
const pidFile = getPidFile(config);
// 写入一个不存在的荒谬 PID
writeFileSync(pidFile, "9999999\n", "utf-8");
expect(existsSync(pidFile)).toBe(true);
const status = serviceStatus(config);
expect(status.running).toBe(false);
// 验证旧文件已被自愈删除
expect(existsSync(pidFile)).toBe(false);
});
test("isHoseServiceProcess 正确识别非 hose 进程", () => {
// 当前测试进程自身不是后台 service run 守护进程
expect(isHoseServiceProcess(process.pid, "/non/existent/path")).toBe(false);
// 不存在的进程
expect(isHoseServiceProcess(9999999, tempDir)).toBe(false);
});
test("路径辅助函数返回规范的子路径", () => {
const config: ServiceConfig = {
appRoot: tempDir,
entryFile: join(tempDir, "entry.js"),
stateDir: tempDir,
};
expect(getPidFile(config)).toBe(join(tempDir, "service.pid"));
expect(getLogFile(config)).toBe(join(tempDir, "service.log"));
});
});