process.test.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { describe, expect, test } from "bun:test"
  2. import { Process } from "../../src/util/process"
  3. function node(script: string) {
  4. return [process.execPath, "-e", script]
  5. }
  6. describe("util.process", () => {
  7. test("captures stdout and stderr", async () => {
  8. const out = await Process.run(node('process.stdout.write("out");process.stderr.write("err")'))
  9. expect(out.code).toBe(0)
  10. expect(out.stdout.toString()).toBe("out")
  11. expect(out.stderr.toString()).toBe("err")
  12. })
  13. test("returns code when nothrow is enabled", async () => {
  14. const out = await Process.run(node("process.exit(7)"), { nothrow: true })
  15. expect(out.code).toBe(7)
  16. })
  17. test("throws RunFailedError on non-zero exit", async () => {
  18. const err = await Process.run(node('process.stderr.write("bad");process.exit(3)')).catch((error) => error)
  19. expect(err).toBeInstanceOf(Process.RunFailedError)
  20. if (!(err instanceof Process.RunFailedError)) throw err
  21. expect(err.code).toBe(3)
  22. expect(err.stderr.toString()).toBe("bad")
  23. })
  24. test("aborts a running process", async () => {
  25. const abort = new AbortController()
  26. const started = Date.now()
  27. setTimeout(() => abort.abort(), 25)
  28. const out = await Process.run(node("setInterval(() => {}, 1000)"), {
  29. abort: abort.signal,
  30. nothrow: true,
  31. })
  32. expect(out.code).not.toBe(0)
  33. expect(Date.now() - started).toBeLessThan(1000)
  34. }, 3000)
  35. test("kills after timeout when process ignores terminate signal", async () => {
  36. if (process.platform === "win32") return
  37. const abort = new AbortController()
  38. const started = Date.now()
  39. setTimeout(() => abort.abort(), 25)
  40. const out = await Process.run(node('process.on("SIGTERM", () => {}); setInterval(() => {}, 1000)'), {
  41. abort: abort.signal,
  42. nothrow: true,
  43. timeout: 25,
  44. })
  45. expect(out.code).not.toBe(0)
  46. expect(Date.now() - started).toBeLessThan(1000)
  47. }, 3000)
  48. })