Repository Public
1import Foundation2import Testing3@testable import MCCCore4@testable import MCCiOS56/// Logic of the nodes, services, models, jobs, network and storage screens.7@Suite("Group A — nodes, services, models, jobs, network, storage")8@MainActor9struct GroupATests {10 // MARK: Fixtures (decoded from JSON in the wire format)1112 static let decoder: JSONDecoder = {13 let d = JSONDecoder()14 d.dateDecodingStrategy = .custom { dec in15 let s = try dec.singleValueContainer().decode(String.self)16 let f = ISO8601DateFormatter()17 f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]18 if let date = f.date(from: s) { return date }19 f.formatOptions = [.withInternetDateTime]20 if let date = f.date(from: s) { return date }21 throw DecodingError.dataCorrupted(.init(codingPath: dec.codingPath, debugDescription: "bad date \(s)"))22 }23 return d24 }()2526 static func decode<T: Decodable>(_ type: T.Type, _ json: String) throws -> T { try decoder.decode(T.self, from: Data(json.utf8)) }2728 static func node(_ n: Int, alias: String? = nil, kind: String = "mac", site: String = "lab", freshness: String = "fresh", maintenance: Bool = false,29 cpu: Double? = nil, mem: Double? = nil, alerts: Int? = nil, tags: [String] = []) throws -> API.Node {30 var headline = ""31 if cpu != nil || mem != nil {32 let parts = [cpu.map { "\"cpu_usage_pct\":\($0)" }, mem.map { "\"mem_used_pct\":\($0)" }].compactMap { $0 }.joined(separator: ",")33 headline = ",\"headline\":{\(parts)}"34 }35 let a = alerts.map { ",\"open_alerts\":\($0)" } ?? ""36 let t = tags.map { "\"\($0)\"" }.joined(separator: ",")37 return try decode(API.Node.self, """38 {"id":"105e0000-0000-7000-8000-00000000000\(n)","alias":"\(alias ?? "ios-test-node-0\(n)")","kind":"\(kind)","hostname":"h\(n).test","site":"\(site)",39 "role":"worker","environment":"test","tags":[\(t)],"registered_via":"agent","maintenance":\(maintenance),"maintenance_reason":"",40 "created_at":"2026-11-18T20:00:00Z","freshness":"\(freshness)"\(headline)\(a)}41 """)42 }4344 static func service(_ n: Int, name: String, node: String = "ios-test-node-01", nodeN: Int = 1, state: String = "online", manager: String = "pm2", ports: [Int] = []) throws -> API.Service {45 try decode(API.Service.self, """46 {"id":"105e0000-0000-7000-8000-0000000000a\(n)","node_id":"105e0000-0000-7000-8000-00000000000\(nodeN)","node_alias":"\(node)","manager":"\(manager)",47 "name":"\(name)","state":"\(state)","ports":[\(ports.map(String.init).joined(separator: ","))],"managed":false,48 "first_seen_at":"2026-11-18T20:00:00Z","last_seen_at":"2026-11-18T20:00:00.5Z","freshness":"fresh"}49 """)50 }5152 // MARK: Nodes5354 @Test("nodes: search matches alias, site, tags; filters combine; an empty filter keeps everything")55 func nodeFiltering() throws {56 let nodes = [try Self.node(1, site: "lab", tags: ["gpu"]), try Self.node(2, site: "edge", freshness: "stale", maintenance: true),57 try Self.node(3, kind: "linux", site: "edge", freshness: "offline")]58 #expect(NodesLogic.apply(nodes, search: "", filter: NodeFilter(), sort: .alias).count == 3)59 #expect(NodesLogic.apply(nodes, search: " NODE-02 ", filter: NodeFilter(), sort: .alias).map(\.alias) == ["ios-test-node-02"])60 #expect(NodesLogic.apply(nodes, search: "gpu", filter: NodeFilter(), sort: .alias).map(\.alias) == ["ios-test-node-01"])61 #expect(NodesLogic.apply(nodes, search: "edge", filter: NodeFilter(), sort: .alias).count == 2)62 var f = NodeFilter()63 #expect(!f.isActive && f.activeCount == 0)64 f.site = "edge"; f.kind = .linux65 #expect(f.isActive && f.activeCount == 2)66 #expect(NodesLogic.apply(nodes, search: "", filter: f, sort: .alias).map(\.alias) == ["ios-test-node-03"])67 #expect(NodesLogic.apply(nodes, search: "", filter: NodeFilter(freshness: .stale), sort: .alias).map(\.alias) == ["ios-test-node-02"])68 #expect(NodesLogic.apply(nodes, search: "", filter: NodeFilter(maintenanceOnly: true), sort: .alias).map(\.alias) == ["ios-test-node-02"])69 #expect(NodesLogic.sites(nodes) == ["edge", "lab"])70 }7172 @Test("nodes: sorting puts the worst state first and a missing measurement last (unknown is not zero)")73 func nodeSorting() throws {74 let nodes = [try Self.node(1, cpu: 10, mem: 80, alerts: 0), try Self.node(2, freshness: "offline"),75 try Self.node(3, freshness: "stale", cpu: 90, mem: 20, alerts: 3), try Self.node(4, alias: "ios-test-node-10", cpu: 0)]76 func order(_ s: NodeSort) -> [String] { NodesLogic.apply(nodes, search: "", filter: NodeFilter(), sort: s).map { String($0.alias.suffix(2)) } }77 #expect(order(.alias) == ["01", "02", "03", "10"]) // natural order, not lexicographic78 #expect(order(.state) == ["02", "03", "01", "10"])79 #expect(order(.cpu) == ["03", "01", "10", "02"]) // a measured 0 % ranks above "not reported"80 #expect(order(.memory) == ["01", "03", "02", "10"])81 #expect(order(.alerts).first == "03")82 #expect(order(.alerts).last == "10")83 }8485 @Test("nodes: headline texts are nil when the server reported nothing")86 func headlineTexts() {87 #expect(NodesLogic.percentText(nil) == nil)88 #expect(NodesLogic.loadText(nil) == nil)89 #expect(NodesLogic.percentText(0) != nil)90 #expect(NodesLogic.loadText(2.25)?.contains("2") == true)91 }9293 @Test("nodes: comparison selection toggles and is bounded to 2–4")94 func compareSelection() {95 var s: [String] = []96 for id in ["a", "b", "c", "d", "e"] { s = NodesLogic.toggle(id, in: s) }97 #expect(s == ["a", "b", "c", "d"]) // the fifth is refused98 #expect(NodesLogic.canCompare(s))99 s = NodesLogic.toggle("b", in: s)100 #expect(s == ["a", "c", "d"])101 #expect(!NodesLogic.canCompare(["a"]))102 #expect(!NodesLogic.canCompare([]))103 #expect(NodesLogic.canCompare(["a", "b"]))104 }105106 @Test("nodes: metric keys split into name and label; titles fall back to the metric name")107 func metricKeys() {108 Localization.shared.register(bundle: .main)109 #expect(NodesLogic.split(metricKey: "disk.used{/}").name == "disk.used")110 #expect(NodesLogic.split(metricKey: "disk.used{/}").label == "/")111 #expect(NodesLogic.split(metricKey: "net.rx{en0}").label == "en0")112 #expect(NodesLogic.split(metricKey: "cpu.usage").label == nil)113 #expect(NodesLogic.split(metricKey: "odd{}").label == nil)114 #expect(NodesLogic.metricTitle("vendor.custom{x}") == "vendor.custom (x)")115 #expect(NodesLogic.metricTitle("net.rx{en0}").hasSuffix("(en0)"))116 #expect(!NodesLogic.metricTitle("cpu.usage").contains("cpu.usage"))117 }118119 @Test("nodes: a chart is replaced by the availability label only when there is nothing to draw")120 func chartBlocker() {121 #expect(NodesLogic.chartBlocker(availability: .unsupported, hasPoints: false) == .unsupported)122 #expect(NodesLogic.chartBlocker(availability: .permissionDenied, hasPoints: false) == .permissionDenied)123 #expect(NodesLogic.chartBlocker(availability: .unavailable, hasPoints: false) == .unavailable)124 #expect(NodesLogic.chartBlocker(availability: .unsupported, hasPoints: true) == nil)125 #expect(NodesLogic.chartBlocker(availability: .available, hasPoints: false) == nil)126 #expect(NodesLogic.chartBlocker(availability: .stale, hasPoints: false) == nil)127 #expect(NodesLogic.chartBlocker(availability: nil, hasPoints: false) == nil)128 }129130 @Test("nodes: health totals add up per state; usage ratio is nil without both figures")131 func healthAndUsage() throws {132 let h = try Self.decode(API.HealthHistory.self, """133 {"node_id":"105e0000-0000-7000-8000-000000000001","range":"1h","bucket_seconds":300,"uptime_ratio":0.5,"items":[134 {"start":"2026-11-18T20:00:00Z","end":"2026-11-18T20:05:00Z","state":"up","alerts_firing":0},135 {"start":"2026-11-18T20:05:00Z","end":"2026-11-18T20:10:00Z","state":"down","alerts_firing":1},136 {"start":"2026-11-18T20:10:00Z","end":"2026-11-18T20:15:00Z","state":"up","alerts_firing":0}]}137 """)138 let totals = NodesLogic.healthTotals(h.items)139 #expect(totals.map(\.state) == [.up, .down])140 #expect(totals.map(\.seconds) == [600, 300])141 #expect(NodesLogic.healthTone(.down) == .critical && NodesLogic.healthTone(.maintenance) == .maintenance && NodesLogic.healthTone(.unknown) == .neutral)142 #expect(NodesLogic.usageRatio(used: 50, total: 200) == 0.25)143 #expect(NodesLogic.usageRatio(used: nil, total: 200) == nil)144 #expect(NodesLogic.usageRatio(used: 5, total: nil) == nil)145 #expect(NodesLogic.usageRatio(used: 5, total: 0) == nil)146 }147148 // MARK: Services149150 @Test("services: search (name, node, exact port), filters, sort by state puts errored first")151 func serviceFiltering() throws {152 let list = [try Self.service(1, name: "api", ports: [8700]), try Self.service(2, name: "agentd", state: "errored", manager: "launchd"),153 try Self.service(3, name: "worker", node: "ios-test-node-02", nodeN: 2, state: "stopped")]154 #expect(ServicesLogic.apply(list, search: "8700", filter: ServiceFilter(), sort: .name).map(\.name) == ["api"])155 #expect(ServicesLogic.apply(list, search: "870", filter: ServiceFilter(), sort: .name).isEmpty)156 #expect(ServicesLogic.apply(list, search: "node-02", filter: ServiceFilter(), sort: .name).map(\.name) == ["worker"])157 #expect(ServicesLogic.apply(list, search: "", filter: ServiceFilter(manager: .launchd), sort: .name).map(\.name) == ["agentd"])158 #expect(ServicesLogic.apply(list, search: "", filter: ServiceFilter(state: .stopped), sort: .name).map(\.name) == ["worker"])159 #expect(ServicesLogic.apply(list, search: "", filter: ServiceFilter(nodeID: list[2].nodeId), sort: .name).map(\.name) == ["worker"])160 #expect(ServicesLogic.apply(list, search: "", filter: ServiceFilter(), sort: .name).map(\.name) == ["agentd", "api", "worker"])161 #expect(ServicesLogic.apply(list, search: "", filter: ServiceFilter(), sort: .state).map(\.name) == ["agentd", "worker", "api"])162 #expect(ServicesLogic.apply(list, search: "", filter: ServiceFilter(), sort: .node).map(\.name) == ["agentd", "api", "worker"])163 #expect(ServicesLogic.nodes(list).map(\.alias) == ["ios-test-node-01", "ios-test-node-02"])164 #expect(ServiceFilter(state: .online, manager: .pm2).activeCount == 2)165 }166167 @Test("services: ports text, openable URLs (http/https only), log line clamp")168 func serviceHelpers() {169 #expect(ServicesLogic.portsText([]) == nil)170 #expect(ServicesLogic.portsText([80, 443]) == "80, 443")171 #expect(ServicesLogic.openableURL("https://ios-test-app.example.test")?.host() == "ios-test-app.example.test")172 #expect(ServicesLogic.openableURL("http://localhost:8700") != nil)173 #expect(ServicesLogic.openableURL("javascript:alert(1)") == nil)174 #expect(ServicesLogic.openableURL("file:///etc/passwd") == nil)175 #expect(ServicesLogic.openableURL("not a url") == nil)176 #expect(ServicesLogic.openableURL(nil) == nil)177 #expect(ServicesLogic.clampLines(0, to: 1...500) == 1)178 #expect(ServicesLogic.clampLines(900, to: 1...500) == 500)179 #expect(ServicesLogic.clampLines(200, to: 1...500) == 200)180 }181182 // MARK: Models, jobs183184 @Test("models: title falls back to kind and port; the five metric families are listed, none invented")185 func models() throws {186 let support = #"{"availability":"unsupported","reason":"not exposed by mlx_lm"}"#187 let json = """188 {"id":"105e0000-0000-7000-8000-0000000000b1","node_id":"105e0000-0000-7000-8000-000000000002","node_alias":"ios-test-node-02","kind":"mlx_lm","port":8081,189 "health":"ok","listed_models":[],"metrics_support":{"requests":\(support),"tokens_per_s":\(support),"ttft":\(support),"latency":{"availability":"available"},"queue":\(support)},190 "last_seen_at":"2026-11-18T20:00:00Z","freshness":"fresh"}191 """192 var s = try Self.decode(API.InferenceServer.self, json)193 #expect(ModelsLogic.title(s) == "mlx_lm :8081")194 s.model = "ios-test-org/Test-Model-7B-4bit"195 #expect(ModelsLogic.title(s) == "ios-test-org/Test-Model-7B-4bit")196 let rows = ModelsLogic.supportRows(s.metricsSupport)197 #expect(rows.map(\.key) == ["models.metric.requests", "models.metric.tokens_per_s", "models.metric.ttft", "models.metric.latency", "models.metric.queue"])198 #expect(rows.filter { $0.support.availability == .available }.map(\.key) == ["models.metric.latency"])199 #expect(rows[0].support.reason == "not exposed by mlx_lm")200 }201202 @Test("jobs: progress is nil when absent, clamped otherwise; active jobs first; duration and placement")203 func jobs() throws {204 #expect(JobsLogic.progressRatio(nil) == nil)205 #expect(JobsLogic.progressRatio(.nan) == nil)206 #expect(JobsLogic.progressRatio(0) == 0)207 #expect(JobsLogic.progressRatio(0.4) == 0.4)208 #expect(JobsLogic.progressRatio(40) == 0.4)209 #expect(JobsLogic.progressRatio(250) == 1)210 func job(_ n: Int, _ state: String, created: String, started: String? = nil, finished: String? = nil) throws -> API.Job {211 try Self.decode(API.Job.self, """212 {"id":"105e0000-0000-7000-8000-00000000010\(n)","template":"t\(n)","params":{},"state":"\(state)","placement":{},"attempt":1,"max_attempts":3,"depends_on":[],213 "created_at":"\(created)"\(started.map { ",\"started_at\":\"\($0)\"" } ?? "")\(finished.map { ",\"finished_at\":\"\($0)\"" } ?? "")}214 """)215 }216 let jobs = [try job(1, "succeeded", created: "2026-11-18T20:03:00Z", started: "2026-11-18T20:03:00Z", finished: "2026-11-18T20:04:30Z"),217 try job(2, "queued", created: "2026-11-18T20:01:00Z"), try job(3, "running", created: "2026-11-18T20:00:00Z", started: "2026-11-18T20:00:10Z"),218 try job(4, "failed", created: "2026-11-18T20:05:00Z")]219 #expect(JobsLogic.sorted(jobs).map(\.template) == ["t3", "t2", "t4", "t1"])220 #expect(JobsLogic.duration(jobs[0]) == 90)221 #expect(JobsLogic.duration(jobs[1]) == nil)222 #expect(JobsLogic.duration(jobs[2], now: jobs[2].startedAt!.addingTimeInterval(42)) == 42)223 #expect(JobsLogic.placementText(API.JobPlacement(), alias: { _ in nil }) == nil)224 #expect(JobsLogic.placementText(API.JobPlacement(nodeId: "n1", site: "lab", tags: ["gpu", "fast"]), alias: { $0 == "n1" ? "ios-test-node-01" : nil }) == "ios-test-node-01 · lab · gpu, fast")225 #expect(JobsLogic.placementText(API.JobPlacement(nodeId: "n9", tags: []), alias: { _ in nil }) == "n9")226 }227228 // MARK: Network, storage229230 @Test("network: latency and loss show the availability instead of a number that was not measured")231 func network() throws {232 Localization.shared.register(bundle: .main)233 let fmt: (Double) -> String = { "\($0) ms" }234 #expect(NetworkLogic.measured(12, availability: .available, format: fmt) == "12.0 ms")235 #expect(NetworkLogic.measured(12, availability: .stale, format: fmt) == "12.0 ms")236 #expect(NetworkLogic.measured(nil, availability: .unsupported, format: fmt) == API.Availability.unsupported.label)237 #expect(NetworkLogic.measured(0, availability: .permissionDenied, format: fmt) == API.Availability.permissionDenied.label)238 #expect(NetworkLogic.measured(nil, availability: .available, format: fmt) == tr("metric.not_reported"))239 func link(_ id: String, _ state: String) throws -> API.TopologyLink {240 try Self.decode(API.TopologyLink.self, """241 {"id":"\(id)","source":"a","target":"b","kind":"lan","state":"\(state)","latency_availability":"unsupported","loss_availability":"unsupported","freshness":"fresh"}242 """)243 }244 let links = [try link("l1", "up"), try link("l2", "unknown"), try link("l3", "down"), try link("l0", "up")]245 #expect(NetworkLogic.sorted(links).map(\.id) == ["l3", "l2", "l0", "l1"])246 let c = NetworkLogic.linkCounts(links)247 #expect(c.up == 2 && c.down == 1 && c.unknown == 1)248 #expect(NetworkLogic.linkTone(.down) == .critical && NetworkLogic.linkTone(.unknown) == .neutral)249 }250251 @Test("storage: fullest volume first, volumes without figures last; usage detail never invents a figure")252 func storage() throws {253 func volume(_ n: Int, used: Int64?, total: Int64?) throws -> API.Volume {254 try Self.decode(API.Volume.self, """255 {"id":"v\(n)","node_id":"n","node_alias":"ios-test-node-01","mount":"/m\(n)","kind":"internal"\(total.map { ",\"total_bytes\":\($0)" } ?? "")\(used.map { ",\"used_bytes\":\($0)" } ?? ""),256 "last_seen_at":"2026-11-18T20:00:00Z","freshness":"fresh"}257 """)258 }259 let v = [try volume(1, used: 10, total: 100), try volume(2, used: nil, total: 100), try volume(3, used: 95, total: 100), try volume(4, used: nil, total: nil)]260 #expect(StorageLogic.sorted(v).map(\.id) == ["v3", "v1", "v2", "v4"])261 #expect(StorageLogic.usageDetail(used: nil, total: nil) == nil)262 #expect(StorageLogic.usageDetail(used: nil, total: 1_000_000_000) == Format.bytes(1_000_000_000))263 #expect(StorageLogic.usageDetail(used: 1, total: 2) != nil)264 #expect(StorageLogic.nasTone(.offline) == .critical && StorageLogic.backupTone(.unknown) == .neutral && StorageLogic.backupTone(.ok) == .ok)265 }266267 // MARK: Strings268269 @Test("every key built at runtime by these screens exists in French and in English")270 func dynamicKeys() {271 Localization.shared.register(bundle: .main)272 for key in GroupADynamicKeys.all {273 for lang in AppLanguage.allCases {274 #expect(Localization.shared.has(key, language: lang), "missing \(key) in \(lang.rawValue)")275 }276 }277 #expect(GroupADynamicKeys.all.count == Set(GroupADynamicKeys.all).count)278 }279}280