Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : MacLustr Command Center (MCC)9// File : apps/ios/UITests/UITestSupport.swift10// Module : ios11// Repository : https://git.spboucher.ai/maclustr-command-center12// Project Website : https://clustr.spboucher.ai13// Created : 2026-11-1914// Last Modified : 2026-11-1915//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 Foundation89import Network90import XCTest9192/// Channel to Scripts/ui-test-control.py on the Mac (stop / start the backend, refresh synthetic timestamps, open a93/// Debug link with `simctl`, save screenshots). The simulator shares the Mac's loopback interface.94enum Control {95 static var port: UInt16 { UInt16(ProcessInfo.processInfo.environment["MCC_UI_CONTROL_PORT"] ?? "") ?? 0 }9697 @discardableResult98 static func send(_ line: String, payload: Data? = nil, timeout: TimeInterval = 60) -> Bool {99 guard port != 0, let p = NWEndpoint.Port(rawValue: port) else { return false }100 let connection = NWConnection(host: "127.0.0.1", port: p, using: .tcp)101 let done = DispatchSemaphore(value: 0)102 let result = ResultBox()103 let data = Data((line + "\n").utf8) + (payload ?? Data())104 connection.stateUpdateHandler = { state in105 switch state {106 case .ready:107 connection.send(content: data, completion: .contentProcessed { _ in108 connection.receive(minimumIncompleteLength: 1, maximumLength: 64) { reply, _, _, _ in109 result.ok = reply.map { String(decoding: $0, as: UTF8.self).hasPrefix("ok") } ?? false110 done.signal()111 }112 })113 case .failed, .cancelled:114 done.signal()115 default: break116 }117 }118 connection.start(queue: .global())119 _ = done.wait(timeout: .now() + timeout)120 connection.cancel()121 return result.ok122 }123124 private final class ResultBox: @unchecked Sendable { var ok = false }125}126127extension XCUIApplication {128 /// Any element carrying this accessibility identifier.129 func el(_ id: String) -> XCUIElement { descendants(matching: .any).matching(identifier: id).firstMatch }130}131132extension XCUIElement {133 @discardableResult134 func waitToExist(_ timeout: TimeInterval = 15, file: StaticString = #filePath, line: UInt = #line) -> XCUIElement {135 XCTAssertTrue(waitForExistence(timeout: timeout), "\(self) did not appear", file: file, line: line)136 return self137 }138139 func waitToDisappear(_ timeout: TimeInterval = 15, file: StaticString = #filePath, line: UInt = #line) {140 let gone = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: self)141 XCTAssertEqual(XCTWaiter().wait(for: [gone], timeout: timeout), .completed, "\(self) did not disappear", file: file, line: line)142 }143144 /// Waits until the accessibility value equals `value`.145 func waitForValue(_ value: String, timeout: TimeInterval = 30, file: StaticString = #filePath, line: UInt = #line) {146 let e = XCTNSPredicateExpectation(predicate: NSPredicate(format: "value == %@", value), object: self)147 XCTAssertEqual(XCTWaiter().wait(for: [e], timeout: timeout), .completed, "value of \(self) is '\(String(describing: self.value))', expected '\(value)'", file: file, line: line)148 }149150 /// Scrolls until the element can be tapped, then taps it. `within` is the scrollable screen to drag in; by default151 /// the frontmost one (the last element whose identifier starts with "screen-": a sheet, or the detail pane on iPad).152 func scrollAndTap(in app: XCUIApplication, within: XCUIElement? = nil, maxSwipes: Int = 12, file: StaticString = #filePath, line: UInt = #line) {153 scrollIntoView(in: app, within: within, maxSwipes: maxSwipes)154 XCTAssertTrue(waitForExistence(timeout: 5), "\(self) not found after scrolling", file: file, line: line)155 tap()156 }157158 func scrollIntoView(in app: XCUIApplication, within: XCUIElement? = nil, maxSwipes: Int = 12) {159 // Give a screen that is still laying out (data arriving) a moment before deciding to scroll.160 let deadline = Date().addingTimeInterval(4)161 while !(exists && isHittable) && Date() < deadline { usleep(250_000) }162 var n = 0163 while !(exists && isHittable) && n < maxSwipes {164 var region: XCUIElement = app165 if let within, within.exists {166 region = within167 } else {168 let screens = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'screen-'"))169 let count = screens.count170 if count > 0 { region = screens.element(boundBy: count - 1) }171 }172 // Drag inside the content, away from the bars and from the screen edges.173 let start = region.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.7))174 let end = region.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.35))175 start.press(forDuration: 0.05, thenDragTo: end)176 n += 1177 }178 // Overshot (the element was above): come back up.179 n = 0180 while !(exists && isHittable) && n < maxSwipes {181 let region: XCUIElement = (within?.exists ?? false) ? within! : app182 region.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.35)).press(forDuration: 0.05, thenDragTo: region.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.7)))183 n += 1184 }185 }186187 func clearAndType(_ text: String) {188 tap()189 if let current = value as? String, !current.isEmpty, current != placeholderValue {190 typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: current.count))191 }192 typeText(text)193 }194}195