import { describe, expect, it } from "vitest";
import {
  determineDefaultRuntimeFailure,
  extractDefaultRuntimeFatalError,
  extractDefaultRuntimeThresholdFailures,
  sanitizeDefaultRuntimeExitError,
} from "./default-runtime-errors.mjs";

const firstLine = (value) => value.split(/\r?\n/)[0];

describe("default runtime errors", () => {
  it("extracts fatal stacktrace errors", () => {
    expect(
      extractDefaultRuntimeFatalError("source=stacktrace\nError: boom\nmore", firstLine)
    ).toBe("boom");
  });

  it("extracts failed thresholds", () => {
    expect(
      extractDefaultRuntimeThresholdFailures({
        metrics: {
          checks: {
            thresholds: {
              "rate==1": true,
              "rate>0.9": false,
            },
          },
          other: {},
        },
      })
    ).toEqual(["checks(rate==1)"]);
  });

  it("sanitizes exit errors", () => {
    expect(sanitizeDefaultRuntimeExitError(99, "bad\nstack", firstLine)).toBe(
      "Default runtime failed with exit code 99: bad"
    );
  });

  it("chooses the highest-priority runtime failure", () => {
    expect(
      determineDefaultRuntimeFailure(
        { exitCode: 0, stderr: "source=stacktrace\nError: boom", stdout: "" },
        null,
        firstLine
      )
    ).toBe("Default runtime uncaught error: boom");
  });
});
