-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstats-cli.test.ts
More file actions
234 lines (203 loc) · 7.46 KB
/
Copy pathstats-cli.test.ts
File metadata and controls
234 lines (203 loc) · 7.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import { describe, it, expect, afterEach, afterAll } from "vitest";
import { terminateAndWait } from "./setup/processes.ts";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import { spawn, execFileSync, type ChildProcess } from "node:child_process";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const nodeBin = process.execPath;
const cliPath = path.join(__dirname, "..", "dist", "cli.js");
const serverModule = path.join(__dirname, "..", "dist", "server.js");
const testRoot = fs.mkdtempSync(path.join(os.tmpdir(), "pty-stats-"));
afterAll(() => {
fs.rmSync(testRoot, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
});
let bgPids: number[] = [];
let sessionDirs: string[] = [];
function makeSessionDir(): string {
const dir = fs.mkdtempSync(path.join(testRoot, "d-"));
sessionDirs.push(dir);
return dir;
}
let nameCounter = 0;
function uniqueName(): string {
return `s${++nameCounter}-${Math.random().toString(36).slice(2, 6)}`;
}
async function startDaemon(
sessionDir: string,
name: string,
command: string,
args: string[] = [],
tags?: Record<string, string>,
): Promise<number> {
const config = JSON.stringify({
name,
command,
args,
displayCommand: command,
cwd: os.tmpdir(),
rows: 24,
cols: 80,
tags,
});
const child = spawn(nodeBin, [serverModule], {
detached: true,
stdio: ["ignore", "ignore", "pipe"],
env: {
...process.env,
PTY_SERVER_CONFIG: config,
PTY_SESSION_DIR: sessionDir,
},
});
let stderr = "";
child.stderr?.on("data", (d: Buffer) => { stderr += d.toString(); });
let exitCode: number | null = null;
child.on("exit", (code) => { exitCode = code; });
(child.stderr as any)?.unref?.();
child.unref();
const socketPath = path.join(sessionDir, `${name}.sock`);
const start = Date.now();
while (Date.now() - start < 5000) {
if (exitCode !== null) {
throw new Error(`Daemon exited with code ${exitCode}. stderr:\n${stderr}`);
}
try {
fs.statSync(socketPath);
await new Promise((r) => setTimeout(r, 100));
bgPids.push(child.pid!);
return child.pid!;
} catch {}
await new Promise((r) => setTimeout(r, 50));
}
throw new Error(`Timeout waiting for daemon socket: ${socketPath}`);
}
function runStats(sessionDir: string, ...args: string[]): string {
return execFileSync(nodeBin, [cliPath, "stats", ...args], {
env: { ...process.env, PTY_SESSION_DIR: sessionDir },
encoding: "utf-8",
timeout: 10000,
});
}
afterEach(async () => {
await terminateAndWait(bgPids);
bgPids = [];
for (const dir of sessionDirs) {
try {
const entries = fs.readdirSync(dir);
for (const e of entries) {
try { fs.unlinkSync(path.join(dir, e)); } catch {}
}
} catch {}
}
sessionDirs = [];
});
describe("pty stats CLI", () => {
it("prints stats for a named session", async () => {
const dir = makeSessionDir();
const name = uniqueName();
await startDaemon(dir, name, "cat");
const output = runStats(dir, name);
expect(output).toContain(`Session: ${name}`);
expect(output).toContain("Generation:");
expect(output).toContain("I/O rev:");
expect(output).toContain("Terminal:");
expect(output).toContain("Scrollback:");
expect(output).toContain("Clients:");
expect(output).toContain("Process:");
expect(output).toContain("Modes:");
expect(output).toContain("Activity: unknown");
expect(output).toContain("running");
expect(output).toContain("CPU:");
expect(output).toContain("Memory:");
expect(output).toContain("Daemon:");
}, 15000);
it("returns valid JSON with --json flag", async () => {
const dir = makeSessionDir();
const name = uniqueName();
await startDaemon(dir, name, "cat");
const output = runStats(dir, "--json", name);
const stats = JSON.parse(output);
expect(stats.name).toBe(name);
expect(stats.generation).toBeTypeOf("string");
expect(stats.ioRevision).toBeTypeOf("number");
expect(stats.terminal).toBeDefined();
expect(stats.terminal.cols).toBe(80);
expect(stats.terminal.rows).toBe(24);
expect(stats.terminal.scrollbackCapacity).toBe(24 + 10000);
expect(stats.process.alive).toBe(true);
expect(stats.process.pid).toBeTypeOf("number");
expect(stats.process.resources).toBeDefined();
expect(stats.process.resources.rssKb).toBeTypeOf("number");
expect(stats.process.resources.cpuPercent).toBeTypeOf("number");
expect(stats.daemon).toBeDefined();
expect(stats.daemon.pid).toBeTypeOf("number");
expect(stats.daemon.resources).toBeDefined();
expect(stats.daemon.resources.rssKb).toBeTypeOf("number");
expect(stats.clients).toBeDefined();
expect(stats.modes.alternateScreen).toBe(false);
expect(stats.activity).toMatchObject({
state: "unknown",
producerEpoch: null,
sequence: 0,
});
expect(stats.activity.generation).toBeTypeOf("string");
}, 15000);
it("queries all running sessions when no name given", async () => {
const dir = makeSessionDir();
const name1 = uniqueName();
const name2 = uniqueName();
await startDaemon(dir, name1, "cat");
await startDaemon(dir, name2, "cat");
const output = runStats(dir);
expect(output).toContain(`Session: ${name1}`);
expect(output).toContain(`Session: ${name2}`);
}, 15000);
it("exits with error for nonexistent session", async () => {
const dir = makeSessionDir();
try {
runStats(dir, "nonexistent");
expect.fail("should have thrown");
} catch (err: any) {
expect(err.status).not.toBe(0);
}
}, 15000);
it("shows exited message for dead session", async () => {
const dir = makeSessionDir();
const name = uniqueName();
// `keep=true` exempts the session from the daemon's exit-time self-reap,
// so `stats` still has a dead session to report on.
await startDaemon(dir, name, "true", [], { keep: "true" }); // exits immediately
await new Promise((r) => setTimeout(r, 1000)); // wait for exit
const output = runStats(dir, name);
expect(output).toContain("exited");
}, 15000);
it("reports resource usage with reasonable values", async () => {
const dir = makeSessionDir();
const name = uniqueName();
await startDaemon(dir, name, "cat");
const output = runStats(dir, "--json", name);
const stats = JSON.parse(output);
// Child process resources
expect(stats.process.resources.rssKb).toBeGreaterThan(0);
expect(stats.process.resources.cpuPercent).toBeGreaterThanOrEqual(0);
// Daemon resources
expect(stats.daemon.resources.rssKb).toBeGreaterThan(0);
expect(stats.daemon.resources.cpuPercent).toBeGreaterThanOrEqual(0);
// PIDs should be positive integers
expect(stats.process.pid).toBeGreaterThan(0);
expect(stats.daemon.pid).toBeGreaterThan(0);
expect(stats.process.pid).not.toBe(stats.daemon.pid);
}, 15000);
it("does not show CPU/Memory for exited sessions", async () => {
const dir = makeSessionDir();
const name = uniqueName();
// `keep=true`: retain the exited session past the exit-time self-reap.
await startDaemon(dir, name, "true", [], { keep: "true" }); // exits immediately
await new Promise((r) => setTimeout(r, 1000)); // wait for exit
const output = runStats(dir, name);
expect(output).toContain("exited");
expect(output).not.toContain("CPU:");
expect(output).not.toContain("Memory:");
}, 15000);
});