SPB Git

Repository Public BSD-3-Clause

Support.swift 13.9 KB 287 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Apps/ORIXMaps/Tests/ORIXMapsUITests/Support.swift10// Module           : ORIXMapsUITests11// Repository       : https://git.spboucher.ai/orix-maps12// Created          : 2026-11-2513// Last Modified    : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import XCTest8990/// Loopback endpoints started by scripts/uitest.sh (see docs/TESTING.md). Override with TEST_RUNNER_ORIX_* variables.91enum TestServer {92    private static func value(_ name: String, _ fallback: String) -> String { ProcessInfo.processInfo.environment[name] ?? fallback }93    /// The development distribution, unthrottled.94    static var catalog: String { value("ORIX_CATALOG_URL", "http://127.0.0.1:8765/maps/v1/") }95    /// The same distribution, slowed down to exercise pause, resume and relaunch.96    static var throttledCatalog: String { value("ORIX_THROTTLED_CATALOG_URL", "http://127.0.0.1:8766/maps/v1/") }97    /// A port nothing listens on: the catalog cannot be reached.98    static var stoppedCatalog: String { value("ORIX_STOPPED_CATALOG_URL", "http://127.0.0.1:8799/maps/v1/") }99    /// Appearance of the simulator, set by scripts/uitest.sh with `simctl ui <udid> appearance` before each phase100    /// (XCUIDevice's own appearance setter has no effect on this simulator runtime).101    static var isDark: Bool { value("ORIX_APPEARANCE", "light") == "dark" }102}103104/// Places of the test region (Greater Montréal).105enum Place {106    static let downtown = "45.5017,-73.5673"107    static let olympicStadium = "45.5579,-73.5515"108    static let region = "ca-qc-montreal"109}110111@MainActor112class ORIXUITestCase: XCTestCase {113    var app: XCUIApplication!114    var springboard: XCUIApplication { XCUIApplication(bundleIdentifier: "com.apple.springboard") }115116    /// Language of the interface under test. Functional tests read English labels; the screenshot tours also run in French.117    var language: (code: String, locale: String) = ("en", "en_CA")118    /// Extra launch arguments added to every launch of the test (appearance or text size under test).119    var commonArguments: [String] = []120121    override func setUp() async throws {122        continueAfterFailure = false123        XCUIDevice.shared.orientation = UIDevice.current.userInterfaceIdiom == .pad ? .landscapeLeft : .portrait124        dismissSystemAlerts()125    }126127    override func tearDown() async throws {128        if let app, app.state != .notRunning { app.terminate() }129    }130131    var isPad: Bool { UIDevice.current.userInterfaceIdiom == .pad }132133    /// Tests of the dark appearance run in the dark phase of scripts/uitest.sh, and only there.134    func requireDarkPhase() throws { try XCTSkipUnless(TestServer.isDark, "runs in the dark phase of scripts/uitest.sh (simulator appearance set to dark)") }135    func requireLightPhase() throws { try XCTSkipIf(TestServer.isDark, "runs in the light phase of scripts/uitest.sh") }136137    // MARK: Launch138139    /// Launches the application in an isolated, freshly reset state.140    /// - Parameters:141    ///   - region: download and install the test region from the local server before the test starts.142    ///   - reset: erase data and preferences first (false = relaunch on the data of the previous launch).143    @discardableResult144    func launch(region: Bool = false, reset: Bool = true, onboarding: Bool = false, catalog: String? = TestServer.catalog, camera: String? = "45.5017,-73.5673,14",145                extra: [String] = []) -> XCUIApplication {146        let app = XCUIApplication()147        var arguments = ["-ORIXUITest", "YES", "-AppleLanguages", "(\(language.code))", "-AppleLocale", language.locale]148        if reset { arguments += ["-ORIXReset", "YES"] }149        if !onboarding { arguments += ["-ORIXSkipOnboarding", "YES"] }150        if let catalog { arguments += ["-ORIXCatalogURL", catalog] }151        if let camera { arguments += ["-ORIXCamera", camera] }152        if region { arguments += ["-ORIXAutoDownload", Place.region] }153        app.launchArguments = arguments + commonArguments + extra154        app.launch()155        self.app = app156        // With a route scenario the planner opens by itself once the region is ready: there is no home panel to wait for.157        if region, !extra.contains("-ORIXRouteTo") { waitForRegion() }158        return app159    }160161    /// The region is usable when the category shortcuts appear (the search index is open) — routing opens with it.162    func waitForRegion(timeout: TimeInterval = 180) {163        XCTAssertTrue(app.buttons["category.restaurant"].waitForExistence(timeout: timeout), "the test region was not installed in time (is the dev server running? see scripts/uitest.sh)")164    }165166    // MARK: System alerts167168    /// Dismisses a system alert left on screen (for example a permission prompt), choosing the last button.169    func dismissSystemAlerts() {170        for _ in 0..<3 {171            let alert = springboard.alerts.firstMatch172            guard alert.waitForExistence(timeout: 0.5) else { return }173            alert.buttons.element(boundBy: alert.buttons.count - 1).tap()174        }175    }176177    /// Answers the position permission prompt. Buttons are, in order: once, while using the app, refuse.178    func answerLocationPrompt(allow: Bool, timeout: TimeInterval = 8) -> Bool {179        let alert = springboard.alerts.firstMatch180        guard alert.waitForExistence(timeout: timeout) else { return false }181        alert.buttons.element(boundBy: allow ? 1 : alert.buttons.count - 1).tap()182        return true183    }184185    // MARK: Elements186187    /// An element with an accessibility identifier, whatever its type.188    func element(_ id: String) -> XCUIElement { app.descendants(matching: .any).matching(identifier: id).firstMatch }189190    @discardableResult191    func require(_ element: XCUIElement, _ message: String = "", timeout: TimeInterval = 10, file: StaticString = #filePath, line: UInt = #line) -> XCUIElement {192        XCTAssertTrue(element.waitForExistence(timeout: timeout), message.isEmpty ? "missing \(element)" : message, file: file, line: line)193        return element194    }195196    func waitGone(_ element: XCUIElement, timeout: TimeInterval = 10, file: StaticString = #filePath, line: UInt = #line) {197        XCTAssertTrue(element.waitForNonExistence(timeout: timeout), "still on screen: \(element)", file: file, line: line)198    }199200    /// Any static text containing the given text.201    func text(containing fragment: String) -> XCUIElement {202        app.staticTexts.containing(NSPredicate(format: "label CONTAINS %@", fragment)).firstMatch203    }204205    /// Waits for a condition evaluated on the interface.206    func wait(_ description: String, timeout: TimeInterval = 10, file: StaticString = #filePath, line: UInt = #line, until condition: () -> Bool) {207        let deadline = Date().addingTimeInterval(timeout)208        while Date() < deadline {209            if condition() { return }210            usleep(200_000)211        }212        XCTAssertTrue(condition(), description, file: file, line: line)213    }214215    // MARK: Navigation216217    var map: XCUIElement { element("map.canvas") }218219    func closeModal() { require(app.buttons["modal.done"]).tap() }220221    /// Scrolls the frontmost list up until the element is on screen.222    @discardableResult223    func scrollTo(_ element: XCUIElement, maxSwipes: Int = 12, file: StaticString = #filePath, line: UInt = #line) -> XCUIElement {224        var swipes = 0225        while !(element.exists && element.isHittable) && swipes < maxSwipes { app.swipeUp(velocity: .slow); swipes += 1 }226        XCTAssertTrue(element.exists, "not found after scrolling: \(element)", file: file, line: line)227        return element228    }229230    /// Entries of the main menu (the "…" button next to the search field) by their symbol, which does not depend on231    /// the interface language — and "Compass" is also the name of a control of the map engine.232    enum MenuEntry: String {233        case downloads = "arrow.down.circle", collections = "bookmark", tracks = "point.topleft.down.to.point.bottomright.curvepath", explorer = "binoculars"234        case planner = "map", measure = "ruler", compass = "safari", studio = "paintpalette", settings = "gearshape", about = "info.circle"235    }236237    func openMenu(_ entry: MenuEntry, file: StaticString = #filePath, line: UInt = #line) {238        require(element("home.menu"), file: file, line: line).tap()239        let item = app.buttons[entry.rawValue]240        // At the largest text sizes the menu is taller than the screen: its first entries are reached by scrolling.241        var swipes = 0242        while !item.waitForExistence(timeout: 2), swipes < 4 { app.swipeDown(); swipes += 1 }243        require(item, "menu entry \(entry)", file: file, line: line).tap()244    }245246    /// Types in the search field and submits. A search left in the field (it is kept when a place card is closed) is cleared first.247    func search(_ text: String) {248        let field = require(app.textFields["search.field"])249        if app.buttons["search.clear"].exists { app.buttons["search.clear"].tap() }250        field.tap()251        field.typeText(text + "\n")252    }253254    /// A point of the map that is clear of the controls and the panel, as a fraction of the visible map.255    func mapPoint(dx: CGFloat = 0.45, dy: CGFloat = 0.28) -> XCUICoordinate {256        let window = app.windows.firstMatch257        // On iPad the side panel covers the left part of the window.258        let x = isPad ? 0.45 + dx * 0.5 : dx259        return window.coordinate(withNormalizedOffset: CGVector(dx: x, dy: dy))260    }261262    // MARK: Evidence263264    /// A capture for docs/screenshots: `scripts/uitest.sh --screenshots` copies it there as <device>-<language>-<appearance>-<name>.png.265    func documentationScreenshot(_ name: String) {266        let appearance = TestServer.isDark ? "dark" : "light"267        screenshot("docs-\(isPad ? "ipad" : "iphone")-\(language.code)-\(appearance)-\(name)")268    }269270    /// Keeps a screenshot with the test result; scripts/uitest.sh exports the attachments.271    func screenshot(_ name: String) {272        let capture = XCUIScreen.main.screenshot()273        // The screen is captured in the device's native (portrait) orientation: turn landscape captures upright.274        let attachment: XCTAttachment275        if XCUIDevice.shared.orientation == .landscapeLeft || XCUIDevice.shared.orientation == .landscapeRight, let cg = capture.image.cgImage {276            let turned = UIImage(cgImage: cg, scale: capture.image.scale, orientation: XCUIDevice.shared.orientation == .landscapeLeft ? .left : .right)277            let upright = UIGraphicsImageRenderer(size: turned.size).image { _ in turned.draw(in: CGRect(origin: .zero, size: turned.size)) }278            attachment = XCTAttachment(image: upright)279        } else {280            attachment = XCTAttachment(screenshot: capture)281        }282        attachment.name = name283        attachment.lifetime = .keepAlways284        add(attachment)285    }286}287
Files main
Menu

Theme