SPB Git

Repository Public

ExtensionSmokeTests.swift 17.5 KB 366 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : Tests/UITests/ExtensionSmokeTests.swift10// Description      : End-to-end check of the real keyboard extension in the11//                    simulator: adds SP Keyboard in Settings the way a user12//                    does, switches to it in a system text field (Spotlight),13//                    types and reads the text back. Slow and dependent on the14//                    system UI: run on demand (SPK_EXTENSION_SMOKE=1), not in15//                    the default suite.16// Module           : UITests17// Repository       : https://git.spboucher.ai/sp-keyboard18// Created          : 2026-12-0119// Last Modified    : 2026-12-0120//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import XCTest9495@MainActor96final class ExtensionSmokeTests: XCTestCase {97    private let settings = XCUIApplication(bundleIdentifier: "com.apple.Preferences")98    private let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard")99100    override func setUp() async throws {101        continueAfterFailure = false102        guard ProcessInfo.processInfo.environment["SPK_EXTENSION_SMOKE"] == "1" else { throw XCTSkip("set SPK_EXTENSION_SMOKE=1 to run") }103    }104105    private func attach(_ name: String) {106        let shot = XCTAttachment(screenshot: XCUIScreen.main.screenshot())107        shot.name = name108        shot.lifetime = .keepAlways109        add(shot)110    }111112    /// Taps the first hittable row or button whose label starts with one of `labels` (never a navigation title).113    private func tap(_ app: XCUIApplication, anyOf labels: [String], timeout: TimeInterval = 8) -> Bool {114        let deadline = Date().addingTimeInterval(timeout)115        repeat {116            for label in labels {117                let predicate = NSPredicate(format: "label BEGINSWITH %@", label)118                for query in [app.cells, app.collectionViews.buttons, app.tables.buttons, app.collectionViews.staticTexts, app.tables.staticTexts] {119                    let element = query.matching(predicate).firstMatch120                    if element.exists && element.isHittable {121                        element.tap()122                        return true123                    }124                }125            }126            usleep(300_000)127        } while Date() < deadline128        return false129    }130131    func test01_AddKeyboardInSettings() throws {132        XCUIApplication().launch() // installs the containing app133        settings.terminate()134        settings.launch()135        XCTAssertTrue(tap(settings, anyOf: ["General", "Général"]), "General not found")136        XCTAssertTrue(tap(settings, anyOf: ["Keyboard", "Clavier"]), "Keyboard not found")137        XCTAssertTrue(tap(settings, anyOf: ["Keyboards", "Claviers"]), "Keyboards not found")138        if settings.cells.containing(NSPredicate(format: "label CONTAINS 'SP Keyboard'")).firstMatch.waitForExistence(timeout: 2) {139            attach("already-added")140            return141        }142        XCTAssertTrue(tap(settings, anyOf: ["Add New Keyboard", "Ajouter un clavier"]), "Add New Keyboard not found: \(settings.debugDescription.suffix(1800))")143        let entry = settings.cells.containing(NSPredicate(format: "label CONTAINS 'SP Keyboard'")).firstMatch144        XCTAssertTrue(entry.waitForExistence(timeout: 8), "SP Keyboard is not offered by the system: \(settings.debugDescription.prefix(1500))")145        entry.tap()146        XCTAssertTrue(settings.cells.containing(NSPredicate(format: "label CONTAINS 'SP Keyboard'")).firstMatch.waitForExistence(timeout: 8))147        attach("keyboard-added")148    }149150    func test02_SwitchToSPKeyboardInASystemField() throws {151        settings.terminate()152        settings.launch()153        let field = settings.searchFields.firstMatch154        XCTAssertTrue(field.waitForExistence(timeout: 8), "search field not found: \(settings.debugDescription.suffix(1500))")155        field.tap()156        sleep(1)157        attach("system-keyboard")158        let globeQuery = settings.buttons.matching(NSPredicate(format: "label IN %@", ["Next keyboard", "Clavier suivant"]))159        XCTAssertTrue(globeQuery.firstMatch.waitForExistence(timeout: 5), "globe key not found")160        var found = false161        for attempt in 0..<5 {162            globeQuery.firstMatch.tap()163            sleep(1)164            // First use: iOS explains the globe key.165            let tip = settings.buttons.matching(NSPredicate(format: "label IN %@", ["Continue", "Continuer"])).firstMatch166            if tip.exists { tip.tap(); sleep(1) }167            if settings.buttons["SP AI"].waitForExistence(timeout: 2) || settings.otherElements["SP AI"].exists {168                found = true169                print("SPK: SP Keyboard visible after \(attempt + 1) globe tap(s)")170                break171            }172            // A tap only alternates between the two most recent keyboards: pick ours in the globe menu.173            if pickSPKeyboardInGlobeMenu() {174                found = true175                print("SPK: SP Keyboard picked in the globe menu")176                break177            }178        }179        attach("after-globe")180        print("SPK-TREE-BEGIN\n\(settings.debugDescription)\nSPK-TREE-END")181        XCTAssertTrue(found, "SP Keyboard did not come up")182        for letter in ["B", "o", "n", "j", "o", "u", "r"] {183            let key = settings.keys[letter].firstMatch184            XCTAssertTrue(key.waitForExistence(timeout: 3), "key \(letter) not found")185            key.tap()186        }187        settings.keys["Espace"].firstMatch.tap()188        sleep(1)189        attach("typed")190        XCTAssertEqual(field.value as? String, "Bonjour ")191    }192193    /// Focuses the Settings search field and cycles to SP Keyboard. Returns the field.194    private func bringUpSPKeyboard() throws -> XCUIElement {195        settings.terminate()196        settings.launch()197        let field = settings.searchFields.firstMatch198        XCTAssertTrue(field.waitForExistence(timeout: 8))199        field.tap()200        sleep(1)201        if settings.buttons["SP AI"].waitForExistence(timeout: 2) { return field }202        let globeQuery = settings.buttons.matching(NSPredicate(format: "label IN %@", ["Next keyboard", "Clavier suivant"]))203        for _ in 0..<5 {204            guard globeQuery.firstMatch.waitForExistence(timeout: 3) else { break }205            if pickSPKeyboardInGlobeMenu() { return field }206            globeQuery.firstMatch.tap()207            sleep(1)208            if settings.buttons["SP AI"].waitForExistence(timeout: 2) { return field }209        }210        XCTFail("SP Keyboard did not come up")211        return field212    }213214    /// Long-presses the system globe key and chooses SP Keyboard in the menu. A plain tap on the globe only215    /// alternates between the two most recently used keyboards, so a freshly added one is never reached that way.216    private func pickSPKeyboardInGlobeMenu() -> Bool {217        let globe = settings.buttons.matching(NSPredicate(format: "label IN %@", ["Next keyboard", "Clavier suivant"])).firstMatch218        guard globe.waitForExistence(timeout: 3) else { return false }219        globe.press(forDuration: 1.2)220        let entry = settings.descendants(matching: .any).matching(NSPredicate(format: "label CONTAINS 'SP Keyboard'")).firstMatch221        guard entry.waitForExistence(timeout: 3) else {222            attach("globe-menu-without-sp-keyboard")223            // Dismiss whatever the long press opened.224            settings.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.2)).tap()225            return false226        }227        entry.tap()228        sleep(1)229        return settings.buttons["SP AI"].waitForExistence(timeout: 6)230    }231232    private func type(_ keys: [String]) {233        for label in keys {234            let key = settings.keys[label].firstMatch235            XCTAssertTrue(key.waitForExistence(timeout: 3), "key \(label) not found")236            key.tap()237        }238    }239240    func test03_EditingKeysAndPages() throws {241        let field = try bringUpSPKeyboard()242        type(["S", "a", "l", "u", "t"])243        XCTAssertEqual(field.value as? String, "Salut")244        type(["Effacer", "Effacer"])245        XCTAssertEqual(field.value as? String, "Sal")246        type(["Majuscule", "U"])247        XCTAssertEqual(field.value as? String, "SalU")248        type(["Chiffres", "4", "2"])249        XCTAssertEqual(field.value as? String, "SalU42")250        type(["Symboles", "%", "Lettres", "x"])251        XCTAssertEqual(field.value as? String, "SalU42%x")252        attach("editing")253    }254255    func test04_AIPanelExplainsMissingFullAccess() throws {256        let field = try bringUpSPKeyboard()257        type(["O", "k"])258        settings.buttons["SP AI"].tap()259        // Full Access is off by default: SP AI must explain why it is unavailable, and typing must still work.260        let explanation = settings.staticTexts.matching(NSPredicate(format: "label CONTAINS[c] 'accès complet'")).firstMatch261        XCTAssertTrue(explanation.waitForExistence(timeout: 4), "no explanation shown: \(settings.debugDescription.suffix(1200))")262        attach("ai-no-full-access")263        if ProcessInfo.processInfo.environment["SPK_LEAVE_OPEN"] == "1" { return }264        settings.buttons["ai.back"].firstMatch.tap()265        type(["a", "y"])266        XCTAssertEqual(field.value as? String, "Okay")267    }268269    func test05_EmojiPanel() throws {270        let field = try bringUpSPKeyboard()271        settings.buttons["Outils"].tap()272        settings.buttons["tool.emoji"].tap()273        let heart = settings.keys["❤️"].firstMatch274        XCTAssertTrue(heart.waitForExistence(timeout: 4), "favourite emoji not found: \(settings.debugDescription.suffix(1200))")275        heart.tap()276        XCTAssertEqual(field.value as? String, "❤️")277        attach("emoji")278        if ProcessInfo.processInfo.environment["SPK_LEAVE_OPEN"] == "1" { return }279        settings.buttons["Retour aux lettres"].firstMatch.tap()280        sleep(1)281        // Regression: this field reports no context once it holds an emoji; letters must not turn into capitals.282        type(["o", "k"])283        XCTAssertEqual(field.value as? String, "❤️ok")284    }285286    /// The Settings search screen does not rotate in the simulator, so this only proves that an orientation287    /// change request does not break the extension. Landscape layout is covered by the app's preview tests.288    func test06_OrientationChangeDoesNotBreakTyping() throws {289        let field = try bringUpSPKeyboard()290        type(["A"])291        XCUIDevice.shared.orientation = .landscapeLeft292        sleep(2)293        type(["b"])294        attach("landscape")295        if ProcessInfo.processInfo.environment["SPK_LEAVE_OPEN"] == "1" { XCTAssertEqual(field.value as? String, "Ab"); return }296        XCUIDevice.shared.orientation = .portrait297        sleep(2)298        type(["c"])299        XCTAssertEqual(field.value as? String, "Abc")300    }301302    /// Turns on "Allow Full Access" for SP Keyboard in Settings, as the owner would.303    func test07_EnableFullAccess() throws {304        settings.terminate()305        settings.launch()306        XCTAssertTrue(tap(settings, anyOf: ["General", "Général"]))307        XCTAssertTrue(tap(settings, anyOf: ["Keyboard", "Clavier"]))308        XCTAssertTrue(tap(settings, anyOf: ["Keyboards", "Claviers"]))309        XCTAssertTrue(tap(settings, anyOf: ["SP Keyboard"]), "SP Keyboard row not found")310        let toggle = settings.switches.matching(NSPredicate(format: "label CONTAINS[c] 'Full Access' OR label CONTAINS[c] 'accès complet'")).firstMatch311        XCTAssertTrue(toggle.waitForExistence(timeout: 6), "full access switch not found: \(settings.debugDescription.suffix(1500))")312        if (toggle.value as? String) != "1" {313            toggle.switches.firstMatch.exists ? toggle.switches.firstMatch.tap() : toggle.tap()314            let allow = settings.alerts.buttons.matching(NSPredicate(format: "label IN %@", ["Allow", "Autoriser"])).firstMatch315            if allow.waitForExistence(timeout: 4) { allow.tap() }316            sleep(1)317        }318        attach("full-access")319        XCTAssertEqual(settings.switches.matching(NSPredicate(format: "label CONTAINS[c] 'Full Access' OR label CONTAINS[c] 'accès complet'")).firstMatch.value as? String, "1")320    }321322    /// Billable (a fraction of a cent): needs Full Access (test07), a key in the shared Keychain and a chosen323    /// model in the shared settings. Sends one fictional sentence and replaces it with Claude's correction.324    func test08_SPAIReplacesTextInHostField() throws {325        guard ProcessInfo.processInfo.environment["SPK_LIVE_AI"] == "1" else { throw XCTSkip("set SPK_LIVE_AI=1 to run") }326        let field = try bringUpSPKeyboard()327        type(["J", "e", "Espace", "v", "o", "u", "d", "r", "a", "i", "t", "Espace", "v", "e", "n", "i", "r"])328        settings.buttons["SP AI"].tap()329        let send = settings.buttons["ai.send"].firstMatch330        XCTAssertTrue(send.waitForExistence(timeout: 5), "source preview not shown: \(settings.debugDescription.suffix(1500))")331        attach("ai-source")332        send.tap()333        let replace = settings.buttons["ai.replace"].firstMatch334        XCTAssertTrue(replace.waitForExistence(timeout: 40), "no result: \(settings.debugDescription.suffix(1500))")335        attach("ai-result")336        XCTAssertTrue(replace.isEnabled, "replace should be offered: the field did not change")337        replace.tap()338        sleep(1)339        attach("ai-applied")340        let value = field.value as? String ?? ""341        print("SPK: field after SP AI replace = \(value)")342        XCTAssertTrue(value.contains("voudrais"), value)343        XCTAssertFalse(value.contains("voudrait"), value)344    }345346    /// Types enough keys for the extension to report its key-handling latency (read by the Diagnostics screen),347    /// dismisses and re-shows the keyboard so that a warm appearance is measured too.348    func test09_TypingBurstForMetrics() throws {349        let field = try bringUpSPKeyboard()350        let letters = ["b", "o", "n", "j", "o", "u", "r", "Espace", "l", "e", "Espace", "m", "o", "n", "d", "e", "Espace"]351        type(["B"] + Array(letters.dropFirst()))352        for _ in 0..<3 { type(letters) }353        XCTAssertEqual((field.value as? String)?.count, 68)354        // Leave and come back without quitting the host: the extension process stays alive, so the next355        // appearance is a warm one.356        XCUIDevice.shared.press(.home)357        sleep(2)358        settings.activate()359        sleep(1)360        if !settings.buttons["SP AI"].waitForExistence(timeout: 3) { field.tap() }361        XCTAssertTrue(settings.buttons["SP AI"].waitForExistence(timeout: 5))362        sleep(1)363        type(["Effacer"])364    }365}366
Files main
Menu

Theme