SPB Git

Repository Public

logic.test.ts 9.0 KB 140 lines typescript

1import { describe, expect, it } from "vitest";2import {3  countByState, durationText, emptyRuleForm, filtersFromParams, filtersToParams, filtersToQuery, formToScope, inputToUpdate, parseDuration, parseTags, ruleToForm,4  scopeToForm, serverFieldErrors, stripRows, summarizeScope, validateRuleForm, validateSilence, type Rule, type SilenceForm,5} from "./logic";67describe("durations", () => {8  it("parses friendly forms", () => {9    expect(parseDuration("5 min")).toBe(300);10    expect(parseDuration("90s")).toBe(90);11    expect(parseDuration("1h30")).toBe(5400);12    expect(parseDuration("1 h 30 min")).toBe(5400);13    expect(parseDuration("2,5 h")).toBe(9000);14    expect(parseDuration("300")).toBe(300);15    expect(parseDuration("0 s")).toBe(0);16    expect(parseDuration("1 j")).toBe(86400);17    expect(parseDuration("2 minutes 30 secondes")).toBe(150);18  });19  it("rejects what it does not understand", () => {20    for (const bad of ["", "abc", "5 parsecs", "min", "1h30x", "-5 min", "1 30"]) expect(parseDuration(bad)).toBeNull();21  });22  it("round-trips its own output", () => {23    for (const s of [0, 45, 60, 300, 5400, 3661, 86400, 90061]) expect(parseDuration(durationText(s))).toBe(s);24    expect(durationText(5400)).toBe("1 h 30 min");25  });26});2728describe("scope", () => {29  it("maps both ways with exactly one form", () => {30    expect(formToScope({ scopeKind: "all", nodeIds: ["x"], tagsText: "a" })).toEqual({ all: true });31    expect(formToScope({ scopeKind: "nodes", nodeIds: ["x"], tagsText: "a" })).toEqual({ node_ids: ["x"] });32    expect(formToScope({ scopeKind: "tags", nodeIds: [], tagsText: "gpu, lan  gpu;edge" })).toEqual({ tags: ["gpu", "lan", "edge"] });33    expect(formToScope({ scopeKind: "nodes", nodeIds: [], tagsText: "" })).toBeNull();34    expect(formToScope({ scopeKind: "tags", nodeIds: [], tagsText: " , " })).toBeNull();35    expect(scopeToForm({ tags: ["a", "b"] })).toEqual({ scopeKind: "tags", nodeIds: [], tagsText: "a, b" });36    expect(scopeToForm(undefined).scopeKind).toBe("all");37    expect(parseTags("a,b a")).toEqual(["a", "b"]);38    expect(summarizeScope({ node_ids: ["1"] })).toEqual({ kind: "nodes", ids: ["1"] });39    expect(summarizeScope({})).toEqual({ kind: "empty" });40  });41});4243const rule: Rule = {44  id: "r1", name: "CPU high", description: "d", enabled: true, builtin: false, kind: "threshold", metric: "cpu.usage", op: "gte", threshold: 90, clear_threshold: 80,45  for_seconds: 300, clear_seconds: 120, severity: "critical", scope: { all: true }, notify: true, created_at: "2026-11-01T00:00:00Z", updated_at: "2026-11-01T00:00:00Z",46};4748describe("rule form", () => {49  it("requires the threshold fields for threshold rules", () => {50    const { errors, input } = validateRuleForm(emptyRuleForm());51    expect(input).toBeUndefined();52    expect(errors).toMatchObject({ name: "required", metric: "required", threshold: "required" });53  });54  it("round-trips a rule through the form", () => {55    const { errors, input } = validateRuleForm(ruleToForm(rule));56    expect(errors).toEqual({});57    expect(input).toEqual({ name: "CPU high", description: "d", enabled: true, kind: "threshold", metric: "cpu.usage", op: "gte", threshold: 90, clear_threshold: 80, for_seconds: 300, clear_seconds: 120, severity: "critical", scope: { all: true }, notify: true });58  });59  it("omits threshold fields for absence and service_state rules", () => {60    for (const kind of ["absence", "service_state"] as const) {61      const { errors, input } = validateRuleForm({ ...emptyRuleForm(), name: "n", kind, metric: "cpu.usage", threshold: "5", forText: "10 min" });62      expect(errors).toEqual({});63      expect(input).toEqual({ name: "n", kind, enabled: true, notify: true, for_seconds: 600, clear_seconds: 120, severity: "warning", scope: { all: true } });64    }65  });66  it("reports number, duration and scope problems", () => {67    const { errors } = validateRuleForm({ ...ruleToForm(rule), threshold: "abc", clearThreshold: "x", forText: "soon", clearText: "2 j", scopeKind: "nodes", nodeIds: [], name: "x".repeat(121) });68    expect(errors).toEqual({ name: "tooLong", threshold: "number", clearThreshold: "number", forText: "duration", clearText: "durationMax", scope: "scopeEmpty" });69  });70  it("accepts decimal commas", () => {71    expect(validateRuleForm({ ...ruleToForm(rule), threshold: "92,5", clearThreshold: "" }).input).toMatchObject({ threshold: 92.5 });72  });73  it("builds a PATCH body, restricted for built-in rules", () => {74    const input = validateRuleForm(ruleToForm(rule)).input!;75    expect(inputToUpdate(input, { builtin: false, kind: "threshold" })).toEqual({ name: "CPU high", description: "d", enabled: true, notify: true, for_seconds: 300, clear_seconds: 120, severity: "critical", scope: { all: true }, threshold: 90, clear_threshold: 80, metric: "cpu.usage", op: "gte", label_match: "" });76    const builtin = inputToUpdate(input, { builtin: true, kind: "threshold" });77    expect(builtin).toEqual({ enabled: true, notify: true, for_seconds: 300, clear_seconds: 120, severity: "critical", scope: { all: true }, threshold: 90, clear_threshold: 80 });78    expect(inputToUpdate({ ...input, kind: "absence" }, { builtin: true, kind: "absence" })).not.toHaveProperty("threshold");79  });80  it("maps server field errors onto form fields", () => {81    expect(serverFieldErrors({ fields: { for_seconds: "too large", "rule.threshold": "required", weird: "x" } })).toEqual({ fields: { forText: "too large", threshold: "required" }, other: ["weird: x"] });82    expect(serverFieldErrors(undefined)).toEqual({ fields: {}, other: [] });83  });84});8586describe("alert filters", () => {87  const id = "019a9c1e-7b10-7c3a-9d54-2f6f1f0f3a11";88  it("defaults to open alerts and ignores junk", () => {89    expect(filtersFromParams(new URLSearchParams("state=bogus&severity=loud&node=1"))).toEqual({ state: "open" });90    expect(filtersToQuery({ state: "open" })).toEqual({ limit: 100, open: true });91    expect(filtersToParams({ state: "open" })).toEqual({});92  });93  it("round-trips through the URL and maps to the query", () => {94    const f = filtersFromParams(new URLSearchParams(`state=firing&severity=critical&node=${id}&rule=${id}`));95    expect(f).toEqual({ state: "firing", severity: "critical", nodeId: id, ruleId: id });96    expect(filtersFromParams(new URLSearchParams(filtersToParams(f)))).toEqual(f);97    expect(filtersToQuery(f)).toEqual({ limit: 100, state: "firing", severity: "critical", node_id: id, rule_id: id });98    expect(filtersToQuery({ state: "all" })).toEqual({ limit: 100 });99  });100  it("counts by state", () => {101    expect(countByState([{ state: "firing" }, { state: "firing" }, { state: "resolved" }])).toEqual({ firing: 2, pending: 0, acknowledged: 0, resolved: 1 });102  });103});104105describe("validation strip", () => {106  it("projects intervals on the window, open ones to the end", () => {107    const rows = stripRows({108      evaluated_from: "2026-11-01T00:00:00Z", evaluated_to: "2026-11-01T10:00:00Z",109      intervals: [110        { node_id: "b", node_alias: "m4mb", label: "", started_at: "2026-11-01T05:00:00Z" },111        { node_id: "a", node_alias: "M3U96a", label: "", started_at: "2026-11-01T01:00:00Z", ended_at: "2026-11-01T02:00:00Z" },112        { node_id: "a", node_alias: "M3U96a", label: "", started_at: "2026-10-31T23:00:00Z", ended_at: "2026-11-01T00:30:00Z" },113      ],114    });115    expect(rows.map((r) => r.alias)).toEqual(["M3U96a", "m4mb"]);116    expect(rows[0]?.spans).toEqual([{ x0: 0.1, x1: 0.2, open: false }, { x0: 0, x1: 0.05, open: false }]);117    expect(rows[1]?.spans).toEqual([{ x0: 0.5, x1: 1, open: true }]);118    expect(stripRows({ evaluated_from: "x", evaluated_to: "y", intervals: [] })).toEqual([]);119  });120});121122describe("silence form", () => {123  const now = Date.UTC(2026, 10, 18, 12);124  const base: SilenceForm = { reason: "planned", ruleId: null, startsLocal: "", duration: "4", endsLocal: "", scopeKind: "all", nodeIds: [], tagsText: "" };125  it("builds the body with a quick duration from now", () => {126    expect(validateSilence(base, now).body).toEqual({ reason: "planned", scope: { all: true }, ends_at: "2026-11-18T16:00:00.000Z" });127  });128  it("includes rule and explicit start", () => {129    const start = new Date(now + 3600_000);130    const local = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, "0")}-${String(start.getDate()).padStart(2, "0")}T${String(start.getHours()).padStart(2, "0")}:00`;131    const r = validateSilence({ ...base, ruleId: "r", startsLocal: local, duration: "1" }, now);132    expect(r.body).toEqual({ reason: "planned", scope: { all: true }, rule_id: "r", starts_at: "2026-11-18T13:00:00.000Z", ends_at: "2026-11-18T14:00:00.000Z" });133  });134  it("validates reason, scope and custom end", () => {135    expect(validateSilence({ ...base, reason: " ", scopeKind: "tags", duration: "custom" }, now).errors).toEqual({ reason: "required", scope: "scopeEmpty", ends: "required" });136    expect(validateSilence({ ...base, duration: "custom", endsLocal: "2020-01-01T00:00" }, now).errors).toEqual({ ends: "endPast" });137    expect(validateSilence({ ...base, duration: "custom", endsLocal: "nope" }, now).errors).toEqual({ ends: "invalid" });138  });139});140
Files main
Menu

Theme