SPB Git

Repository Public

JourneyTests.swift 15.6 KB 377 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Vault9// File             : apple/Tests/UITests/JourneyTests.swift10// Module           : UITests11// Repository       : https://git.spboucher.ai/sp-vault12// Project Website  : https://vault.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: support@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// =============================================================================8788// End-to-end journeys of the Dev variant against the real local server. The same file runs on macOS and on the89// simulators; Scripts/ui-tests.sh prepares the invitations and orchestrates the cross-device pairing.90// Tests are numbered because they build on each other within one platform run (same profile, same account).91import XCTest9293@MainActor94final class JourneyTests: VaultUITestCase {95    private var me: String { UI.platform }96    private let password = "correct-horse-ZQ9-battery"97    private let title = "Example Bank"9899    // ── 01: join with an invitation → recovery kit → verification → main; item life cycle ──100    func test01_JoinAndItemLifecycle() throws {101        launch(profile: "\(me)-main", account: me, reset: true)102        let account = try join(shotName: me == "iphone" ? "iphone-recovery-kit" : nil)103        UI.write("account-\(me).txt", "\(account.handle)\n\(account.key)\n")104105        // create a login with a one-time code106        createLogin(title: title, user: "ada@example.com", password: password, totp: "JBSWY3DPEHPK3PXP", url: "bank.example.com")107        need("item-detail")108        XCTAssertEqual(need("detail-title").label, title)109        XCTAssertTrue(need("totp-code").exists, "live one-time code is shown")110        // masked by default, revealed on demand111        XCTAssertNotEqual(value("field-password-value"), password)112        tap("field-password-reveal")113        XCTAssertEqual(value("field-password-value"), password)114        tap("field-password-reveal")115        // copy116        tap("field-password-copy")117        XCTAssertTrue(need("toast").label.contains("copied"), "toast says: \(el("toast").label)")118        #if os(macOS)119        XCTAssertEqual(NSPasteboard.general.string(forType: .string), password)120        XCTAssertNotNil(NSPasteboard.general.types?.first { $0.rawValue == "org.nspasteboard.ConcealedType" }, "copied secret is marked concealed")121        #endif122        shot(me == "mac" ? "mac-item-detail" : "\(me)-detail")123124        // edit: add a note125        tap("detail-edit")126        need("item-editor")127        type("editor-notes", "note-zq9")128        tap("editor-save")129        gone("item-editor")130        XCTAssertTrue(app.staticTexts["note-zq9"].waitForExistence(timeout: 10))131132        // favorite133        tap("detail-favorite")134        XCTAssertTrue(app.descendants(matching: .any).matching(NSPredicate(format: "label == %@", "Remove from favorites")).firstMatch.waitForExistence(timeout: 10))135136        // a second item, then search137        backToList()138        createLogin(title: "Pocket Mail", user: "mob@example.com", password: "m0bile-Only-pass!word-9", url: "mail.example.com")139        backToList()140        search("pocket")141        XCTAssertTrue(need("item-row-Pocket Mail").exists)142        XCTAssertFalse(el("item-row-\(title)").exists, "search filters the list")143        clearSearch()144        shot(me == "mac" ? "mac-main" : "\(me)-list")145146        // trash and restore147        tap("item-row-Pocket Mail")148        tap("detail-trash")149        backToList()150        gone("item-row-Pocket Mail")151        showTrash()152        tap("item-row-Pocket Mail")153        tap("detail-restore")154        showAllItems()155        need("item-row-Pocket Mail")156157        // lock / unlock (offline-capable path: device key, no passkey)158        lock()159        if me == "iphone" { shot("iphone-locked") }160        unlock()161        need("item-row-\(title)")162163        // generator164        openSection("section-generator", phoneTab: "Generator")165        need("generator-page")166        tap("generator-copy")167        #if os(macOS)168        let first = NSPasteboard.general.string(forType: .string) ?? ""169        XCTAssertEqual(first.count, 24)170        tap("generator-regenerate")171        tap("generator-copy")172        XCTAssertNotEqual(NSPasteboard.general.string(forType: .string), first)173        #else174        tap("generator-regenerate")175        #endif176    }177178    // ── 02: import a CSV, Security Center findings ──179    func test02_ImportAndSecurityCenter() throws {180        launch(profile: "\(me)-main", account: me)181        unlock()182        openSection("section-settings", phoneTab: "Settings", phoneRow: "section-settings")183        need("settings-page")184        tap("import-choose") // SPV_DEV_IMPORT_FILE: the Dev build reads the prepared file instead of showing the picker185        XCTAssertTrue(need("import-preview").label.contains("4 items"))186        tap("import-run")187        need("import-done", 60)188        openSection("section-security-center", phoneTab: "Security")189        need("security-score", 20)190        need("security-finding-weak")191        need("security-finding-reused")192        need("security-finding-insecure-url")193        shot("\(me)-security")194        showAllItems()195        need("item-row-Imported Shop")196    }197198    // ── 03: recovery with the recovery key on a fresh install ──199    func test03_RecoverOnFreshInstall() throws {200        let saved = try XCTUnwrap(UI.read("account-\(me).txt")).split(separator: "\n").map(String.init)201        launch(profile: "\(me)-fresh", account: "none-\(me)", reset: true)202        need("welcome", 40)203        tap("welcome-recover")204        type("recover-handle", saved[0])205        // a damaged key is refused locally, before any request206        type("recover-key", String(saved[1].dropLast(1)) + (saved[1].hasSuffix("0") ? "1" : "0"))207        need("recover-checksum-bad")208        clearField("recover-key", count: saved[1].count + 2)209        type("recover-key", saved[1])210        need("recover-checksum-ok")211        tap("recover-submit")212        need("main", 40)213        need("item-row-\(title)", 30)214    }215216    // ── 04 (iPad): screenshot of the split layout ──217    func test04_SplitLayoutScreenshot() throws {218        #if os(iOS)219        XCUIDevice.shared.orientation = .landscapeLeft220        #endif221        launch(profile: "\(me)-main", account: me, reset: true)222        try join()223        createLogin(title: title, user: "ada@example.com", password: password, totp: "JBSWY3DPEHPK3PXP", url: "bank.example.com")224        createLogin(title: "Pocket Mail", user: "mob@example.com", password: "m0bile-Only-pass!word-9", url: "mail.example.com")225        tap("item-row-\(title)")226        need("item-detail")227        shot("\(me)-split")228    }229230    // ── 05 (macOS): light / dark main window and the menu bar extra ──231    func test05_AppearanceAndMenuBar() throws {232        #if os(macOS)233        for mode in ["dark", "light"] {234            launch(profile: "mac-main", account: "mac", appearance: mode)235            unlock()236            tap("item-row-\(title)")237            need("item-detail")238            shot("mac-main-\(mode)")239            app.terminate()240        }241        launch(profile: "mac-main", account: "mac", appearance: "dark")242        unlock()243        let status = app.menuBars.statusItems.firstMatch244        XCTAssertTrue(status.waitForExistence(timeout: 10))245        status.click()246        need("menubar-search")247        el("menubar-search").typeText("example")248        XCTAssertTrue(app.staticTexts[title].waitForExistence(timeout: 10))249        shot("mac-menubar", element: el("menubar"))250        tap("menubar-lock")251        need("menubar-unlock")252        tap("menubar-unlock")253        need("menubar-search", 20)254        #else255        throw XCTSkip("macOS only")256        #endif257    }258259    // ── pairing, trusted side (this device approves the other one, then both sync) ──260    func test10_ApproveNewDeviceAndSync() throws {261        launch(profile: "\(me)-main", account: me)262        unlock()263        let lines = try XCTUnwrap(UI.waitForFile("pairing.txt", timeout: 240), "the new device never showed a pairing code").split(separator: "\n").map(String.init)264        openSection("section-devices", phoneTab: "Settings", phoneRow: "section-devices")265        tap("devices-add")266        type("devices-code", lines[0])267        tap("devices-inspect")268        XCTAssertEqual(value("devices-sas").filter(\.isNumber), lines[1], "the 6-digit fingerprint must be the one the new device shows")269        shot("\(me)-pairing-approve")270        tap("devices-approve")271        need("devices-approved", 40)272        tap("devices-done")273        UI.write("paired.txt", "ok\n")274        // sync both ways275        showAllItems()276        need("item-row-From New Device", 120)277        createLogin(title: "From Trusted Device", user: "sync@example.com", password: "sync-both-ways-1")278        UI.write("trusted-wrote.txt", "ok\n")279    }280281    // ── pairing, new-device side (signs in with the account's passkey, shows the code, waits for approval) ──282    func test11_PairAsNewDeviceAndSync() throws {283        let trusted = UI.env["SPV_UI_PAIR_WITH"] ?? "mac"284        try? FileManager.default.removeItem(at: UI.dir.appendingPathComponent("pairing.txt"))285        launch(profile: "\(me)-paired", account: trusted, reset: true, extra: ["SPV_DEV_PAIRING_FILE": UI.dir.appendingPathComponent("pairing.txt").path])286        need("welcome", 40)287        tap("welcome-signin")288        need("pairing", 30)289        let sas = value("pairing-sas").filter(\.isNumber)290        let lines = try XCTUnwrap(UI.waitForFile("pairing.txt", timeout: 20)).split(separator: "\n").map(String.init)291        XCTAssertEqual(sas, lines[1])292        shot("\(me)-pairing")293        need("main", 300)294        need("item-row-\(title)", 60) // the trusted device's items arrived295        createLogin(title: "From New Device", user: "new@example.com", password: "new-device-pass-1")296        _ = UI.waitForFile("trusted-wrote.txt", timeout: 240)297        backToList()298        need("item-row-From Trusted Device", 120)299    }300301    // ── helpers ──302    private func backToList() {303        #if os(iOS)304        if UI.platform == "iphone" {305            for _ in 0..<3 where el("item-detail").exists {306                let named = app.navigationBars.buttons["BackButton"]307                let back = named.exists ? named : app.navigationBars.buttons.element(boundBy: 0)308                if back.exists { back.tap() } else { app.tabBars.buttons["Items"].firstMatch.tap() }309                Thread.sleep(forTimeInterval: 1)310            }311        }312        #endif313    }314315    private func search(_ text: String) {316        #if os(macOS)317        app.typeKey("f", modifierFlags: .command)318        app.typeText(text)319        #else320        if UI.platform == "iphone" { app.tabBars.buttons["Search"].firstMatch.tap() }321        let field = app.searchFields.firstMatch322        XCTAssertTrue(field.waitForExistence(timeout: 10))323        field.tap()324        _ = app.keyboards.firstMatch.waitForExistence(timeout: 5)325        Thread.sleep(forTimeInterval: 1) // the search activation animation resets the field once326        field.typeText(text)327        if ((field.value as? String) ?? "").lowercased().contains(text) == false {328            // fall back to the on-screen keys329            for ch in text { let k = app.keyboards.keys[String(ch)]; if k.exists { k.tap() } }330        }331        #endif332    }333334    private func clearSearch() {335        #if os(macOS)336        app.typeKey("a", modifierFlags: .command)337        app.typeKey(.delete, modifierFlags: [])338        app.typeKey(.escape, modifierFlags: [])339        #else340        let field = app.searchFields.firstMatch341        field.typeText("\n") // dismisses the keyboard, which covers the tab bar342        if UI.platform == "iphone" { app.tabBars.buttons["Items"].firstMatch.tap() }343        #endif344    }345346    private func clearField(_ id: String, count: Int) {347        #if os(macOS)348        clear(id)349        #else350        tap(id)351        el(id).typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: count))352        #endif353    }354355    private func showTrash() {356        #if os(macOS)357        tap("section-trash")358        #else359        if UI.platform == "ipad" { tap("section-trash"); return }360        tap("section-menu")361        app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", "Trash")).firstMatch.tap()362        #endif363    }364365    private func showAllItems() {366        #if os(macOS)367        tap("section-all-items")368        #else369        if UI.platform == "ipad" { tap("section-all-items"); return }370        app.tabBars.buttons["Items"].firstMatch.tap()371        if el("item-detail").exists { backToList() }372        tap("section-menu")373        app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", "All Items")).firstMatch.tap()374        #endif375    }376}377
Files main
Menu

Theme