import { mockTestStd } from "../../__tests__/internal/mockTestStd";
import { inspectError } from "../inspectError";
import { progress } from "../logging";
import { runShell } from "../runShell";

test("echoed to &2 is not a part of error if already printed to stderr", async () => {
  const printed = mockTestStd();
  const cmd = "echo 'test stdout'; echo 'test' 'stderr' >&2; exit 1";
  const error = await runShell(cmd, null).catch((e: unknown) =>
    inspectError(e),
  );
  expect(printed.stderr.trimEnd()).toEqual("test stderr");
  expect(error).not.toMatch(/test stderr/);
});

test("echoed to &2 is a part of error if erasable progress is shown", async () => {
  mockTestStd();
  const spyClear = jest.spyOn(progress, "clear");
  const cmd = "echo 'test stdout'; echo 'test' 'stderr' >&2; exit 2";
  const error = await runShell(cmd, null, undefined, "progress.unlogged").catch(
    (e: unknown) => inspectError(e),
  );
  expect(spyClear).toBeCalled();
  expect(error).toMatch(/test stderr/);
});

test("echoed to &2 is printed if succeeds", async () => {
  const printed = mockTestStd();
  const cmd = "echo 'test stdout'; echo 'test stderr' >&2; exit 0";
  const res = await runShell(cmd, null);
  expect(res).toMatch(/test stdout/);
  expect(printed.stderr.trimEnd()).toEqual("test stderr");
});

test("huge input", async () => {
  const input = "x".repeat(10000000);
  const res = await runShell("cat", input);
  expect(res.length).toEqual(input.length);
});
