SPB Git

Repository Public

CoreScreensTests.swift 12.5 KB 175 lines swift

1import MCCCore2import XCTest3@testable import MCC45@MainActor6final class CoreScreensTests: XCTestCase {7    private func decode<T: Decodable>(_ type: T.Type, _ json: String) throws -> T {8        let d = JSONDecoder()9        d.dateDecodingStrategy = .iso860110        return try d.decode(T.self, from: Data(json.utf8))11    }1213    private func node(_ alias: String, freshness: String = "fresh", kind: String = "mac", site: String = "lan", tags: [String] = [],14                      maintenance: Bool = false, retired: Bool = false, cpu: Double? = nil) throws -> API.Node {15        let headline = cpu.map { #","headline":{"cpu_usage_pct":\#($0)}"# } ?? ""16        let retiredAt = retired ? #","retired_at":"2026-11-01T00:00:00Z""# : ""17        return try decode(API.Node.self, #"{"id":"\#(UUID().uuidString.lowercased())","alias":"\#(alias)","kind":"\#(kind)","hostname":"\#(alias).local","site":"\#(site)","role":"compute","environment":"prod","tags":[\#(tags.map { "\"\($0)\"" }.joined(separator: ","))],"registered_via":"agent","maintenance":\#(maintenance),"maintenance_reason":"","created_at":"2026-11-18T20:00:00Z","freshness":"\#(freshness)"\#(headline)\#(retiredAt)}"#)18    }1920    func testNodeFilter() throws {21        let nodes = [try node("M4M64a", tags: ["studio"]), try node("m6ma", freshness: "offline", tags: ["mini"]),22                     try node("BHS64", kind: "linux", site: "ovh"), try node("M2U64", maintenance: true), try node("old", retired: true)]23        var f = NodeFilter()24        XCTAssertFalse(f.isActive)25        XCTAssertEqual(f.apply(to: nodes).map(\.alias), ["M4M64a", "m6ma", "BHS64", "M2U64"], "retired nodes are hidden by default")26        f.includeRetired = true27        XCTAssertEqual(f.apply(to: nodes).count, 5)28        f = NodeFilter(); f.text = "m6m"29        XCTAssertEqual(f.apply(to: nodes).map(\.alias), ["m6ma"])30        f = NodeFilter(); f.text = "STUDIO"31        XCTAssertEqual(f.apply(to: nodes).map(\.alias), ["M4M64a"], "text matches tags, case-insensitively")32        f = NodeFilter(); f.freshness = .offline33        XCTAssertEqual(f.apply(to: nodes).map(\.alias), ["m6ma"])34        f = NodeFilter(); f.kind = .linux; f.site = "ovh"35        XCTAssertEqual(f.apply(to: nodes).map(\.alias), ["BHS64"])36        f = NodeFilter(); f.maintenanceOnly = true37        XCTAssertEqual(f.apply(to: nodes).map(\.alias), ["M2U64"])38        f = NodeFilter(); f.tag = "mini"39        XCTAssertTrue(f.isActive)40        XCTAssertEqual(f.apply(to: nodes).map(\.alias), ["m6ma"])41    }4243    func testNodeRowsSortUnmeasuredValuesLast() throws {44        let rows = [try node("a", cpu: 10), try node("b"), try node("c", cpu: 80)].map(NodeRow.init)45        let byCPU = rows.sorted(using: [KeyPathComparator(\NodeRow.cpu, order: .reverse)])46        XCTAssertEqual(byCPU.map(\.alias), ["c", "a", "b"], "a node without measurement is never ranked as if it were at 0 %")47        XCTAssertNil(rows[1].node.headline)48        let states = [try node("f"), try node("m", maintenance: true), try node("s", freshness: "stale"), try node("o", freshness: "offline")].map(NodeRow.init)49        XCTAssertEqual(states.sorted(using: [KeyPathComparator(\NodeRow.stateRank)]).map(\.alias), ["f", "m", "s", "o"])50    }5152    func testActionMenuFollowsTheCatalog() throws {53        func type(_ name: String, _ crit: String, kinds: [String], available: Bool = true) throws -> API.ActionType {54            try decode(API.ActionType.self, #"{"type":"\#(name)","title":"\#(name)","description":"","criticality":"\#(crit)","permission":"actions.run.\#(crit)","target_kinds":[\#(kinds.map { "\"\($0)\"" }.joined(separator: ","))],"params_schema":{"type":"object","properties":{}},"requires_step_up":false,"requires_justification":false,"requires_confirmation":false,"requires_approval":false,"timeout_s":60,"lock_scope":"node","available":\#(available)}"#)55        }56        let catalog = [try type("system.reboot", "critical", kinds: ["node"]), try type("inventory.refresh", "low", kinds: ["node"]),57                       try type("service.restart", "medium", kinds: ["service"]), try type("system.update.schedule", "high", kinds: ["node"], available: false)]58        XCTAssertEqual(ActionMenu.types(for: .node, in: catalog).map(\._type), ["inventory.refresh", "system.update.schedule", "system.reboot"])59        XCTAssertEqual(ActionMenu.types(for: .service, in: catalog).map(\._type), ["service.restart"])60        XCTAssertTrue(ActionMenu.types(for: .job, in: catalog).isEmpty)61        XCTAssertTrue(ActionMenu.types(for: .node, in: nil).isEmpty, "no catalog → no action offered")62        XCTAssertEqual(ActionMenu.types(for: .node, in: catalog, excluding: ["system.reboot"]).count, 2)63    }6465    func testActionFormOnlyChecksCompleteness() throws {66        let type = try decode(API.ActionType.self, #"{"type":"system.reboot","title":"Reboot","description":"d","criticality":"critical","permission":"actions.run.critical","target_kinds":["node"],"params_schema":{"type":"object","required":["delay_s"],"properties":{"delay_s":{"type":"integer","minimum":0,"maximum":600,"title":"Delay"},"mode":{"type":"string","enum":["soft","hard"],"default":"soft"},"note":{"type":"string"}}},"requires_step_up":true,"requires_justification":true,"requires_confirmation":true,"requires_approval":true,"timeout_s":300,"lock_scope":"node","available":true}"#)67        let form = ActionFormModel(type: type, target: .init(kind: .node, id: UUID().uuidString), targetLabel: "M4M64a")68        XCTAssertEqual(form.fields.map(\.name), ["delay_s", "mode", "note"], "required first, then alphabetical")69        XCTAssertEqual(form.values["mode"], .string("soft"), "schema defaults are prefilled")70        XCTAssertEqual(form.missingFields, ["delay_s"])71        XCTAssertFalse(form.canSubmit)72        form.values["delay_s"] = .number(30)73        XCTAssertTrue(form.needsJustification && form.needsConfirmation)74        form.justification = "Kernel panic loop"75        // Whatever the user types is sent; the SERVER decides whether it matches the target alias.76        form.confirmation = "not-the-alias"77        XCTAssertTrue(form.canSubmit)78        let request = try form.request()79        XCTAssertEqual(request.confirm, "not-the-alias")80        XCTAssertEqual(request.justification, "Kernel panic loop")81        XCTAssertEqual(JSONValue(request.params!.additionalProperties), .object(["delay_s": .number(30), "mode": .string("soft")]))82        let key = try form.idempotencyKey()83        XCTAssertEqual(try form.idempotencyKey(), key, "re-submitting the same intent keeps the key")84        form.values["delay_s"] = .number(60)85        XCTAssertNotEqual(try form.idempotencyKey(), key, "a changed request is a new intent")86    }8788    func testErrorTextKeepsCodeAndCorrelationID() {89        let e = APIError(status: 422, code: "confirmation_mismatch", message: "confirm does not equal the alias", correlationID: "0199aaaa-0000-7000-8000-00000000cafe")90        let text = ErrorText.describe(e)91        XCTAssertTrue(text.contains("HTTP 422 · confirmation_mismatch"))92        XCTAssertTrue(text.contains("0199aaaa-0000-7000-8000-00000000cafe"))93        XCTAssertNotEqual(ErrorText.friendly(e), e.message, "known codes get a localized explanation")94        let unknown = APIError(status: 409, code: "some_new_code", message: "Server says so")95        XCTAssertEqual(ErrorText.friendly(unknown), "Server says so", "unknown codes show the server's message unchanged")96        XCTAssertEqual(Loadable<Int>.failureReason(APIError(status: 501, code: "not_implemented", message: "")), .notImplemented)97        XCTAssertNil(Loadable<Int>.failureReason(e))98    }99100    func testAlertNotificationsOnlyForFiringAndResolved() throws {101        func event(_ state: String, severity: String = "critical", suppressed: Bool = false) throws -> API.AlertChangedEvent {102            try decode(API.AlertChangedEvent.self, #"{"alert_id":"a1","rule_id":"r1","state":"\#(state)","severity":"\#(severity)","summary":"Disk almost full","suppressed":\#(suppressed)}"#)103        }104        let firing = try XCTUnwrap(AlertNotificationContent.make(for: try event("firing"), nodeAlias: "M4M64b"))105        XCTAssertTrue(firing.critical)106        XCTAssertTrue(firing.title.contains("M4M64b"))107        XCTAssertEqual(firing.body, "Disk almost full")108        let resolved = try XCTUnwrap(AlertNotificationContent.make(for: try event("resolved"), nodeAlias: nil))109        XCTAssertFalse(resolved.critical)110        XCTAssertEqual(resolved.identifier, firing.identifier, "the resolution replaces the alert in Notification Centre")111        XCTAssertNil(AlertNotificationContent.make(for: try event("pending"), nodeAlias: nil))112        XCTAssertNil(AlertNotificationContent.make(for: try event("acknowledged"), nodeAlias: nil))113        XCTAssertNil(AlertNotificationContent.make(for: try event("firing", suppressed: true), nodeAlias: nil), "silenced alerts stay silent")114        XCTAssertFalse(try XCTUnwrap(AlertNotificationContent.make(for: try event("firing", severity: "warning"), nodeAlias: nil)).critical)115    }116117    func testAppLockIsLocalAndIdleBased() {118        UserDefaults.standard.removeObject(forKey: AppLock.enabledKey)119        let lock = AppLock()120        XCTAssertFalse(lock.isEnabled)121        XCTAssertFalse(lock.isLocked, "the lock is optional and off by default")122        lock.isEnabled = true123        lock.idleMinutes = 10124        let t0 = Date()125        lock.noteActivity(now: t0)126        lock.evaluateIdle(now: t0.addingTimeInterval(9 * 60))127        XCTAssertFalse(lock.isLocked)128        lock.evaluateIdle(now: t0.addingTimeInterval(10 * 60))129        XCTAssertTrue(lock.isLocked)130        lock.isEnabled = false131        XCTAssertFalse(lock.isLocked)132        XCTAssertFalse(AppLock(disabled: true).isEnabled)133        UserDefaults.standard.removeObject(forKey: AppLock.enabledKey)134    }135136    func testMetricFamiliesUseCatalogNamesOnce() {137        let all = MetricFamily.allCases.flatMap { $0.charts.flatMap(\.metrics) }138        XCTAssertEqual(Set(all).count, all.count, "a metric is charted in one place")139        for name in ["cpu.usage", "load.1", "mem.used", "disk.read", "net.rx", "gpu.usage", "thermal.temp", "power.draw", "agent.rss"] {140            XCTAssertTrue(all.contains(name), "\(name) is charted")141        }142        for family in MetricFamily.allCases {143            XCTAssertNotEqual(family.title, "nodes.family." + family.rawValue)144            for chart in family.charts { XCTAssertTrue(Localization.shared.has("nodes.chart." + chart.key, language: .fr), chart.key) }145        }146    }147148    func testHealthSharesAndComparableMetrics() throws {149        let buckets = try decode([API.HealthBucket].self, #"[{"start":"2026-11-18T00:00:00Z","end":"2026-11-18T18:00:00Z","state":"up","alerts_firing":0},{"start":"2026-11-18T18:00:00Z","end":"2026-11-18T21:00:00Z","state":"down","alerts_firing":2},{"start":"2026-11-18T21:00:00Z","end":"2026-11-19T00:00:00Z","state":"maintenance","alerts_firing":0}]"#)150        let shares = NodeHealth.shares(buckets)151        XCTAssertEqual(shares.map(\.state), [.up, .down, .maintenance])152        XCTAssertEqual(shares.map(\.ratio), [0.75, 0.125, 0.125])153        XCTAssertTrue(NodeHealth.shares([]).isEmpty)154        XCTAssertEqual(NodeHealth.tone(.down), .critical)155        let catalog = try decode(API.MetricCatalog.self, #"{"items":[{"name":"net.rx","unit":"bytes/s","kind":"counter_rate","interval_s":10,"labeled":true,"source":"s","description":"d"},{"name":"cpu.usage","unit":"%","kind":"gauge","interval_s":10,"labeled":false,"source":"s","description":"d"}]}"#)156        XCTAssertEqual(NodeCompareView.comparableMetrics(catalog), ["cpu.usage"], "labeled metrics are not offered for a direct overlay")157        XCTAssertFalse(NodeCompareView.comparableMetrics(nil).isEmpty)158    }159160    func testCatalogsAreLoadedInBothLanguages() throws {161        // The app registers its own catalogs on top of MCCCore's. (That every literal tr("…") key of the sources exists162        // in both languages is checked on the source tree by Scripts/test.sh with strings.py: the sandboxed test host163        // must not read the repository.)164        Localization.shared.register(bundle: Bundle(for: AppDelegate.self))165        for lang in AppLanguage.allCases {166            XCTAssertGreaterThan(Localization.shared.table(for: lang).count, 1000, lang.rawValue)167            for item in SidebarItem.allCases { XCTAssertTrue(Localization.shared.has("nav." + item.rawValue, language: lang)) }168            for key in ["nodes.add", "actions.submit", "signin.button", "offline.banner.message", "error.title"] {169                XCTAssertTrue(Localization.shared.has(key, language: lang), "\(key) missing in \(lang.rawValue)")170            }171        }172        XCTAssertEqual(Localization.shared.table(for: .fr).count, Localization.shared.table(for: .en).count)173    }174}175
Files main
Menu

Theme