SPB Git

Repository Public

SPKeyboardUITests.swift 17.3 KB 368 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : Tests/UITests/SPKeyboardUITests.swift10// Description      : UI tests of the configuration app, run with in-memory11//                    stores (-SPInMemory 1): they never touch the real12//                    Keychain, the App Group or the network.13// Module           : UITests14// Repository       : https://git.spboucher.ai/sp-keyboard15// Created          : 2026-12-0116// Last Modified    : 2026-12-0117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import XCTest9192final class SPKeyboardUITests: XCTestCase {93    private var app: XCUIApplication!9495    override func setUp() {96        continueAfterFailure = false97        app = XCUIApplication()98    }99100    private func launch(_ screen: String, extra: [String] = []) {101        app.launchArguments = ["-SPInMemory", "1", "-SPScreen", screen] + extra102        app.launch()103    }104105    /// Scrolls the first scrollable container until `element` can be tapped.106    @discardableResult107    private func reveal(_ element: XCUIElement, maxSwipes: Int = 40) -> XCUIElement {108        var swipes = 0109        while !(element.exists && element.isHittable), swipes < maxSwipes {110            // Drag inside the upper half: whichever keyboard is up (the system one or SP Keyboard itself,111            // when it is installed on the simulator) never receives the gesture.112            let start = app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.55))113            let end = app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.12))114            start.press(forDuration: 0.05, thenDragTo: end)115            swipes += 1116        }117        XCTAssertTrue(element.exists, "\(element) not found after scrolling")118        return element119    }120121    // MARK: Home122123    func testHomeShowsVerifiableStatusGuideAndTestAreas() {124        launch("home")125        XCTAssertTrue(app.staticTexts["SP Keyboard"].waitForExistence(timeout: 15))126        XCTAssertTrue(app.staticTexts["Clé Anthropic"].exists)127        XCTAssertTrue(app.staticTexts["Dernier rapport du clavier"].exists)128        // The app never claims the keyboard is enabled: it says it cannot know.129        XCTAssertTrue(app.staticTexts.containing(NSPredicate(format: "label CONTAINS %@", "iOS n'indique pas à une app")).firstMatch.exists)130        reveal(app.buttons["home.openSettings"])131        reveal(app.textFields["home.realField"])132        reveal(app.buttons["home.clearPreview"])133        XCTAssertEqual(app.tabBars.buttons.count, 5)134    }135136    // MARK: Themes137138    func testThemeGalleryListsEighteenThemesAndActivates() {139        launch("themes")140        let atelier = app.buttons["theme.atelier-clair"]141        XCTAssertTrue(atelier.waitForExistence(timeout: 15))142        XCTAssertEqual(atelier.value as? String, "actif")143        XCTAssertEqual(app.buttons["theme.atelier-nuit"].value as? String, "actif", "the default is a light/dark pair")144        XCTAssertTrue(app.switches["themes.followsAppearance"].exists)145        app.buttons["preview.toggle"].tap() // fold the preview to see the gallery146        for id in ["craie", "ardoise", "sable", "sapin", "monochrome"] {147            reveal(app.buttons["theme.\(id)"])148        }149        let cyberpunk = reveal(app.buttons["theme.cyberpunk"])150        XCTAssertEqual(cyberpunk.value as? String, "inactif")151        cyberpunk.tap()152        XCTAssertEqual(cyberpunk.value as? String, "actif")153        for id in ["solar-flare", "ocean-pulse", "galaxy", "rainbow-prism", "candy-glass", "toxic-lime", "arctic-ice", "midnight-luxe", "lava"] {154            reveal(app.buttons["theme.\(id)"])155        }156    }157158    func testFavoritesFilterAndDuplicateOpensTheEditor() {159        launch("themes")160        XCTAssertTrue(app.buttons["theme.favorite.cyberpunk"].waitForExistence(timeout: 15))161        app.buttons["preview.toggle"].tap()162        app.buttons["theme.favorite.cyberpunk"].tap()163        app.switches["themes.favoritesOnly"].switches.firstMatch.tap()164        XCTAssertTrue(app.buttons["theme.cyberpunk"].exists)165        XCTAssertFalse(app.buttons["theme.atelier-clair"].exists)166        app.buttons["theme.edit.cyberpunk"].tap()167        XCTAssertTrue(app.textFields["editor.name"].waitForExistence(timeout: 10))168        XCTAssertEqual(app.textFields["editor.name"].value as? String, "Cyberpunk (copie)")169        XCTAssertTrue(app.descendants(matching: .any)["editor.contrast"].exists)170    }171172    func testThemeEditorEntryPoints() {173        launch("editor", extra: ["-SPTheme", "lava"])174        XCTAssertTrue(app.textFields["editor.name"].waitForExistence(timeout: 15))175        app.buttons["preview.toggle"].tap()176        reveal(app.descendants(matching: .any)["editor.photo"])177        reveal(app.buttons["editor.export"])178        reveal(app.buttons["editor.delete"])179        XCTAssertTrue(app.buttons["themes.import"].exists == false) // the import button belongs to the gallery180    }181182    // MARK: Typing Lab183184    func testTypingLabTogglesKeepTheirStateAcrossNavigation() {185        launch("typing")186        let toggle = app.switches["typing.autocorrection"]187        XCTAssertTrue(toggle.waitForExistence(timeout: 15))188        XCTAssertEqual(toggle.value as? String, "1")189        toggle.switches.firstMatch.tap()190        XCTAssertEqual(toggle.value as? String, "0")191        app.tabBars.buttons["Accueil"].tap()192        app.tabBars.buttons["Frappe"].tap()193        XCTAssertEqual(app.switches["typing.autocorrection"].value as? String, "0")194        XCTAssertTrue(app.descendants(matching: .any)["typing.add.fr-AZERTY"].waitForExistence(timeout: 5), "AZERTY is optional and offered")195        let glide = reveal(app.switches["typing.glide"])196        XCTAssertEqual(glide.value as? String, "1", "glide typing ships on in 2.0")197        XCTAssertEqual(reveal(app.switches["typing.numberRow"]).value as? String, "0")198        XCTAssertEqual(reveal(app.switches["typing.numberHints"]).value as? String, "1")199    }200201    // MARK: SP AI202203    func testSecretFieldIsMaskedValidatedAndClearedAfterSaving() {204        launch("ai")205        let secure = app.secureTextFields["ai.keyField"]206        XCTAssertTrue(secure.waitForExistence(timeout: 15), "the key field is masked by default")207        XCTAssertFalse(app.textFields["ai.keyField"].exists)208        XCTAssertTrue(app.staticTexts["Aucune clé"].exists)209        XCTAssertFalse(app.buttons["ai.saveKey"].isEnabled)210        XCTAssertFalse(app.buttons["ai.test"].isEnabled, "no connection test without a key")211212        secure.tap()213        secure.typeText("bonjour")214        app.buttons["ai.saveKey"].tap()215        let message = app.staticTexts["ai.keyMessage"]216        XCTAssertTrue(message.waitForExistence(timeout: 5))217        XCTAssertTrue(message.label.contains("Rien n'a été enregistré"))218        XCTAssertTrue(app.staticTexts["Aucune clé"].exists)219220        // Replace the draft with a well-formed (fictional) key.221        let fake = "sk-ant-api03-" + String(repeating: "Ab1_-", count: 16)222        secure.tap()223        secure.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: 10))224        secure.typeText(fake)225        app.buttons["ai.saveKey"].tap()226        XCTAssertTrue(app.staticTexts["Clé enregistrée"].waitForExistence(timeout: 5))227        // The saved key is shown masked only, and the field is emptied.228        XCTAssertFalse(app.staticTexts.containing(NSPredicate(format: "label CONTAINS %@", fake)).firstMatch.exists)229        let status = app.descendants(matching: .any)["ai.keyStatus"]230        XCTAssertTrue(status.label.contains("sk-ant-…"), status.label)231        XCTAssertFalse(status.label.contains(fake))232        XCTAssertNotEqual(app.secureTextFields["ai.keyField"].value as? String, fake)233234        // Stubbed (offline) connection test: the model list appears and the preferred model is preselected.235        app.buttons["ai.test"].tap()236        XCTAssertTrue(app.staticTexts["ai.testResult"].waitForExistence(timeout: 10))237        XCTAssertTrue(app.staticTexts["ai.testResult"].label.contains("2 modèles"))238        let picker = app.buttons["ai.model"]239        XCTAssertTrue(picker.waitForExistence(timeout: 5))240        XCTAssertTrue(picker.label.contains("Claude Opus 5.5 (simulé)"), "the preferred model returned by the API is preselected: \(picker.label)")241        // The key section scrolled away while the keyboard was up: come back to it.242        app.swipeDown(velocity: .fast)243        app.swipeDown(velocity: .fast)244        XCTAssertTrue(app.buttons["ai.eraseKey"].waitForExistence(timeout: 5))245    }246247    func testRevealShowsTheDraftOnlyOnAction() {248        launch("ai")249        let secure = app.secureTextFields["ai.keyField"]250        XCTAssertTrue(secure.waitForExistence(timeout: 15))251        secure.tap()252        secure.typeText("abc")253        app.buttons["ai.reveal"].tap()254        XCTAssertTrue(app.textFields["ai.keyField"].waitForExistence(timeout: 5))255        XCTAssertEqual(app.textFields["ai.keyField"].value as? String, "abc")256        app.buttons["ai.reveal"].tap()257        XCTAssertTrue(app.secureTextFields["ai.keyField"].waitForExistence(timeout: 5))258    }259260    // MARK: Dictionary, import / export261262    func testDictionaryWordsAndImportExportEntryPoints() {263        launch("dictionary")264        let field = app.textFields["dictionary.newWord"]265        XCTAssertTrue(field.waitForExistence(timeout: 15))266        field.tap()267        field.typeText("Saguenay")268        app.buttons["dictionary.addWord"].tap()269        XCTAssertTrue(app.staticTexts["Saguenay"].waitForExistence(timeout: 5))270        XCTAssertTrue(app.staticTexts["Mes mots (1)"].exists || app.staticTexts["MES MOTS (1)"].exists)271        if app.keyboards.firstMatch.exists { app.swipeDown(velocity: .fast) }272        reveal(app.buttons["dictionary.export"])273        reveal(app.buttons["dictionary.import"])274        app.buttons["dictionary.export"].tap()275        // The system file exporter appears (sheet with a navigation bar).276        XCTAssertTrue(app.navigationBars.element(boundBy: 1).waitForExistence(timeout: 10) || app.buttons["Enregistrer"].waitForExistence(timeout: 5)277            || app.buttons["Déplacer"].waitForExistence(timeout: 2) || app.buttons["Save"].waitForExistence(timeout: 2))278    }279280    func testThemeImportEntryPoint() {281        launch("themes")282        XCTAssertTrue(app.buttons["themes.import"].waitForExistence(timeout: 15))283        XCTAssertTrue(app.buttons["themes.import"].isHittable)284    }285286    // MARK: Privacy and diagnostics287288    func testPrivacyEraseAsksForConfirmation() {289        launch("privacy")290        let erase = reveal(app.buttons["privacy.erase.everything"])291        erase.tap()292        let confirm = app.buttons["Effacer"]293        XCTAssertTrue(confirm.waitForExistence(timeout: 5), "erasing requires a confirmation")294        confirm.tap()295        XCTAssertTrue(app.staticTexts["privacy.done"].waitForExistence(timeout: 5))296        reveal(app.staticTexts.containing(NSPredicate(format: "label CONTAINS %@", "CC BY-SA 4.0")).firstMatch)297    }298299    func testDiagnosticsRunsTheKeychainProbe() {300        launch("diagnostics")301        XCTAssertTrue(app.staticTexts["Version"].waitForExistence(timeout: 15))302        let probe = reveal(app.buttons["diag.keychainProbe"])303        probe.tap()304        let result = app.descendants(matching: .any)["diag.keychain"]305        XCTAssertTrue(result.waitForExistence(timeout: 5))306        let shown = [result.label, result.value as? String ?? ""].joined(separator: " ")307            + app.staticTexts.matching(NSPredicate(format: "label == %@", "accessible")).count.description308        XCTAssertTrue(shown.contains("accessible") || app.staticTexts.matching(NSPredicate(format: "label == %@", "accessible")).count >= 2, shown)309        XCTAssertFalse(app.staticTexts["non vérifié"].exists)310        reveal(app.staticTexts["diag.noReport"])311    }312313    // MARK: Embedded keyboard314315    func testTypingOnTheEmbeddedPreviewKeyboard() {316        launch("home")317        XCTAssertTrue(app.staticTexts["SP Keyboard"].waitForExistence(timeout: 15))318        let text = app.descendants(matching: .any)["preview.text"]319        reveal(app.buttons["home.clearPreview"])320        XCTAssertTrue(text.exists)321        // Automatic capitalisation: the first key is shown and typed in upper case, then lower case.322        func key(_ label: String) -> XCUIElement {323            let element = app.keys[label]324            XCTAssertTrue(element.waitForExistence(timeout: 5), "key \(label) not found")325            return element326        }327        key("B").tap()328        key("o").tap()329        key("n").tap()330        XCTAssertEqual(text.value as? String, "Bon")331        key("Espace").tap()332        key("a").tap()333        key("Effacer").tap()334        XCTAssertEqual(text.value as? String, "Bon ")335        key("Chiffres").tap()336        key("7").tap()337        XCTAssertEqual(text.value as? String, "Bon 7")338        app.buttons["home.clearPreview"].tap()339        XCTAssertEqual(text.value as? String, "")340    }341342    // MARK: Accessibility343344    @MainActor345    func testAccessibilityAuditOnMainScreens() throws {346        var issues: [String] = []347        for screen in ["home", "themes", "ai", "typing", "dictionary", "diagnostics", "privacy", "help"] {348            launch(screen)349            XCTAssertTrue(app.tabBars.firstMatch.waitForExistence(timeout: 15))350            // Audited: element descriptions, element detection, traits and hit regions. The contrast, Dynamic Type351            // and clipped-text audits are not asserted: on this OS they flag system list headers, footers and352            // rows lying under the translucent tab bar (see the test report for the findings of a full run).353            try app.performAccessibilityAudit(for: [.sufficientElementDescription, .elementDetection, .trait, .hitRegion]) { issue in354                guard let element = issue.element else {355                    issues.append("[\(screen)] \(issue.compactDescription) — no element")356                    return true357                }358                // Key caps of the embedded keyboard are sized like the system keyboard's; static text is not a control.359                if element.elementType == .key || element.elementType == .staticText { return true }360                issues.append("[\(screen)] \(issue.compactDescription) — \(element.debugDescription.prefix(160))")361                return true362            }363            app.terminate()364        }365        XCTAssertTrue(issues.isEmpty, "\n" + issues.joined(separator: "\n"))366    }367}368
Files main
Menu

Theme