SPB Git

Repository Public

ShellTests.swift 16.8 KB 335 lines swift

1import Foundation2import SwiftUI3import Testing4import UIKit5@testable import MCCCore6@testable import MCCiOS78private let nodeA = "105e0000-0000-7000-8000-000000000001"9private let alertA = "105e0000-0000-7000-8000-0000000a1e47"1011@Suite("Navigation and state restoration")12@MainActor13struct NavigationTests {14    @Test("phone: a row tap pushes on the current tab; sections of the More tab are pushed under it")15    func phonePaths() {16        let nav = Navigator()17        nav.layout = .phone18        nav.show(.nodes)19        #expect(nav.tab == .nodes && nav.phonePaths[.nodes] == [])20        nav.open(.node(nodeA))21        #expect(nav.phonePaths[.nodes] == [.node(nodeA)])22        #expect(nav.currentSection == .nodes)23        nav.show(.maintenance)24        #expect(nav.tab == .more)25        #expect(nav.phonePaths[.more] == [.section(.maintenance)])26        #expect(nav.currentSection == .maintenance)27        nav.open(.maintenanceWindow(id: nodeA, occurrence: nil))28        #expect(nav.phonePaths[.more]?.count == 2)29        // The other tab kept its own stack.30        #expect(nav.phonePaths[.nodes] == [.node(nodeA)])31    }3233    @Test("iPad: the primary item of a master-detail section fills the detail pane, anything else is pushed")34    func padSelection() {35        let nav = Navigator()36        nav.layout = .pad37        nav.show(.nodes)38        nav.open(.node(nodeA))39        #expect(nav.padSelection[.nodes] == .node(nodeA))40        #expect(nav.padPaths[.nodes] == [])41        #expect(nav.isSelected(.node(nodeA)))42        nav.open(.nodeNotes(nodeA))43        #expect(nav.padPaths[.nodes] == [.nodeNotes(nodeA)])44        // Selecting another node clears what was pushed on the previous one.45        nav.open(.compare([nodeA, alertA]))46        #expect(nav.padSelection[.nodes] == .compare([nodeA, alertA]))47        #expect(nav.padPaths[.nodes] == [])48        // A section link switches section instead of pushing.49        nav.open(.section(.alerts))50        #expect(nav.section == .alerts)51        // A non master-detail section pushes on its single stack.52        nav.show(.maintenance)53        nav.open(.maintenanceWindow(id: nodeA, occurrence: nil))54        #expect(nav.padSelection[.maintenance] == nil)55        #expect(nav.padPaths[.maintenance]?.count == 1)56    }5758    @Test("go(to:) lands in the right section on both layouts (deep link, notification, search)")59    func goTo() {60        let nav = Navigator()61        nav.layout = .phone62        nav.go(to: .alert(alertA))63        #expect(nav.tab == .alerts && nav.phonePaths[.alerts] == [.alert(alertA)])64        #expect(nav.section == .alerts && nav.padSelection[.alerts] == .alert(alertA))65        nav.go(to: .service(nodeA))66        #expect(nav.tab == .more)67        #expect(nav.phonePaths[.more] == [.section(.services), .service(nodeA)])68        nav.go(to: .section(.audit))69        #expect(nav.phonePaths[.more] == [.section(.audit)] && nav.section == .audit)70    }7172    @Test("state restoration: tab, section and open node survive an encode / decode round trip")73    func restoration() throws {74        let nav = Navigator()75        nav.layout = .phone76        nav.show(.nodes)77        nav.open(.node(nodeA))78        nav.padSelection[.alerts] = .alert(alertA)79        let stored = nav.snapshot.encoded80        #expect(!stored.isEmpty)8182        let restored = Navigator()83        restored.snapshot = try #require(NavigationSnapshot.decode(stored))84        #expect(restored.tab == .nodes)85        #expect(restored.section == .nodes)86        #expect(restored.phonePaths[.nodes] == [.node(nodeA)])87        #expect(restored.padSelection[.alerts] == .alert(alertA))88        #expect(restored.snapshot == nav.snapshot)89        // Garbage or an older format restores nothing instead of crashing.90        #expect(NavigationSnapshot.decode("") == nil)91        #expect(NavigationSnapshot.decode("{\"tab\":\"gone\"}") == nil)92        // Only the first two levels of a stack are kept.93        nav.open(.nodeNotes(nodeA)); nav.open(.settings(.about))94        #expect(nav.snapshot.phonePaths["nodes"]?.count == 2)95    }9697    @Test("a tab tap keeps the section in sync (restoration, shell switch); a session end resets the navigation")98    func tabSyncAndReset() {99        let nav = Navigator()100        nav.layout = .phone101        nav.tab = .alerts                      // what the tab bar binding does102        #expect(nav.section == .alerts && nav.currentSection == .alerts)103        nav.show(.storage)104        #expect(nav.section == .storage && nav.tab == .more)105        nav.tab = .nodes106        nav.tab = .more                        // back to More: the section under it is current again107        #expect(nav.section == .storage)108        nav.open(.node(nodeA)); nav.sheet = .search109        nav.reset()110        #expect(nav.tab == .overview && nav.section == .overview && nav.sheet == nil)111        #expect(nav.phonePaths.isEmpty && nav.padSelection.isEmpty && nav.padPaths.isEmpty)112    }113114    @Test("every section is reachable: tabs + More on iPhone, ⌘1…⌘9 on iPad")115    func sections() {116        #expect(Set(AppSection.primary + AppSection.secondary) == Set(AppSection.allCases))117        #expect(AppSection.primary.map(PhoneTab.tab(for:)) == [.overview, .nodes, .alerts, .actions])118        #expect(AppSection.secondary.allSatisfy { PhoneTab.tab(for: $0) == .more })119        #expect(AppSection.allCases.compactMap(\.shortcutIndex) == Array(1...9))120        #expect(Set(SettingsPane.personal + SettingsPane.admin) == Set(SettingsPane.allCases))121        #expect(SettingsPane.personal.allSatisfy { $0.permission == nil })122        #expect(SettingsPane.admin.allSatisfy { $0.permission != nil })123    }124}125126@Suite("Links")127struct LinkTests {128    @Test("universal links and the Debug scheme map to routes; anything else is ignored")129    func deepLinks() {130        func r(_ s: String) -> Route? { DeepLink.route(for: URL(string: s)!) }131        #expect(r("https://clustr.spboucher.ai/open/alerts/\(alertA)") == .alert(alertA))132        #expect(r("https://clustr.spboucher.ai/open/nodes/\(nodeA)") == .node(nodeA))133        #expect(r("https://clustr.spboucher.ai/open/actions/\(nodeA)") == .action(nodeA))134        #expect(r("https://clustr.spboucher.ai/open/maintenance/\(nodeA)") == .maintenanceWindow(id: nodeA, occurrence: nil))135        #expect(r("https://clustr.spboucher.ai/open/maintenance") == .section(.maintenance))136        #expect(r("https://clustr.spboucher.ai/open/incidents") == .section(.alerts))137        #expect(r("mcc-ios-debug://open/alerts/\(alertA)") == .alert(alertA))138        #expect(r("https://clustr.spboucher.ai/open/alerts/not-a-uuid") == nil)139        #expect(r("https://clustr.spboucher.ai/open/unknown") == nil)140        #expect(r("https://clustr.spboucher.ai/other") == nil)141    }142143    @Test("the setup link is recognised in its universal and Debug forms; the token never reaches a route")144    func setupLinks() {145        let token = "aCki2xqqqOPK-0123456789_abcdefghijklmnopqrstu"146        #expect(SetupLink.token(from: "https://clustr.spboucher.ai/setup#\(token)") == token)147        #expect(SetupLink.token(from: "mcc-ios-debug://setup#\(token)") == token)148        #expect(SetupLink.token(from: "https://clustr.spboucher.ai/setup") == nil)149        #expect(DeepLink.route(for: URL(string: "https://clustr.spboucher.ai/setup#\(token)")!) == nil)150    }151152    @Test("a notification can only open a screen: alert or action, identified by a UUID")153    func notificationRouting() {154        #expect(NotificationRouting.route(for: ["alert_id": alertA]) == .alert(alertA))155        #expect(NotificationRouting.route(for: ["action_id": nodeA]) == .action(nodeA))156        #expect(NotificationRouting.route(for: ["alert_id": "../../x"]) == nil)157        #expect(NotificationRouting.route(for: ["aps": ["alert": "x"]]) == nil)158        #expect(NotificationRouting.route(for: ["alert_id": 3]) == nil)159    }160161    @Test("search results map to routes")162    func searchRoutes() throws {163        func result(_ kind: String) throws -> API.SearchResult {164            try JSONDecoder().decode(API.SearchResult.self, from: Data("{\"kind\":\"\(kind)\",\"id\":\"\(nodeA)\",\"title\":\"t\",\"score\":1}".utf8))165        }166        #expect(SearchSheet.route(for: try result("node")) == .node(nodeA))167        #expect(SearchSheet.route(for: try result("inference_server")) == .model(nodeA))168        #expect(SearchSheet.route(for: try result("maintenance_window")) == .maintenanceWindow(id: nodeA, occurrence: nil))169        #expect(SearchSheet.route(for: try result("maintenance_note")) == .section(.maintenance))170    }171}172173@Suite("App lock")174@MainActor175struct AppLockTests {176    final class Clock: @unchecked Sendable { var now = Date(timeIntervalSince1970: 1_800_000_000) }177    final class Outcome: @unchecked Sendable { var result: Result<Void, AppLock.LockError> = .success(()); var calls = 0 }178179    func make(enabled: Bool, grace: TimeInterval = 0) -> (AppLock, Clock, Outcome, UserDefaults) {180        let name = "mcc.lock.tests.\(UUID().uuidString)"181        let d = UserDefaults(suiteName: name)!182        d.removePersistentDomain(forName: name)183        d.set(enabled, forKey: AppLock.enabledKey)184        d.set(grace, forKey: AppLock.graceKey)185        let clock = Clock(), outcome = Outcome()186        let lock = AppLock(defaults: d, now: { clock.now }) { _ in outcome.calls += 1; return outcome.result }187        return (lock, clock, outcome, d)188    }189190    @Test("disabled: never locks")191    func disabled() async {192        let (lock, _, outcome, _) = make(enabled: false)193        lock.lockAtLaunchIfEnabled()194        lock.appDidEnterBackground(); lock.appDidBecomeActive()195        #expect(!lock.isLocked)196        #expect(await lock.unlock(reason: "r"))197        #expect(outcome.calls == 0)198    }199200    @Test("enabled: locked at launch and when going to the background; unlock needs the system check")201    func lockAndUnlock() async {202        let (lock, _, outcome, _) = make(enabled: true)203        lock.lockAtLaunchIfEnabled()204        #expect(lock.isLocked)205        outcome.result = .failure(.cancelled)206        #expect(!(await lock.unlock(reason: "r")))207        #expect(lock.isLocked && lock.lastError == nil)208        outcome.result = .failure(.failed("no match"))209        #expect(!(await lock.unlock(reason: "r")))210        #expect(lock.isLocked && lock.lastError == .failed("no match"))211        outcome.result = .success(())212        #expect(await lock.unlock(reason: "r"))213        #expect(!lock.isLocked && lock.lastError == nil)214        // No grace period: locked as soon as the app leaves the foreground (the switcher snapshot shows the lock).215        lock.appDidEnterBackground()216        #expect(lock.isLocked)217    }218219    @Test("grace period: a short trip to the background does not lock, a long one does")220    func grace() {221        let (lock, clock, _, _) = make(enabled: true, grace: 60)222        lock.appDidEnterBackground()223        #expect(!lock.isLocked)224        clock.now += 30225        lock.appDidBecomeActive()226        #expect(!lock.isLocked)227        lock.appDidEnterBackground()228        clock.now += 61229        lock.appDidBecomeActive()230        #expect(lock.isLocked)231    }232233    @Test("turning the lock on requires passing it once; the choice is persisted; turning it off unlocks")234    func enable() async {235        let (lock, _, outcome, d) = make(enabled: false)236        outcome.result = .failure(.unavailable("no passcode"))237        #expect(!(await lock.enable(reason: "r")))238        #expect(!lock.isEnabled && lock.lastError == .unavailable("no passcode"))239        outcome.result = .success(())240        #expect(await lock.enable(reason: "r"))241        #expect(lock.isEnabled && d.bool(forKey: AppLock.enabledKey))242        lock.lockAtLaunchIfEnabled()243        lock.isEnabled = false244        #expect(!lock.isLocked && !d.bool(forKey: AppLock.enabledKey))245    }246}247248@Suite("Launch configuration, notifications, catalogs")249@MainActor250struct EnvironmentTests {251    @Test("Debug overrides are read from the environment; without them the build targets production")252    func environment() {253        let prod = AppEnvironment.resolve([:])254        #expect(prod.origin == CoreConfiguration.productionOrigin && prod.isProduction)255        #expect(!prod.softwarePasskeys && prod.secureStore == .keychain && prod.launchURL == nil)256        let dev = AppEnvironment.resolve(["MCC_BASE_URL": "http://localhost:8780", "MCC_PASSKEY": "software", "MCC_SECURE_STORE": "file",257                                          "MCC_LANGUAGE": "en", "MCC_UITEST": "1", "MCC_OPEN_URL": "mcc-ios-debug://setup#abc"])258        #expect(dev.origin.absoluteString == "http://localhost:8780" && !dev.isProduction)259        #expect(dev.softwarePasskeys && dev.secureStore == .file && dev.language == .en && dev.uiTesting)260        #expect(dev.launchURL?.scheme == AppEnvironment.debugScheme)261        // A malformed base URL is ignored rather than sending credentials somewhere unexpected.262        #expect(AppEnvironment.resolve(["MCC_BASE_URL": "not a url"]).isProduction)263        #expect(AppEnvironment.pushIsProduction == false)   // tests run a Debug build264    }265266    @Test("local alert notifications: only a firing, non-suppressed alert is announced")267    func alertContent() throws {268        func event(_ state: String, suppressed: Bool = false) throws -> API.AlertChangedEvent {269            try JSONDecoder().decode(API.AlertChangedEvent.self, from: Data("""270            {"alert_id":"\(alertA)","rule_id":"\(nodeA)","node_id":"\(nodeA)","state":"\(state)","severity":"critical","summary":"CPU saturated","suppressed":\(suppressed)}271            """.utf8))272        }273        let c = try #require(AlertNotificationContent.make(for: try event("firing"), nodeAlias: "ios-test-node-01"))274        #expect(c.identifier == "alert-" + alertA && c.body == "CPU saturated" && c.critical)275        #expect(c.title.contains("ios-test-node-01"))276        #expect(AlertNotificationContent.make(for: try event("resolved"), nodeAlias: nil) == nil)277        #expect(AlertNotificationContent.make(for: try event("acknowledged"), nodeAlias: nil) == nil)278        #expect(AlertNotificationContent.make(for: try event("firing", suppressed: true), nodeAlias: nil) == nil)279    }280281    @Test("error text of a refused mutation carries the server message, the status and the correlation id")282    func mutationErrorText() {283        let e = APIError(status: 403, code: "forbidden", message: "permission actions.run.medium required", correlationID: "c-123")284        let text = MutationErrorText.describe(e)285        #expect(text.contains("permission actions.run.medium required") && text.contains("403") && text.contains("c-123"))286    }287288    @Test("every key built at runtime exists in French and English; the app catalogs are registered")289    func dynamicKeys() {290        Localization.shared.register(bundle: Bundle(for: AppModel.self))291        for key in DynamicKeys.all {292            for lang in AppLanguage.allCases {293                #expect(Localization.shared.has(key, language: lang), "missing \(key) in \(lang.rawValue)")294            }295        }296        #expect(Localization.shared.string("section.nodes", language: .fr) == "Nœuds")297        #expect(Localization.shared.string("section.nodes", language: .en) == "Nodes")298    }299300    @Test("token contrast: text tokens on surface tokens reach WCAG AA (4.5:1), in the dark and light themes")301    func tokenContrast() {302        func luminance(_ c: Color) -> Double {303            var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0304            UIColor(c).getRed(&r, green: &g, blue: &b, alpha: &a)305            func lin(_ v: CGFloat) -> Double { let x = Double(v); return x <= 0.03928 ? x / 12.92 : pow((x + 0.055) / 1.055, 2.4) }306            return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)307        }308        func ratio(_ a: Color, _ b: Color) -> Double {309            let la = luminance(a), lb = luminance(b)310            return (max(la, lb) + 0.05) / (min(la, lb) + 0.05)311        }312        for scheme in [ColorScheme.dark, .light] {313            let t = MCCTheme(scheme: scheme)314            for surface in [t.canvas, t.surface, t.raised] {315                #expect(ratio(t.textPrimary, surface) >= 7, "primary text, \(scheme)")316                #expect(ratio(t.textSecondary, surface) >= 4.5, "secondary text, \(scheme)")317            }318            // Primary buttons: the contrast token on the accent fill.319            #expect(ratio(t.accentContrast, t.accent) >= 4.5, "primary button label, \(scheme)")320        }321    }322323    @Test("MutationRunner: one mutation at a time; a failure is kept for display, a cancelled passkey is not an error")324    func mutationRunner() async {325        let runner = MutationRunner()326        #expect(await runner.run { 42 } == 42)327        #expect(runner.error == nil)328        let refused: Int? = await runner.run { throw APIError(status: 403, code: "forbidden", message: "no") }329        #expect(refused == nil && runner.error?.isForbidden == true)330        runner.error = nil331        let cancelled: Int? = await runner.run { throw APIError(code: APIError.codePasskeyCancelled, message: "cancelled") }332        #expect(cancelled == nil && runner.error == nil)333    }334}335
Files main
Menu

Theme