testStopJobStopsWhatItRuns

tcmts.cli.mcp.testStopJobStopsWhatItRuns · #4mne5m2n · term

Stopping a job stops what it runs too, and its end says it was stopped.

import { jobWhen, processAlive, startJob, stopJob } from "#codebase/tcmts/cli/mcp";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

export const testStopJobStopsWhatItRuns = async () => {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), "tcm jobs "));
  try {
    const id = startJob(
      dir,
      { argv: ["run", "forever"] },
      {
        cmd: [process.execPath, "-e", "console.log(process.pid); setInterval(() => {}, 1000);"],
        cwd: dir,
        env: process.env,
      },
    );
    const running = await jobWhen(dir, id, (j) => /^\d+\n/.test(j.out));
    const command = Number(running.out.trim());
    assert.ok(processAlive(command) && processAlive(running.pid));
    const stopped = await stopJob(dir, id);
    assert.equal(stopped?.done?.stopped, true);
    for (const until = Date.now() + 5000; processAlive(command) || processAlive(running.pid);) {
      if (Date.now() > until) assert.fail("what the job ran is still running");
      await new Promise((r) => setTimeout(r, 50));
    }
    // (one that has ended is as it was)
    assert.deepEqual((await stopJob(dir, id))?.done, stopped.done);
  } finally {
    fs.rmSync(dir, { recursive: true, force: true });
  }
}

uses