SPB Git

Repository Public

Support.swift 9.5 KB 222 lines swift

1// UI-test support: launches "SP Vault Dev" (SPV_DEV) against the real local server (Scripts/dev-server.sh) with a2// named profile, and reads / writes the small files the scenarios share (invitations, recovery key, pairing code).3// Environment of the test runner (xcodebuild passes TEST_RUNNER_<NAME> as <NAME>):4//   SPV_UI_DIR      host directory shared by the runs (invites.txt, passkeys-*.json, account-*.txt, pairing.txt, import.csv)5//   SPV_UI_SHOTS    host directory where screenshots are written (apple/docs/screenshots)6import XCTest78enum UI {9    static let env = ProcessInfo.processInfo.environment10    static var dir: URL { URL(fileURLWithPath: env["SPV_UI_DIR"] ?? "/tmp/spvault-ui") }11    static var shots: URL? { env["SPV_UI_SHOTS"].map { URL(fileURLWithPath: $0) } }12    #if os(macOS)13    static let platform = "mac"14    #else15    @MainActor static var platform: String { UIDevice.current.userInterfaceIdiom == .pad ? "ipad" : "iphone" }16    #endif1718    /// Takes the next unused invitation of `invites.txt` (one token per line, prepared by Scripts/ui-tests.sh).19    static func nextInvite() throws -> String {20        let file = dir.appendingPathComponent("invites.txt")21        var lines = try String(contentsOf: file, encoding: .utf8).split(separator: "\n").map(String.init)22        guard !lines.isEmpty else { throw XCTSkip("no invitation left in \(file.path)") }23        let token = lines.removeFirst()24        try lines.joined(separator: "\n").write(to: file, atomically: true, encoding: .utf8)25        return token26    }2728    static func write(_ name: String, _ text: String) { try? text.write(to: dir.appendingPathComponent(name), atomically: true, encoding: .utf8) }29    static func read(_ name: String) -> String? { try? String(contentsOf: dir.appendingPathComponent(name), encoding: .utf8) }3031    /// Waits for a file another process writes (the pairing code of the other "device").32    static func waitForFile(_ name: String, timeout: TimeInterval) -> String? {33        let end = Date().addingTimeInterval(timeout)34        while Date() < end {35            if let s = read(name), !s.isEmpty { return s }36            Thread.sleep(forTimeInterval: 1)37        }38        return nil39    }40}4142@MainActor43class VaultUITestCase: XCTestCase {44    var app: XCUIApplication!4546    override func setUp() async throws {47        continueAfterFailure = false48    }4950    override func tearDown() async throws {51        // a picture of where a failed journey stopped (build/ui-failures, never in docs/)52        if let run = testRun, run.failureCount > 0, app != nil {53            let dir = UI.dir.appendingPathComponent("failures")54            try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)55            #if os(macOS)56            let image = app.windows.firstMatch.exists ? app.windows.firstMatch.screenshot() : nil57            #else58            let image: XCUIScreenshot? = XCUIScreen.main.screenshot()59            #endif60            let base = "\(UI.platform)-\(name.filter { $0.isLetter || $0.isNumber || $0 == "_" })"61            try? image?.pngRepresentation.write(to: dir.appendingPathComponent("\(base).png"))62            try? app.debugDescription.write(to: dir.appendingPathComponent("\(base).txt"), atomically: true, encoding: .utf8)63        }64        app?.terminate()65    }6667    /// Launches the Dev app. `account` names the software passkey file (one per account), `profile` the local "device".68    func launch(profile: String, account: String, reset: Bool = false, appearance: String? = nil, extra: [String: String] = [:]) {69        let a = XCUIApplication()70        var e: [String: String] = [71            "SPV_DEV_SERVER": UI.env["SPV_UI_SERVER"] ?? "http://localhost:8781",72            "SPV_DEV_PROFILE": profile,73            "SPV_DEV_PASSKEY_FILE": UI.dir.appendingPathComponent("passkeys-\(account).json").path,74            "SPV_DEV_ALLOW_CAPTURE": "1",75            "SPV_DEV_IMPORT_FILE": UI.dir.appendingPathComponent("import.csv").path,76        ]77        if reset { e["SPV_DEV_RESET"] = "1" }78        if let appearance { e["SPV_DEV_APPEARANCE"] = appearance }79        for (k, v) in extra { e[k] = v }80        a.launchEnvironment = e81        a.launch()82        app = a83    }8485    /// The element with this identifier; a button is preferred (list rows expose the identifier on several elements).86    func el(_ id: String) -> XCUIElement {87        let button = app.buttons.matching(identifier: id).firstMatch88        return button.exists ? button : app.descendants(matching: .any).matching(identifier: id).firstMatch89    }9091    @discardableResult92    func need(_ id: String, _ timeout: TimeInterval = 20, file: StaticString = #filePath, line: UInt = #line) -> XCUIElement {93        let e = el(id)94        XCTAssertTrue(e.waitForExistence(timeout: timeout), "element \(id) did not appear", file: file, line: line)95        return e96    }9798    func tap(_ id: String, _ timeout: TimeInterval = 20, file: StaticString = #filePath, line: UInt = #line) {99        let e = need(id, timeout, file: file, line: line)100        #if os(macOS)101        e.click()102        #else103        e.tap()104        #endif105    }106107    func type(_ id: String, _ text: String, file: StaticString = #filePath, line: UInt = #line) {108        tap(id, file: file, line: line)109        el(id).typeText(text)110    }111112    func gone(_ id: String, _ timeout: TimeInterval = 15, file: StaticString = #filePath, line: UInt = #line) {113        let e = el(id)114        let p = NSPredicate(format: "exists == false")115        let x = XCTNSPredicateExpectation(predicate: p, object: e)116        XCTAssertEqual(XCTWaiter().wait(for: [x], timeout: timeout), .completed, "element \(id) is still there", file: file, line: line)117    }118119    /// Writes a screenshot of the app window (macOS) or of the screen (simulator) into the screenshots directory.120    func shot(_ name: String, element: XCUIElement? = nil) {121        guard let dir = UI.shots else { return }122        try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)123        #if os(macOS)124        let image = (element ?? app.windows.firstMatch).screenshot()125        #else126        let image = element?.screenshot() ?? XCUIScreen.main.screenshot()127        #endif128        try? image.pngRepresentation.write(to: dir.appendingPathComponent("\(name).png"))129    }130131    func value(_ id: String) -> String { (el(id).value as? String) ?? "" }132133    // ── steps shared by the scenarios ──134135    /// Welcome → invitation → handle → recovery kit → verification → main. Returns (handle, recovery key).136    @discardableResult137    func join(shotName: String? = nil) throws -> (handle: String, key: String) {138        let invite = try UI.nextInvite()139        need("welcome", 40)140        tap("welcome-join")141        type("welcome-invite", "http://localhost:8781/#/join/\(invite)")142        tap("welcome-invite-continue")143        let handle = "ui" + String(UUID().uuidString.lowercased().filter { $0.isLetter || $0.isNumber }.prefix(8))144        type("join-handle", handle)145        tap("join-create")146        need("recovery-kit", 40)147        var groups: [String] = []148        for i in 1...14 { groups.append(value("kit-group-\(i)")) }149        XCTAssertTrue(groups.allSatisfy { $0.count == 4 }, "recovery key groups unreadable: \(groups)")150        if let shotName { shot(shotName) }151        tap("kit-continue")152        let asked = need("kit-asked").label.split(whereSeparator: { !$0.isNumber }).compactMap { Int($0) }153        XCTAssertEqual(asked.count, 3)154        // a wrong group first: the vault must not open155        type("kit-verify-0", "ZZZZ")156        XCTAssertFalse(el("kit-done").isEnabled)157        clear("kit-verify-0")158        for (i, g) in asked.enumerated() { type("kit-verify-\(i)", groups[g - 1]) }159        XCTAssertTrue(el("kit-done").isEnabled)160        tap("kit-done")161        need("main", 30)162        return (handle, "SPV1-" + groups.joined(separator: "-"))163    }164165    func clear(_ id: String) {166        tap(id)167        #if os(macOS)168        el(id).typeKey("a", modifierFlags: .command)169        el(id).typeKey(.delete, modifierFlags: [])170        #else171        el(id).typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: 8))172        #endif173    }174175    func newItem() {176        #if os(macOS)177        app.typeKey("n", modifierFlags: .command)178        #else179        tap("new-item")180        #endif181        need("item-editor")182    }183184    func createLogin(title: String, user: String, password: String, totp: String? = nil, url: String? = nil) {185        newItem()186        type("editor-title", title)187        type("editor-field-username", user)188        type("editor-field-password", password)189        if let totp { type("editor-field-totp", totp) }190        if let url { tap("editor-add-url"); type("editor-url-0", url) }191        tap("editor-save")192        gone("item-editor")193        Thread.sleep(forTimeInterval: 1) // taps made while the sheet is still sliding away are swallowed194    }195196    func openSection(_ id: String, phoneTab: String? = nil, phoneRow: String? = nil) {197        #if os(macOS)198        tap(id)199        #else200        if UI.platform == "ipad" { tap(id); return }201        if let phoneTab { app.tabBars.buttons[phoneTab].firstMatch.tap() }202        if let phoneRow { tap(phoneRow) }203        #endif204    }205206    func lock() {207        #if os(macOS)208        app.typeKey("l", modifierFlags: .command)209        #else210        if UI.platform == "iphone" { app.tabBars.buttons["Items"].firstMatch.tap() }211        tap("lock")212        #endif213        need("locked")214    }215216    func unlock() {217        need("locked", 30)218        tap("unlock")219        need("main", 30)220    }221}222
Files main
Menu

Theme