Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

nodePtyConsoleList.test.ts

70 lines2.6 KB

1import * as NodeEvents from "node:events";
2import * as NodeModule from "node:module";
3​
4import { afterEach, describe, expect, it } from "vite-plus/test";
5​
6// Exercises the patched console-list helper in patches/node-pty@1.2.0-beta.15.patch.
7// The agent calls `require("child_process").fork` at call time, so replacing it on
8// the shared CJS module stands in for the forked helper on every platform.
9const requireCjs = NodeModule.createRequire(import.meta.url);
10const childProcess: typeof import("node:child_process") = requireCjs("child_process");
11const {
12 WindowsPtyAgent,
13}: {
14 WindowsPtyAgent: {
15 prototype: { _getConsoleProcessList(this: { _innerPid: number }): Promise<number[]> };
16 };
17} = requireCjs("node-pty/lib/windowsPtyAgent.js");
18const originalFork = childProcess.fork;
19​
20const SHELL_PID = 4242;
21​
22function getConsoleProcessList(
23 driveHelper: (helper: NodeEvents.EventEmitter) => void,
24): Promise<number[]> {
25 const helper = Object.assign(new NodeEvents.EventEmitter(), { kill: () => true });
26 childProcess.fork = (() => {
27 queueMicrotask(() => driveHelper(helper));
28 return helper;
29 }) as unknown as typeof childProcess.fork;
30 return WindowsPtyAgent.prototype._getConsoleProcessList.call({ _innerPid: SHELL_PID });
32​
33describe("node-pty console process list helper", () => {
34 afterEach(() => {
35 childProcess.fork = originalFork;
36 });
37​
38 it("returns the helper's list when it replies and then closes", async () => {
39 const list = await getConsoleProcessList((helper) => {
40 helper.emit("message", { consoleProcessList: [SHELL_PID, 5001, 5002] });
41 helper.emit("exit", 0, null);
42 helper.emit("close", 0, null);
43 });
44 expect(list).toEqual([SHELL_PID, 5001, 5002]);
45 });
46​
47 it("keeps waiting for the reply when exit arrives before the IPC message", async () => {
48 const list = await getConsoleProcessList((helper) => {
49 helper.emit("exit", 0, null);
50 helper.emit("message", { consoleProcessList: [SHELL_PID, 5001] });
51 helper.emit("close", 0, null);
52 });
53 expect(list).toEqual([SHELL_PID, 5001]);
54 });
55​
56 it("falls back to the shell PID when the helper closes without replying", async () => {
57 const list = await getConsoleProcessList((helper) => {
58 helper.emit("exit", 1, null);
59 helper.emit("close", 1, null);
60 });
61 expect(list).toEqual([SHELL_PID]);
62 });
63​
64 it("falls back to the shell PID when the helper fails to spawn", async () => {
65 const list = await getConsoleProcessList((helper) => {
66 helper.emit("error", Object.assign(new Error("spawn ENOENT"), { code: "ENOENT" }));
67 });
68 expect(list).toEqual([SHELL_PID]);
69 });
70});