Repository Public
1import Foundation2import MCCCore3import Testing4@testable import MCCiOS56@Suite("Alerts, actions, activity, audit — logic")7@MainActor8struct GroupBTests {9 static let t0 = Date(timeIntervalSince1970: 1_800_000_000)10 /// An empty JSON object payload, decoded (the memberwise default is not linkable from a hosted test bundle).11 static func empty<T: Decodable>() -> T { try! JSONValue.object([:]).decode(T.self) }12 static func uuid(_ n: Int) -> String { String(format: "00000000-0000-4000-8000-%012d", n) }1314 static func alert(_ n: Int, _ state: API.AlertState, _ severity: API.Severity, started: TimeInterval = 0, summary: String = "s", node: String? = nil) -> API.Alert {15 API.Alert(id: uuid(n), ruleId: uuid(900), ruleName: "CPU saturated", nodeId: node.map { _ in uuid(500) }, nodeAlias: node, label: "", fingerprint: "f\(n)",16 state: state, severity: severity, summary: summary, startedAt: t0.addingTimeInterval(started), lastEvalAt: t0, flapCount: 0)17 }1819 static func type(_ name: String, _ c: API.Criticality, kinds: [API.ActionTargetKind], stepUp: Bool = false, just: Bool = false, conf: Bool = false, appr: Bool = false) -> API.ActionType {20 API.ActionType(_type: name, title: name, description: "", criticality: c, permission: "actions.run." + c.rawValue, targetKinds: kinds,21 paramsSchema: Self.empty(), requiresStepUp: stepUp, requiresJustification: just, requiresConfirmation: conf, requiresApproval: appr,22 timeoutS: 60, lockScope: .node, available: true)23 }2425 static func action(_ n: Int, _ state: API.ActionState, created: TimeInterval, label: String? = nil, alias: String? = nil) -> API.Action {26 API.Action(id: uuid(n), _type: "node.maintenance.set", criticality: .medium, target: .init(kind: .node, id: uuid(500)), targetLabel: label, nodeAlias: alias,27 params: Self.empty(), state: state, requestedVia: "ios", justification: "", approvalRequired: false, outcomeUnknown: false,28 createdAt: t0.addingTimeInterval(created), timeoutS: 60, correlationId: "c\(n)")29 }3031 @Test("alerts: open first, then severity, then most recent")32 func alertSorting() {33 let list = [Self.alert(1, .resolved, .critical, started: 50), Self.alert(2, .firing, .warning, started: 10), Self.alert(3, .firing, .critical, started: 5),34 Self.alert(4, .acknowledged, .critical, started: 20), Self.alert(5, .pending, .info, started: 99)]35 #expect(AlertsLogic.sorted(list).map(\.id) == [4, 3, 2, 5, 1].map(Self.uuid))36 }3738 @Test("alerts: filters by state / severity and searches summary, rule, node")39 func alertFiltering() {40 let list = [Self.alert(1, .resolved, .critical, summary: "disk full", node: "ios-test-node-01"), Self.alert(2, .firing, .warning, summary: "swap high"),41 Self.alert(3, .firing, .critical, summary: "cpu hot", node: "ios-test-node-02")]42 #expect(AlertsLogic.filter(list, by: .open).map(\.id) == [2, 3].map(Self.uuid))43 #expect(AlertsLogic.filter(list, by: .all).count == 3)44 #expect(AlertsLogic.filter(list, by: .critical).map(\.id) == [1, 3].map(Self.uuid))45 #expect(AlertsLogic.filter(list, by: .warning).map(\.id) == [Self.uuid(2)])46 #expect(AlertsLogic.filter(list, by: .info).isEmpty)47 #expect(AlertsLogic.filter(list, by: .all, query: " NODE-02 ").map(\.id) == [Self.uuid(3)])48 #expect(AlertsLogic.filter(list, by: .all, query: "saturated").count == 3)49 #expect(AlertsLogic.filter(list, by: .open, query: "disk").isEmpty)50 }5152 @Test("timeline is chronological and stable; incidents: unresolved first")53 func timelineAndIncidents() {54 let e = [API.TimelineEvent(id: "b", ts: Self.t0.addingTimeInterval(5), kind: "ack", body: ""), API.TimelineEvent(id: "a", ts: Self.t0, kind: "fired", body: ""),55 API.TimelineEvent(id: "c", ts: Self.t0.addingTimeInterval(5), kind: "comment", body: "x")]56 #expect(AlertsLogic.timeline(e).map(\.id) == ["a", "b", "c"])57 func inc(_ n: Int, _ s: API.IncidentState, _ sev: API.Severity, _ at: TimeInterval) -> API.Incident {58 API.Incident(id: Self.uuid(n), title: "t\(n)", severity: sev, state: s, summary: "", openedAt: Self.t0.addingTimeInterval(at), alertCount: 0)59 }60 let list = [inc(1, .resolved, .critical, 9), inc(2, .open, .warning, 1), inc(3, .mitigated, .critical, 0), inc(4, .open, .warning, 5)]61 #expect(AlertsLogic.sorted(list).map(\.id) == [3, 4, 2, 1].map(Self.uuid))62 #expect(AlertsLogic.filter(list, query: "T4").map(\.id) == [Self.uuid(4)])63 }6465 @Test("silences: scope text parts and request validation")66 func silences() {67 let all = AlertsLogic.scopeParts(API.AlertScope(all: true)) { _ in nil }68 #expect(all.all && all.nodes.isEmpty)69 let some = AlertsLogic.scopeParts(API.AlertScope(nodeIds: [Self.uuid(1), Self.uuid(2)], tags: ["gpu"])) { $0 == Self.uuid(1) ? "node-a" : nil }70 #expect(!some.all)71 #expect(some.nodes == ["node-a", "00000000"])72 #expect(some.tags == ["gpu"])73 let end = Self.t074 #expect(AlertsLogic.silenceRequest(reason: " ", allNodes: true, nodeIDs: [], endsAt: end) == nil)75 #expect(AlertsLogic.silenceRequest(reason: "why", allNodes: false, nodeIDs: [], endsAt: end) == nil)76 let r = AlertsLogic.silenceRequest(reason: " why ", allNodes: false, nodeIDs: ["b", "a"], endsAt: end)77 #expect(r?.reason == "why")78 #expect(r?.scope.nodeIds == ["a", "b"])79 #expect(r?.scope.all == nil)80 #expect(AlertsLogic.silenceRequest(reason: "why", allNodes: true, nodeIDs: ["a"], endsAt: end)?.scope.all == true)81 }8283 @Test("action types: per target kind, grouped by criticality, requirements, review step")84 func actionTypes() {85 let types = [Self.type("system.reboot", .critical, kinds: [.node], stepUp: true, just: true, conf: true, appr: true), Self.type("service.restart", .medium, kinds: [.service]),86 Self.type("node.maintenance.set", .medium, kinds: [.node]), Self.type("inventory.refresh", .low, kinds: [.node])]87 #expect(ActionsLogic.types(for: .node, in: types).map(\._type) == ["inventory.refresh", "node.maintenance.set", "system.reboot"])88 #expect(ActionsLogic.types(for: .job, in: types).isEmpty)89 let groups = ActionsLogic.grouped(types)90 #expect(groups.map(\.criticality) == [.low, .medium, .critical])91 #expect(groups[1].types.map(\._type) == ["node.maintenance.set", "service.restart"])92 #expect(ActionsLogic.requirements(of: types[0]) == [.stepUp, .justification, .confirmation, .approval])93 #expect(ActionsLogic.requirements(of: types[3]).isEmpty)94 #expect(!ActionsLogic.needsReviewStep(.low))95 #expect(ActionsLogic.needsReviewStep(.medium) && ActionsLogic.needsReviewStep(.high) && ActionsLogic.needsReviewStep(.critical))96 }9798 @Test("action history: state filter, newest first, pending count, target label, parameter lines")99 func actionHistory() {100 let list = [Self.action(1, .succeeded, created: 1, label: "ios-test-node-01"), Self.action(2, .pendingApproval, created: 3, alias: "node-b"), Self.action(3, .failed, created: 2)]101 #expect(ActionsLogic.filter(list, state: nil).map(\.id) == [2, 3, 1].map(Self.uuid))102 #expect(ActionsLogic.filter(list, state: .failed).map(\.id) == [Self.uuid(3)])103 #expect(ActionsLogic.pendingApprovalCount(list) == 1)104 #expect(ActionsLogic.targetLabel(list[0]) == "ios-test-node-01")105 #expect(ActionsLogic.targetLabel(list[1]) == "node-b")106 #expect(ActionsLogic.targetLabel(list[2]).hasSuffix("00000000"))107 #expect(ActionsLogic.parameterLines(["reason": .string("ui test"), "enabled": .bool(true), "lines": .number(200), "ratio": .number(0.5)])108 == ["enabled = true", "lines = 200", "ratio = 0.5", "reason = ui test"])109 #expect(ActionsLogic.parameterLines([:]).isEmpty)110 }111112 @Test("schema form: numbers are parsed, truncated to integers and clamped to the advertised bounds")113 func schemaNumbers() {114 #expect(SchemaFormView.number(from: "", integer: true, min: 1, max: 500) == nil)115 #expect(SchemaFormView.number(from: "abc", integer: true, min: nil, max: nil) == nil)116 #expect(SchemaFormView.number(from: " 200 ", integer: true, min: 1, max: 500) == 200)117 #expect(SchemaFormView.number(from: "9999", integer: true, min: 1, max: 500) == 500)118 #expect(SchemaFormView.number(from: "0", integer: true, min: 1, max: 500) == 1)119 #expect(SchemaFormView.number(from: "2,7", integer: true, min: nil, max: nil) == 2)120 #expect(SchemaFormView.number(from: "2,75", integer: false, min: nil, max: nil) == 2.75)121 #expect(SchemaFormView.boundsText(1, 500) == "1 – 500")122 #expect(SchemaFormView.boundsText(nil, 0.5) == "≤ 0.5")123 #expect(SchemaFormView.boundsText(nil, nil) == nil)124 }125126 @Test("activity: target kinds map to routes only with a valid id; grouped by day, newest first")127 func activity() {128 func item(_ n: Int, _ kind: String?, _ id: String?, at: TimeInterval = 0) -> API.ActivityItem {129 API.ActivityItem(id: "\(n)", ts: Self.t0.addingTimeInterval(at), kind: .action, summary: "s", targetKind: kind, targetId: id)130 }131 let id = Self.uuid(7)132 #expect(ActivityLogic.route(for: item(1, "node", id)) == .node(id))133 #expect(ActivityLogic.route(for: item(1, "alert", id)) == .alert(id))134 #expect(ActivityLogic.route(for: item(1, "incident", id)) == .incident(id))135 #expect(ActivityLogic.route(for: item(1, "action", id)) == .action(id))136 #expect(ActivityLogic.route(for: item(1, "service", id)) == .service(id))137 #expect(ActivityLogic.route(for: item(1, "job", id)) == .job(id))138 #expect(ActivityLogic.route(for: item(1, "inference_server", id)) == .model(id))139 #expect(ActivityLogic.route(for: item(1, "maintenance_window", id)) == .maintenanceWindow(id: id, occurrence: nil))140 #expect(ActivityLogic.route(for: item(1, "user", id)) == nil)141 #expect(ActivityLogic.route(for: item(1, "node", "not-a-uuid")) == nil)142 #expect(ActivityLogic.route(for: item(1, nil, id)) == nil)143 var cal = Calendar(identifier: .gregorian)144 cal.timeZone = TimeZone(identifier: "UTC")!145 let groups = ActivityLogic.byDay([item(1, nil, nil, at: 0), item(2, nil, nil, at: 86_400 * 2), item(3, nil, nil, at: 60)], calendar: cal)146 #expect(groups.map { $0.items.map(\.id) } == [["2"], ["3", "1"]])147 #expect(API.ActivityKind.allCases.allSatisfy { !ActivityLogic.symbol($0).isEmpty })148 }149150 @Test("audit: server filter, text match, newest first, export file name")151 func audit() {152 let now = Date(timeIntervalSince1970: 1_800_000_123)153 #expect(AuditLogic.filter(outcome: nil, period: .all, now: now) == AuditFilter())154 let f = AuditLogic.filter(outcome: .denied, period: .day, now: now)155 #expect(f.outcome == .denied)156 #expect(f.from == Date(timeIntervalSince1970: 1_800_000_000 - 86_400))157 // Stable for a while: the same choice a minute later is the same resource key.158 #expect(AuditLogic.filter(outcome: .denied, period: .day, now: now.addingTimeInterval(60)) == f)159 func entry(_ seq: Int64, _ action: String, actor: String = "owner", target: String? = nil) -> API.AuditEntry {160 API.AuditEntry(seq: seq, ts: Self.t0, actorKind: .user, actorLabel: actor, action: action, targetKind: target, targetId: target.map { _ in Self.uuid(1) },161 params: Self.empty(), outcome: .success, detail: "", correlationId: "corr-\(seq)", prevHash: "p", hash: "h")162 }163 let list = [entry(1, "auth.login"), entry(3, "action.create", target: "node"), entry(2, "alert.ack", actor: "Viewer")]164 #expect(AuditLogic.sorted(list).map(\.seq) == [3, 2, 1])165 #expect(list.filter { AuditLogic.matches($0, text: "") }.count == 3)166 #expect(list.filter { AuditLogic.matches($0, text: "ACTION") }.map(\.seq) == [3])167 #expect(list.filter { AuditLogic.matches($0, text: "viewer") }.map(\.seq) == [2])168 #expect(list.filter { AuditLogic.matches($0, text: "corr-1") }.map(\.seq) == [1])169 #expect(AuditLogic.targetText(list[1]) == "node " + Self.uuid(1))170 #expect(AuditLogic.targetText(list[0]) == nil)171 #expect(AuditLogic.exportFileName(from: Date(timeIntervalSince1970: 1_800_000_000), to: Date(timeIntervalSince1970: 1_800_000_000 + 86_400 * 3), format: .csv)172 == "mcc-audit-20270115-20270118.csv")173 }174175 @Test("every literal string key of the group-B screens exists in fr and en")176 func catalogs() {177 Localization.shared.register(bundle: Bundle(for: AppModel.self))178 let keys = ["alerts.ack", "alerts.resolve", "alerts.silences", "alerts.incident.mark", "actions.catalog", "actions.review.send", "actions.requires.step_up",179 "actions.approvals.count", "activity.empty", "audit.export", "audit.chain.ok", "audit.period.week"]180 for lang in AppLanguage.allCases {181 for k in keys { #expect(Localization.shared.has(k, language: lang), "\(k) missing in \(lang.rawValue)") }182 }183 }184}185