SPB Git

Repository Public

MCCUITests.swift 19.2 KB 403 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr Command Center (MCC)9// File             : apps/macos/UITests/MCCUITests.swift10// Module           : macos11// Repository       : https://git.spboucher.ai/maclustr-command-center12// Project Website  : https://clustr.spboucher.ai13// Created          : 2026-11-1814// Last Modified    : 2026-11-1815//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: admin@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import XCTest8990/// End-to-end UI tests against a REAL local control-api (started by Scripts/test.sh on a throwaway database).91/// Passkeys: the Debug-only software authenticator (a native app cannot use system passkeys for `localhost`);92/// the server verifies its attestations and assertions like any other. Tests run in name order and share the93/// signed-in state created by the first one.94final class MCCUITests: XCTestCase {95    static let env = ProcessInfo.processInfo.environment96    static var origin: String { env["MCC_UI_ORIGIN"] ?? "http://localhost:8760" }97    static var configured: Bool { env["MCC_UI_SETUP_TOKEN"]?.isEmpty == false && env["MCC_UI_CONTROL_PORT"] != nil }98    static let nodeAlias = "ui-node"99100    override func setUpWithError() throws {101        continueAfterFailure = false102        try XCTSkipUnless(Self.configured, "run through Scripts/test.sh ui (needs the local backend)")103    }104105    // MARK: Helpers106107    @discardableResult108    private func launch(reset: Bool = false, setupToken: String? = nil, language: String? = "fr") -> XCUIApplication {109        let app = XCUIApplication()110        var e = ["MCC_BASE_URL": Self.origin, "MCC_PASSKEY": "software", "MCC_SECURE_STORE": "file", "MCC_UITEST": "1"]111        if reset { e["MCC_RESET"] = "1" }112        if let setupToken { e["MCC_SETUP_TOKEN"] = setupToken }113        if let language { e["MCC_LANGUAGE"] = language }114        app.launchEnvironment = e115        app.launchArguments = ["-ApplePersistenceIgnoreState", "YES", "-NSQuitAlwaysKeepsWindows", "NO"]116        app.launch()117        app.activate()118        return app119    }120121    private func element(_ app: XCUIApplication, _ id: String) -> XCUIElement {122        app.descendants(matching: .any).matching(identifier: id).firstMatch123    }124125    private func wait(_ e: XCUIElement, _ timeout: TimeInterval = 15, file: StaticString = #filePath, line: UInt = #line) {126        XCTAssertTrue(e.waitForExistence(timeout: timeout), "missing element: \(e)", file: file, line: line)127    }128129    private func waitGone(_ e: XCUIElement, _ timeout: TimeInterval = 60, file: StaticString = #filePath, line: UInt = #line) {130        let gone = expectation(for: NSPredicate(format: "exists == false"), evaluatedWith: e)131        XCTAssertEqual(XCTWaiter().wait(for: [gone], timeout: timeout), .completed, "still present: \(e)", file: file, line: line)132    }133134    private func waitValue(_ e: XCUIElement, contains text: String, _ timeout: TimeInterval = 30, file: StaticString = #filePath, line: UInt = #line) {135        let p = NSPredicate(format: "label CONTAINS[c] %@ OR value CONTAINS[c] %@", text, text)136        let ok = expectation(for: p, evaluatedWith: e)137        XCTAssertEqual(XCTWaiter().wait(for: [ok], timeout: timeout), .completed, "\(e) never showed “\(text)” (label: \(e.label))", file: file, line: line)138    }139140    /// True when some element shows `text` in its label or value (rows expose "label / value" pairs to accessibility).141    private func shows(_ app: XCUIApplication, _ text: String, timeout: TimeInterval = 5) -> Bool {142        let p = NSPredicate(format: "label CONTAINS[c] %@ OR value CONTAINS[c] %@", text, text)143        return app.descendants(matching: .any).matching(p).firstMatch.waitForExistence(timeout: timeout)144    }145146    /// Navigates with the documented keyboard shortcuts (⌘1…⌘0, ⌘,), which also exercises the menu commands.147    private func go(_ app: XCUIApplication, _ section: String) {148        let keys = ["overview": "1", "nodes": "2", "services": "3", "models": "4", "jobs": "5", "network": "6", "storage": "7",149                    "alerts": "8", "maintenance": "9", "activity": "0", "settings": ","]150        wait(element(app, "sidebar-\(section)"))151        app.typeKey(keys[section]!, modifierFlags: .command)152    }153154    /// Sends one command to Scripts/ui-test-control.py (the runner is sandboxed: it cannot do these things itself).155    @discardableResult156    private func control(_ header: String, payload: Data = Data()) -> Bool {157        guard let port = Self.env["MCC_UI_CONTROL_PORT"].flatMap(UInt16.init) else { return false }158        let fd = socket(AF_INET, SOCK_STREAM, 0)159        guard fd >= 0 else { return false }160        defer { close(fd) }161        var addr = sockaddr_in()162        addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)163        addr.sin_family = sa_family_t(AF_INET)164        addr.sin_port = port.bigEndian165        addr.sin_addr.s_addr = inet_addr("127.0.0.1")166        let connected = withUnsafePointer(to: &addr) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(fd, $0, socklen_t(MemoryLayout<sockaddr_in>.size)) } }167        guard connected == 0 else { return false }168        var out = Data((header + "\n").utf8)169        out.append(payload)170        let sent = out.withUnsafeBytes { raw -> Bool in171            var offset = 0172            while offset < raw.count {173                let n = write(fd, raw.baseAddress! + offset, raw.count - offset)174                if n <= 0 { return false }175                offset += n176            }177            return true178        }179        guard sent else { return false }180        var buf = [UInt8](repeating: 0, count: 16)181        let n = read(fd, &buf, buf.count)182        return n >= 2 && String(decoding: buf.prefix(2), as: UTF8.self) == "ok"183    }184185    private func stopBackend() { XCTAssertTrue(control("stop"), "could not stop the local backend") }186    private func startBackend() { XCTAssertTrue(control("start"), "could not start the local backend") }187188    /// Saves a screenshot of the frontmost window when a directory was given (documentation screenshots).189    private func snapshot(_ app: XCUIApplication, _ name: String, window: XCUIElement? = nil) {190        guard Self.env["MCC_UI_SCREENSHOTS"] == "1" else { return }191        let w = window ?? app.windows.firstMatch192        guard w.exists else { return }193        let png = w.screenshot().pngRepresentation194        control("shot \(name) \(png.count)", payload: png)195    }196197    // MARK: Tests198199    /// Invitation setup (identity and role shown before the passkey exists), then sign-out and passkey sign-in.200    func test01_InvitationSetupThenPasskeySignIn() throws {201        let app = launch(reset: true, setupToken: Self.env["MCC_UI_SETUP_TOKEN"])202        // The invitation is explained before anything is created.203        let accept = element(app, "setup-accept")204        wait(accept, 30)205        snapshot(app, "02-invitation-review")206        XCTAssertTrue(shows(app, "owner-ui"), "the handle of the invited identity is shown")207        XCTAssertTrue(shows(app, "Owner UI"))208        XCTAssertTrue(shows(app, "Propriétaire"), "the role is shown before the passkey is created")209        snapshot(app, "02-invitation-review")210        accept.click()211        let create = element(app, "setup-create-passkey")212        wait(create)213        snapshot(app, "03-invitation-passkey")214        create.click()215        let finish = element(app, "setup-finish")216        wait(finish, 30)217        finish.click()218        wait(element(app, "sidebar-overview"), 30)219        waitValue(element(app, "account-footer"), contains: "Owner UI")220        waitValue(element(app, "global-state"), contains: "En direct", 30)   // the event stream is connected221        snapshot(app, "04-overview")222223        // Sign out.224        app.menuBars.menuBarItems.element(boundBy: 1).click()225        app.menuItems["Se déconnecter"].click()226        let signIn = element(app, "sign-in")227        wait(signIn, 20)228        XCTAssertTrue(shows(app, "localhost"), "the Debug build says which server it talks to")229        snapshot(app, "01-sign-in")230231        // The same invitation link again: single use → an explained dead end with a correlation id.232        element(app, "invitation-disclosure").click()233        let field = element(app, "invitation-link")234        wait(field)235        field.click()236        field.typeText(Self.env["MCC_UI_SETUP_TOKEN"]!)        // the bare token is accepted as well as the full link237        element(app, "invitation-continue").click()238        wait(element(app, "setup-invalid"), 30)239        XCTAssertTrue(element(app, "correlation-id").exists, "the refusal carries a correlation id")240        snapshot(app, "05-invitation-invalid")241        element(app, "setup-cancel").click()242243        // Passkey sign-in with the credential created above.244        wait(signIn, 20)245        signIn.click()246        wait(element(app, "sidebar-overview"), 30)247        waitValue(element(app, "account-footer"), contains: "Propriétaire")248    }249250    private func relaunchSignedIn(language: String? = "fr") -> XCUIApplication {251        let app = launch(language: language)252        wait(element(app, "sidebar-overview"), 30)253        return app254    }255256    private func text(_ app: XCUIApplication, _ value: String) -> XCUIElement {257        app.staticTexts.matching(NSPredicate(format: "value == %@ OR label == %@", value, value)).firstMatch258    }259260    /// A confirmed action from the catalog, end to end: form generated from the server's schema, request, live261    /// window, final state — and its effect on the node.262    func test02_ActionEndToEnd() throws {263        let app = relaunchSignedIn()264        go(app, "nodes")265        let add = element(app, "nodes-add")266        wait(add)267        add.click()268        let alias = element(app, "node-create-alias")269        wait(alias)270        alias.click()271        alias.typeText(Self.nodeAlias)272        element(app, "node-create-submit").click()273        let cell = text(app, Self.nodeAlias)274        wait(cell, 20)275        snapshot(app, "06-nodes")276        cell.doubleClick()                                   // opens the node in its own window277        let menu = element(app, "action-menu")278        wait(menu, 20)279        snapshot(app, "07-node-detail", window: app.windows.element(boundBy: 0))280        menu.click()281        var item = app.menuItems.matching(identifier: "action-type-node.maintenance.set").firstMatch282        if !item.waitForExistence(timeout: 5) { item = app.menuItems.matching(NSPredicate(format: "title CONTAINS[c] %@", "maintenance")).firstMatch }283        wait(item)284        item.click()285        let submit = element(app, "action-submit")286        wait(submit, 20)287        XCTAssertFalse(submit.isEnabled == false && element(app, "param-enabled").exists == false, "the form is generated from the catalog schema")288        element(app, "param-enabled").click()                // enabled = true289        snapshot(app, "08-action-request", window: app.windows.element(boundBy: 0))290        XCTAssertTrue(submit.isEnabled)291        submit.click()292        let state = element(app, "action-state")293        wait(state, 30)294        waitValue(state, contains: "Réussie", 45)            // executed by the real orchestrator295        snapshot(app, "09-action-window", window: app.windows.element(boundBy: 0))296        XCTAssertTrue(shows(app, "En entretien", timeout: 30), "the node is now in maintenance mode")297    }298299    /// Maintenance calendar: create a window on the node, then take a note on it.300    func test03_MaintenanceWindowAndNote() throws {301        let app = relaunchSignedIn()302        go(app, "maintenance")303        let new = element(app, "maintenance-new-window")304        wait(new, 20)305        snapshot(app, "10-maintenance-calendar")306        new.click()307        let title = element(app, "maintenance-form-title")308        wait(title)309        title.click()310        title.typeText("Remplacement SSD")311        let node = element(app, "maintenance-form-node-\(Self.nodeAlias)")312        wait(node)313        node.click()314        snapshot(app, "11-maintenance-form")315        element(app, "maintenance-form-save").click()316        XCTAssertTrue(shows(app, "Remplacement SSD", timeout: 30), "the new window appears in the calendar")317        let detail = element(app, "maintenance-detail")318        if !detail.waitForExistence(timeout: 5) {319            app.descendants(matching: .any).matching(NSPredicate(format: "label CONTAINS %@ OR value CONTAINS %@", "Remplacement SSD", "Remplacement SSD")).firstMatch.click()320        }321        wait(detail, 20)322        let composer = element(app, "maintenance-note-composer")323        wait(composer, 20)324        composer.click()325        composer.typeText("Commander le SSD de rechange avant jeudi")326        let addNote = element(app, "maintenance-note-add")327        wait(addNote)328        addNote.click()329        XCTAssertTrue(shows(app, "Commander le SSD de rechange avant jeudi", timeout: 30), "the note is saved and listed")330        snapshot(app, "12-maintenance-note")331    }332333    /// Server unreachable → read-only with timestamps; server back → reconnection without relaunch.334    func test04_OfflineReadOnlyThenReconnect() throws {335        let app = relaunchSignedIn()336        go(app, "nodes")337        wait(text(app, Self.nodeAlias), 20)338        waitValue(element(app, "global-state"), contains: "En direct", 30)339        stopBackend()340        let banner = element(app, "offline-banner")341        wait(banner, 60)342        waitValue(banner, contains: "Hors ligne depuis")343        app.typeKey("r", modifierFlags: .command)             // a refresh attempt fails: the cached data stays, dated344        let stale = element(app, "stale-banner")345        wait(stale, 30)346        waitValue(stale, contains: "Données du")347        XCTAssertTrue(text(app, Self.nodeAlias).exists, "the last known data is still shown")348        XCTAssertFalse(element(app, "nodes-add").isEnabled, "mutations are disabled while offline")349        snapshot(app, "13-offline")350        startBackend()351        waitGone(banner, 120)352        waitValue(element(app, "global-state"), contains: "En direct", 60)353        waitGone(stale, 60)354        XCTAssertTrue(element(app, "nodes-add").isEnabled)355    }356357    /// The interface language switches at runtime, without relaunch.358    func test05_LanguageSwitch() throws {359        let app = relaunchSignedIn(language: nil)360        XCTAssertTrue(element(app, "sidebar-nodes").label.contains("Nœuds") || shows(app, "Nœuds"))361        go(app, "settings")362        let pane = element(app, "settings-pane-profile")363        if pane.waitForExistence(timeout: 10) { pane.click() }364        let picker = element(app, "language-picker")365        wait(picker, 20)366        snapshot(app, "14-settings")367        let english = picker.radioButtons["English"]368        wait(english)369        english.click()370        XCTAssertTrue(shows(app, "Nodes", timeout: 15), "the sidebar is now in English")371        XCTAssertTrue(shows(app, "Maintenance"))372        snapshot(app, "15-settings-english")373        // Back to French for whoever runs the app next.374        let french = picker.radioButtons["Français"]375        wait(french)376        french.click()377        XCTAssertTrue(shows(app, "Nœuds", timeout: 15))378    }379380    /// Visits the remaining sections against the real backend and records what they honestly show.381    func test06_SectionTour() throws {382        let app = relaunchSignedIn()383        for (section, name) in [("services", "16-services"), ("models", "17-models"), ("jobs", "18-jobs"), ("network", "19-network"),384                                ("storage", "20-storage"), ("alerts", "21-alerts"), ("activity", "22-activity"), ("overview", "24-overview-after")] {385            go(app, section)386            sleep(2)387            XCTAssertFalse(element(app, "state-error").exists, "\(section) shows an unexpected error state")388            snapshot(app, name)389        }390        app.typeKey("a", modifierFlags: [.command, .option])     // Audit391        sleep(2)392        XCTAssertFalse(element(app, "state-error").exists, "audit shows an unexpected error state")393        snapshot(app, "23-audit")394        app.typeKey("k", modifierFlags: .command)                // command palette395        let field = element(app, "palette-field")396        wait(field)397        field.typeText("ui-n")398        XCTAssertTrue(shows(app, Self.nodeAlias, timeout: 15), "universal search finds the node")399        snapshot(app, "25-command-palette")400        app.typeKey(.escape, modifierFlags: [])401    }402}403
Files main
Menu

Theme