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

processRunner.test.ts

298 lines9.0 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as Deferred from "effect/Deferred";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as Layer from "effect/Layer";
7import * as Sink from "effect/Sink";
8import * as Stream from "effect/Stream";
9import { TestClock } from "effect/testing";
10import { ChildProcessSpawner } from "effect/unstable/process";
11​
12import {
13 isWindowsCommandNotFound,
14 ProcessOutputLimitError,
15 ProcessRunner,
16 ProcessTimeoutError,
17 layer as ProcessRunnerLive,
18 type ProcessRunInput,
19} from "./processRunner.ts";
20​
21type ChildProcessCommand = {
22 readonly command: string;
23 readonly args: ReadonlyArray<string>;
24};
25​
26// Accesses private properties of ChildProcessCommand for testing purposes
27function asChildProcessCommand(command: unknown): ChildProcessCommand {
28 return command as ChildProcessCommand;
30​
31function makeHandle(input: {
32 readonly stdout?: string | Stream.Stream<Uint8Array>;
33 readonly stderr?: string | Stream.Stream<Uint8Array>;
34 readonly code?: number;
35 readonly stdin?: ChildProcessSpawner.ChildProcessHandle["stdin"];
36 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
37}) {
38 return ChildProcessSpawner.makeHandle({
39 pid: ChildProcessSpawner.ProcessId(1),
40 exitCode: input.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(input.code ?? 0)),
41 isRunning: Effect.succeed(false),
42 kill: () => Effect.void,
43 unref: Effect.succeed(Effect.void),
44 stdin: input.stdin ?? Sink.drain,
45 stdout:
46 typeof input.stdout === "string"
47 ? Stream.encodeText(Stream.make(input.stdout))
48 : (input.stdout ?? Stream.empty),
49 stderr:
50 typeof input.stderr === "string"
51 ? Stream.encodeText(Stream.make(input.stderr))
52 : (input.stderr ?? Stream.empty),
53 all: Stream.empty,
54 getInputFd: () => Sink.drain,
55 getOutputFd: () => Stream.empty,
56 });
58​
59function makeSpawner(
60 f: (command: ChildProcessCommand) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle>,
61) {
62 return ChildProcessSpawner.make((command) => f(asChildProcessCommand(command)));
64​
65const runWith =
66 (spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) => (input: ProcessRunInput) =>
67 Effect.service(ProcessRunner).pipe(
68 Effect.flatMap((runner) =>
69 runner.run({
70 ...input,
71 shell: input.shell ?? false,
72 }),
73 ),
74 Effect.provide(
75 ProcessRunnerLive.pipe(
76 Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
77 ),
78 ),
79 );
80​
81describe("runProcess", () => {
82 it.effect("collects stdout through an injected ChildProcessSpawner", () =>
83 Effect.gen(function* () {
84 const spawner = makeSpawner((command) =>
85 Effect.sync(() => {
86 expect(command.command).toBe("fake");
87 expect(command.args).toEqual(["stdout-bytes", "32"]);
88 return makeHandle({ stdout: "x".repeat(32) });
89 }),
90 );
91​
92 const result = yield* runWith(spawner)({
93 command: "fake",
94 args: ["stdout-bytes", "32"],
95 });
96​
97 expect(result.code).toBe(0);
98 expect(result.stdout).toBe("x".repeat(32));
99 expect(result.timedOut).toBe(false);
100 }),
101 );
102​
103 it.effect("runs through the ProcessRunner service", () => {
104 const spawner = makeSpawner((command) =>
105 Effect.sync(() => {
106 expect(command.command).toBe("fake");
107 expect(command.args).toEqual(["--service"]);
108 return makeHandle({ stdout: "service ok" });
109 }),
110 );
111 const layer = ProcessRunnerLive.pipe(
112 Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
113 );
114​
115 return Effect.gen(function* () {
116 const runner = yield* ProcessRunner;
117 const result = yield* runner.run({
118 command: "fake",
119 args: ["--service"],
120 });
121​
122 expect(result.stdout).toBe("service ok");
123 }).pipe(Effect.provide(layer));
124 });
125​
126 it.effect("fails when output exceeds max buffer in default mode", () =>
127 Effect.gen(function* () {
128 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
129​
130 const error = yield* runWith(spawner)({
131 command: "fake",
132 args: ["stdout-bytes", "2048"],
133 maxOutputBytes: 128,
134 }).pipe(Effect.flip);
135​
136 expect(error).toBeInstanceOf(ProcessOutputLimitError);
137 }),
138 );
139​
140 it.effect("fails fast on output limit before timeout for long-running output", () =>
141 Effect.gen(function* () {
142 const textChunk = "x".repeat(64);
143 const spawner = makeSpawner(() =>
144 Effect.succeed(
145 makeHandle({
146 stdout: Stream.fromIterable(Array.from({ length: 10 }, () => textChunk)).pipe(
147 Stream.encodeText,
148 ),
149 exitCode: Effect.never,
150 }),
151 ),
152 );
153​
154 const error = yield* runWith(spawner)({
155 command: "fake",
156 args: ["spam-stdout"],
157 maxOutputBytes: 128,
158 timeout: "2 seconds",
159 }).pipe(Effect.flip);
160​
161 expect(error).toBeInstanceOf(ProcessOutputLimitError);
162 }),
163 );
164​
165 it.effect("truncates output when outputMode is truncate", () =>
166 Effect.gen(function* () {
167 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
168​
169 const result = yield* runWith(spawner)({
170 command: "fake",
171 args: ["stdout-bytes", "2048"],
172 maxOutputBytes: 128,
173 outputMode: "truncate",
174 });
175​
176 expect(result.code).toBe(0);
177 expect(result.stdout.length).toBeLessThanOrEqual(128);
178 expect(result.stdoutTruncated).toBe(true);
179 expect(result.stderrTruncated).toBe(false);
180 }),
181 );
182​
183 it.effect("writes stdin before waiting for exit", () =>
184 Effect.gen(function* () {
185 const stdinWritten = yield* Deferred.make<void>();
186 const decoder = new TextDecoder();
187 const spawner = makeSpawner(() =>
188 Effect.succeed(
189 makeHandle({
190 stdout: "stdin payload",
191 stdin: Sink.forEach((chunk: Uint8Array) => {
192 const text = decoder.decode(chunk, { stream: true });
193 return text.includes("stdin payload")
194 ? Deferred.succeed(stdinWritten, undefined)
195 : Effect.void;
196 }),
197 exitCode: Deferred.await(stdinWritten).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
198 }),
199 ),
200 );
201​
202 const result = yield* runWith(spawner)({
203 command: "fake",
204 args: ["stdin-echo"],
205 stdin: "stdin payload",
206 });
207​
208 expect(result.stdout).toBe("stdin payload");
209 expect(result.code).toBe(0);
210 }),
211 );
212​
213 it.effect("returns output for non-zero exit codes", () =>
214 Effect.gen(function* () {
215 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stderr: "boom", code: 2 })));
216​
217 const result = yield* runWith(spawner)({
218 command: "fake",
219 args: ["stderr-exit", "boom", "2"],
220 });
221​
222 expect(result.code).toBe(2);
223 expect(result.stderr).toBe("boom");
224 }),
225 );
226​
227 it.effect("fails on timeout", () =>
228 Effect.gen(function* () {
229 const spawner = makeSpawner(() =>
230 Effect.succeed(
231 makeHandle({
232 exitCode: Effect.never,
233 }),
234 ),
235 );
236 const errorFiber = yield* runWith(spawner)({
237 command: "fake",
238 args: ["sleep"],
239 timeout: "50 millis",
240 }).pipe(Effect.flip, Effect.forkScoped);
241​
242 yield* Effect.yieldNow;
243 yield* TestClock.adjust(Duration.millis(50));
244 const error = yield* Fiber.join(errorFiber);
245​
246 expect(error).toBeInstanceOf(ProcessTimeoutError);
247 }),
248 );
249​
250 it.effect("returns a synthetic timed out result when timeoutBehavior is timedOutResult", () =>
251 Effect.gen(function* () {
252 const spawner = makeSpawner(() =>
253 Effect.succeed(
254 makeHandle({
255 exitCode: Effect.never,
256 }),
257 ),
258 );
259 const resultFiber = yield* runWith(spawner)({
260 command: "fake",
261 args: ["sleep"],
262 timeout: "50 millis",
263 timeoutBehavior: "timedOutResult",
264 }).pipe(Effect.forkScoped);
265​
266 yield* Effect.yieldNow;
267 yield* TestClock.adjust(Duration.millis(50));
268 const result = yield* Fiber.join(resultFiber);
269​
270 expect(result).toMatchObject({
271 stdout: "",
272 stderr: "",
273 code: null,
274 timedOut: true,
275 stdoutTruncated: false,
276 stderrTruncated: false,
277 });
278 }),
279 );
280});
281​
282describe("isWindowsCommandNotFound", () => {
283 it("matches the localized German cmd.exe error text", () => {
284 const originalPlatform = process.platform;
285 Object.defineProperty(process, "platform", { value: "win32", configurable: true });
286​
287 try {
288 expect(
289 isWindowsCommandNotFound(
290 1,
291 "wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
292 ),
293 ).toBe(true);
294 } finally {
295 Object.defineProperty(process, "platform", { value: originalPlatform, configurable: true });
296 }
297 });
298});