nodejs-env.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. import { access, chmod, realpath, symlink } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { afterEach, describe, expect, it } from "vitest";
  4. import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts";
  5. import { FileError, getOrThrow } from "../../src/harness/types.ts";
  6. import { executeShellWithCapture } from "../../src/harness/utils/shell-output.ts";
  7. import { createTempDir } from "./session-test-utils.ts";
  8. const chmodRestorePaths: string[] = [];
  9. afterEach(async () => {
  10. for (const path of chmodRestorePaths.splice(0)) {
  11. try {
  12. await access(path);
  13. await chmod(path, 0o700);
  14. } catch {}
  15. }
  16. });
  17. describe("NodeExecutionEnv", () => {
  18. it("reads, writes, lists, and removes files and directories", async () => {
  19. const root = createTempDir();
  20. const env = new NodeExecutionEnv({ cwd: root });
  21. expect(getOrThrow(await env.absolutePath("nested/child"))).toBe(join(root, "nested/child"));
  22. expect(getOrThrow(await env.joinPath([root, "nested", "child"]))).toBe(join(root, "nested", "child"));
  23. getOrThrow(await env.createDir("nested/child"));
  24. getOrThrow(await env.writeFile("nested/child/file.txt", "hel"));
  25. getOrThrow(await env.appendFile("nested/child/file.txt", "lo"));
  26. expect(getOrThrow(await env.readTextFile("nested/child/file.txt"))).toBe("hello");
  27. expect(getOrThrow(await env.readTextLines("nested/child/file.txt", { maxLines: 1 }))).toEqual(["hello"]);
  28. expect(Buffer.from(getOrThrow(await env.readBinaryFile("nested/child/file.txt"))).toString("utf8")).toBe("hello");
  29. const entries = getOrThrow(await env.listDir("nested/child"));
  30. expect(entries).toHaveLength(1);
  31. expect(entries[0]).toMatchObject({
  32. name: "file.txt",
  33. path: join(root, "nested/child/file.txt"),
  34. kind: "file",
  35. size: 5,
  36. });
  37. expect(typeof entries[0]!.mtimeMs).toBe("number");
  38. expect(getOrThrow(await env.exists("nested/child/file.txt"))).toBe(true);
  39. getOrThrow(await env.remove("nested/child/file.txt"));
  40. expect(getOrThrow(await env.exists("nested/child/file.txt"))).toBe(false);
  41. });
  42. it("returns fileInfo for files, directories, and symlinks without following symlinks", async () => {
  43. const root = createTempDir();
  44. const env = new NodeExecutionEnv({ cwd: root });
  45. getOrThrow(await env.createDir("dir", { recursive: true }));
  46. getOrThrow(await env.writeFile("dir/file.txt", "hello"));
  47. await symlink(join(root, "dir/file.txt"), join(root, "file-link"));
  48. await symlink(join(root, "dir"), join(root, "dir-link"));
  49. expect(getOrThrow(await env.fileInfo("dir"))).toMatchObject({
  50. name: "dir",
  51. path: join(root, "dir"),
  52. kind: "directory",
  53. });
  54. expect(getOrThrow(await env.fileInfo("dir/file.txt"))).toMatchObject({
  55. name: "file.txt",
  56. path: join(root, "dir/file.txt"),
  57. kind: "file",
  58. size: 5,
  59. });
  60. expect(getOrThrow(await env.fileInfo("file-link"))).toMatchObject({
  61. name: "file-link",
  62. path: join(root, "file-link"),
  63. kind: "symlink",
  64. });
  65. expect(getOrThrow(await env.fileInfo("dir-link"))).toMatchObject({
  66. name: "dir-link",
  67. path: join(root, "dir-link"),
  68. kind: "symlink",
  69. });
  70. expect(getOrThrow(await env.canonicalPath("file-link"))).toBe(await realpath(join(root, "dir/file.txt")));
  71. });
  72. it("lists symlinks as symlinks", async () => {
  73. const root = createTempDir();
  74. const env = new NodeExecutionEnv({ cwd: root });
  75. getOrThrow(await env.writeFile("target.txt", "hello"));
  76. await symlink(join(root, "target.txt"), join(root, "link.txt"));
  77. const entries = getOrThrow(await env.listDir("."));
  78. expect(
  79. entries.map((entry) => ({ name: entry.name, kind: entry.kind })).sort((a, b) => a.name.localeCompare(b.name)),
  80. ).toEqual([
  81. { name: "link.txt", kind: "symlink" },
  82. { name: "target.txt", kind: "file" },
  83. ]);
  84. });
  85. it("stops reading text lines at the requested limit", async () => {
  86. const root = createTempDir();
  87. const env = new NodeExecutionEnv({ cwd: root });
  88. getOrThrow(await env.writeFile("file.txt", "one\ntwo\nthree"));
  89. expect(getOrThrow(await env.readTextLines("file.txt", { maxLines: 1 }))).toEqual(["one"]);
  90. });
  91. it("returns FileError for missing paths and keeps exists false for missing paths", async () => {
  92. const root = createTempDir();
  93. const env = new NodeExecutionEnv({ cwd: root });
  94. const info = await env.fileInfo("missing.txt");
  95. expect(info.ok).toBe(false);
  96. if (!info.ok) {
  97. expect(info.error).toBeInstanceOf(FileError);
  98. expect(info.error).toMatchObject({
  99. name: "FileError",
  100. code: "not_found",
  101. path: join(root, "missing.txt"),
  102. });
  103. }
  104. expect(getOrThrow(await env.exists("missing.txt"))).toBe(false);
  105. });
  106. it("returns FileError for listing non-directories", async () => {
  107. const root = createTempDir();
  108. const env = new NodeExecutionEnv({ cwd: root });
  109. getOrThrow(await env.writeFile("file.txt", "hello"));
  110. const result = await env.listDir("file.txt");
  111. expect(result.ok).toBe(false);
  112. if (!result.ok) {
  113. expect(result.error).toBeInstanceOf(FileError);
  114. expect(result.error).toMatchObject({ code: "not_directory" });
  115. }
  116. });
  117. it("appends to new files and creates parent directories", async () => {
  118. const root = createTempDir();
  119. const env = new NodeExecutionEnv({ cwd: root });
  120. getOrThrow(await env.appendFile("new/nested/file.txt", "a"));
  121. getOrThrow(await env.appendFile("new/nested/file.txt", "b"));
  122. expect(getOrThrow(await env.readTextFile("new/nested/file.txt"))).toBe("ab");
  123. });
  124. it("creates temporary directories and files", async () => {
  125. const root = createTempDir();
  126. const env = new NodeExecutionEnv({ cwd: root });
  127. const tempDir = getOrThrow(await env.createTempDir("node-env-test-"));
  128. await expect(access(tempDir)).resolves.toBeUndefined();
  129. const tempFile = getOrThrow(await env.createTempFile({ prefix: "prefix-", suffix: ".txt" }));
  130. await expect(access(tempFile)).resolves.toBeUndefined();
  131. expect(tempFile.endsWith(".txt")).toBe(true);
  132. });
  133. it("honors createDir recursive false and remove recursive/force options", async () => {
  134. const root = createTempDir();
  135. const env = new NodeExecutionEnv({ cwd: root });
  136. const createResult = await env.createDir("missing/child", { recursive: false });
  137. expect(createResult.ok).toBe(false);
  138. if (!createResult.ok) expect(createResult.error).toMatchObject({ code: "not_found" });
  139. getOrThrow(await env.writeFile("dir/child/file.txt", "hello"));
  140. const removeDirectory = await env.remove("dir", { recursive: false });
  141. expect(removeDirectory.ok).toBe(false);
  142. getOrThrow(await env.remove("dir", { recursive: true }));
  143. expect(getOrThrow(await env.exists("dir"))).toBe(false);
  144. const removeMissing = await env.remove("missing", { force: false });
  145. expect(removeMissing.ok).toBe(false);
  146. getOrThrow(await env.remove("missing", { force: true }));
  147. });
  148. it("returns aborted results for pre-aborted cancellable file operations", async () => {
  149. const root = createTempDir();
  150. const env = new NodeExecutionEnv({ cwd: root });
  151. getOrThrow(await env.writeFile("file.txt", "hello"));
  152. const controller = new AbortController();
  153. controller.abort();
  154. const signal = controller.signal;
  155. const results = await Promise.all([
  156. env.readTextFile("file.txt", signal),
  157. env.readTextLines("file.txt", { abortSignal: signal }),
  158. env.readBinaryFile("file.txt", signal),
  159. env.writeFile("other.txt", "hello", signal),
  160. env.listDir(".", signal),
  161. ]);
  162. for (const result of results) {
  163. expect(result.ok).toBe(false);
  164. if (!result.ok) expect(result.error).toMatchObject({ code: "aborted" });
  165. }
  166. });
  167. it("cleanup is best-effort", async () => {
  168. const root = createTempDir();
  169. const env = new NodeExecutionEnv({ cwd: root });
  170. await expect(env.cleanup()).resolves.toBeUndefined();
  171. });
  172. it("executes commands in cwd with env overrides", async () => {
  173. const root = createTempDir();
  174. const env = new NodeExecutionEnv({ cwd: root });
  175. const result = getOrThrow(
  176. await env.exec('printf \'%s:%s\' "$PWD" "$NODE_ENV_TEST"', {
  177. env: { NODE_ENV_TEST: "ok" },
  178. }),
  179. );
  180. expect(result).toEqual({ stdout: `${await realpath(root)}:ok`, stderr: "", exitCode: 0 });
  181. });
  182. it("streams stdout and stderr chunks", async () => {
  183. const root = createTempDir();
  184. const env = new NodeExecutionEnv({ cwd: root });
  185. let stdout = "";
  186. let stderr = "";
  187. const result = getOrThrow(
  188. await env.exec("printf out; printf err >&2", {
  189. onStdout: (chunk) => {
  190. stdout += chunk;
  191. },
  192. onStderr: (chunk) => {
  193. stderr += chunk;
  194. },
  195. }),
  196. );
  197. expect(result).toEqual({ stdout: "out", stderr: "err", exitCode: 0 });
  198. expect(stdout).toBe("out");
  199. expect(stderr).toBe("err");
  200. });
  201. it("returns non-zero command exit codes as successful execution results", async () => {
  202. const root = createTempDir();
  203. const env = new NodeExecutionEnv({ cwd: root });
  204. const result = getOrThrow(await env.exec("exit 7"));
  205. expect(result).toEqual({ stdout: "", stderr: "", exitCode: 7 });
  206. });
  207. it("returns timeout errors for commands exceeding the timeout", async () => {
  208. const root = createTempDir();
  209. const env = new NodeExecutionEnv({ cwd: root });
  210. const result = await env.exec("sleep 5", { timeout: 0.01 });
  211. expect(result.ok).toBe(false);
  212. if (!result.ok) expect(result.error).toMatchObject({ code: "timeout" });
  213. });
  214. it("returns callback errors from exec stream handlers", async () => {
  215. const root = createTempDir();
  216. const env = new NodeExecutionEnv({ cwd: root });
  217. const result = await env.exec("printf out", {
  218. onStdout: () => {
  219. throw new Error("callback failed");
  220. },
  221. });
  222. expect(result.ok).toBe(false);
  223. if (!result.ok) expect(result.error).toMatchObject({ code: "callback_error", message: "callback failed" });
  224. });
  225. it("returns shell unavailable and spawn errors", async () => {
  226. const root = createTempDir();
  227. const missingShellEnv = new NodeExecutionEnv({ cwd: root, shellPath: join(root, "missing-shell") });
  228. const missingShell = await missingShellEnv.exec("printf ok");
  229. expect(missingShell.ok).toBe(false);
  230. if (!missingShell.ok) expect(missingShell.error).toMatchObject({ code: "shell_unavailable" });
  231. const shellPath = join(root, "not-executable-shell");
  232. const env = new NodeExecutionEnv({ cwd: root });
  233. getOrThrow(await env.writeFile(shellPath, "not executable"));
  234. const spawnErrorEnv = new NodeExecutionEnv({ cwd: root, shellPath });
  235. const spawnError = await spawnErrorEnv.exec("printf ok");
  236. expect(spawnError.ok).toBe(false);
  237. if (!spawnError.ok) expect(spawnError.error).toMatchObject({ code: "spawn_error" });
  238. });
  239. it("returns an aborted result for aborted commands", async () => {
  240. const root = createTempDir();
  241. const env = new NodeExecutionEnv({ cwd: root });
  242. const controller = new AbortController();
  243. const promise = env.exec("sleep 5", { abortSignal: controller.signal });
  244. controller.abort();
  245. const result = await promise;
  246. expect(result.ok).toBe(false);
  247. if (!result.ok) expect(result.error).toMatchObject({ code: "aborted" });
  248. });
  249. it("captures large shell output to a full output file through the execution env", async () => {
  250. const root = createTempDir();
  251. const env = new NodeExecutionEnv({ cwd: root });
  252. const result = getOrThrow(await executeShellWithCapture(env, "yes line | head -n 15000"));
  253. expect(result.truncated).toBe(true);
  254. expect(result.fullOutputPath).toBeDefined();
  255. const fullOutput = getOrThrow(await env.readTextFile(result.fullOutputPath!));
  256. expect(fullOutput.split("\n").length).toBeGreaterThan(10000);
  257. expect(result.output.length).toBeLessThan(fullOutput.length);
  258. });
  259. });