SPB Git

Repository Public

SandboxFlowUITests.swift 12.8 KB 259 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr Identity9// File             : sdk/swift/Examples/IdentityDemo/UITests/SandboxFlowUITests.swift10// Module           : sdk11// Repository       : https://git.spboucher.ai/maclustr-identity12// Project Website  : https://identity.spboucher.ai13// Created          : 2026-12-0114// Last Modified    : 2026-12-0115//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: admin@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 UI test of the native flow on the iOS Simulator, against a local backend, in sandbox.89// Skipped unless the backend is given:90//   TEST_RUNNER_MLID_TEST_BASE_URL=http://localhost:8875 TEST_RUNNER_MLID_TEST_API_KEY=mlid_sk_test_… xcodebuild test …91// The Simulator has no camera, so only the sandbox path (which never captures images) and the92// camera-unavailable state can be exercised here.93import XCTest9495final class SandboxFlowUITests: XCTestCase {96    /// Test-only stand-in for the integrating app's backend (the app itself never holds an API key).97    private func createSession(live: Bool = false) throws -> String {98        let env = ProcessInfo.processInfo.environment99        guard let base = env["MLID_TEST_BASE_URL"], let key = env[live ? "MLID_TEST_LIVE_API_KEY" : "MLID_TEST_API_KEY"], !key.isEmpty else {100            throw XCTSkip("MLID_TEST_BASE_URL / API key not set")101        }102        var req = URLRequest(url: URL(string: base + "/v1/verification-sessions")!)103        req.httpMethod = "POST"104        req.setValue("Bearer " + key, forHTTPHeaderField: "Authorization")105        req.setValue("application/json", forHTTPHeaderField: "Content-Type")106        req.httpBody = try JSONSerialization.data(withJSONObject: ["purpose": "sdk_ui_test", "external_user_id": "ui_" + UUID().uuidString.prefix(8), "locale": "en-CA"])107        var url: String?108        let done = expectation(description: "session")109        URLSession.shared.dataTask(with: req) { data, _, _ in110            url = data.flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }?["url"] as? String111            done.fulfill()112        }.resume()113        wait(for: [done], timeout: 15)114        return try XCTUnwrap(url, "the backend did not create a session")115    }116117    private func launch(_ hostedURL: String) -> XCUIApplication {118        let app = XCUIApplication()119        app.launchArguments = ["-hostedURL", hostedURL, "-autostart", "YES", "-AppleLanguages", "(en)"]120        app.launch()121        return app122    }123124    /// Dismisses a confirmation dialog without choosing anything. Recent iOS versions show these dialogs without a125    /// cancel button (tapping outside dismisses them); older ones have the cancel button.126    private func dismissDialog(_ app: XCUIApplication, cancelLabel: String) {127        let cancel = app.buttons[cancelLabel]128        if cancel.exists, cancel.isHittable { cancel.tap() } else { app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.08)).tap() }129    }130131    private func shot(_ app: XCUIApplication, _ name: String) {132        let a = XCTAttachment(screenshot: app.screenshot())133        a.name = name134        a.lifetime = .keepAlways135        add(a)136    }137138    func testSandboxSessionEndsVerified() throws {139        let app = launch(try createSession())140        XCTAssertTrue(app.buttons["Get started"].waitForExistence(timeout: 15))141        XCTAssertTrue(app.staticTexts["Verification performed by MacLustr Identity"].exists || app.otherElements.containing(NSPredicate(format: "label CONTAINS 'MacLustr Identity'")).count > 0)142        shot(app, "1-intro")143        app.buttons["Get started"].tap()144        let method = app.buttons["mlid.method.document_selfie"]145        XCTAssertTrue(method.waitForExistence(timeout: 5))146        shot(app, "2-method")147        method.tap()148        let accept = app.buttons["Accept and continue"]149        XCTAssertTrue(accept.waitForExistence(timeout: 5))150        XCTAssertFalse(accept.isEnabled, "consent must not be pre-ticked")151        let checkbox = app.descendants(matching: .any)["mlid.consent.checkbox"]152        XCTAssertTrue(checkbox.label.contains("I expressly consent"))153        for _ in 0..<6 where !checkbox.isHittable { app.swipeUp() }154        shot(app, "3-consent")155        checkbox.tap()156        XCTAssertTrue(accept.isEnabled)157        accept.tap()158        let scenario = app.buttons["Verified"]159        XCTAssertTrue(scenario.waitForExistence(timeout: 10))160        shot(app, "4-sandbox")161        scenario.tap()162        XCTAssertTrue(app.staticTexts["Identity verified"].waitForExistence(timeout: 10))163        shot(app, "5-result")164        app.buttons["Done"].tap()165        XCTAssertTrue(app.staticTexts["completed: verified"].waitForExistence(timeout: 5))166    }167168    func testLeavingTheFlowReportsCanceled() throws {169        let app = launch(try createSession())170        XCTAssertTrue(app.buttons["Get started"].waitForExistence(timeout: 15))171        app.buttons["Get started"].tap()172        XCTAssertTrue(app.buttons["mlid.close"].waitForExistence(timeout: 5))173        app.buttons["mlid.close"].tap()174        let leave = app.buttons["Leave"]175        XCTAssertTrue(leave.waitForExistence(timeout: 5))176        leave.tap()177        XCTAssertTrue(app.staticTexts["canceled"].waitForExistence(timeout: 5))178    }179180    /// Withdrawing consent destroys the session: it must always ask first, and "Cancel" must leave everything intact.181    func testWithdrawalDuringManualReviewAsksForConfirmation() throws {182        let app = launch(try createSession())183        XCTAssertTrue(app.buttons["Get started"].waitForExistence(timeout: 15))184        app.buttons["Get started"].tap()185        app.buttons["mlid.method.document_review"].tap()186        let checkbox = app.descendants(matching: .any)["mlid.consent.checkbox"]187        XCTAssertTrue(checkbox.waitForExistence(timeout: 5))188        for _ in 0..<6 where !checkbox.isHittable { app.swipeUp() }189        checkbox.tap()190        app.buttons["Accept and continue"].tap()191        let scenario = app.buttons["Manual review"]192        XCTAssertTrue(scenario.waitForExistence(timeout: 10))193        scenario.tap()194        XCTAssertTrue(app.staticTexts["Review by a person"].waitForExistence(timeout: 10))195        let withdraw = app.buttons["mlid.withdraw"]196        XCTAssertTrue(withdraw.waitForExistence(timeout: 5))197        for _ in 0..<4 where !withdraw.isHittable { app.swipeUp() }198        withdraw.tap()199        // First tap: only a question. Declining keeps the session under review.200        let confirm = app.buttons["Withdraw and destroy everything"]201        XCTAssertTrue(confirm.waitForExistence(timeout: 5))202        shot(app, "withdraw-confirmation")203        dismissDialog(app, cancelLabel: "Cancel")204        XCTAssertTrue(confirm.waitForNonExistence(timeout: 5))205        XCTAssertTrue(app.staticTexts["Review by a person"].waitForExistence(timeout: 5))206        XCTAssertFalse(app.staticTexts["Verification cancelled"].exists)207        // Confirmed: everything is destroyed.208        withdraw.tap()209        XCTAssertTrue(confirm.waitForExistence(timeout: 5))210        confirm.tap()211        XCTAssertTrue(app.staticTexts["Verification cancelled"].waitForExistence(timeout: 10))212        app.buttons["Done"].tap()213        XCTAssertTrue(app.staticTexts["canceled"].waitForExistence(timeout: 5))214    }215216    func testInvalidSecretShowsAnError() throws {217        let url = try createSession()218        let app = launch(url.components(separatedBy: "#")[0] + "#vsc_wrong")219        XCTAssertTrue(app.staticTexts["This verification link is not valid."].waitForExistence(timeout: 15))220        shot(app, "invalid-link")221        app.buttons["mlid.close"].tap()222        XCTAssertTrue(app.staticTexts.containing(NSPredicate(format: "label BEGINSWITH 'failed'")).firstMatch.waitForExistence(timeout: 5))223    }224225    /// Live session (development database with open gates): the Simulator has no camera, so the document step226    /// must offer the file fallback instead of a camera preview.227    func testLiveSessionWithoutCameraOffersAFile() throws {228        let app = launch(try createSession(live: true))229        XCTAssertTrue(app.buttons["Get started"].waitForExistence(timeout: 15))230        app.buttons["Get started"].tap()231        app.buttons["mlid.method.document_review"].tap()232        let checkbox = app.descendants(matching: .any)["mlid.consent.checkbox"]233        XCTAssertTrue(checkbox.waitForExistence(timeout: 5))234        for _ in 0..<6 where !checkbox.isHittable { app.swipeUp() }235        checkbox.tap()236        app.buttons["Accept and continue"].tap()237        XCTAssertTrue(app.staticTexts["Front of the document"].waitForExistence(timeout: 10))238        XCTAssertTrue(app.buttons["Choose a file"].exists)239        shot(app, "document-no-camera")240        // Withdraw consent: everything is destroyed and the app is told the flow was cancelled.241        // "Cancel" never destroys by itself: it asks whether to leave; withdrawing asks a second, explicit question.242        app.buttons["mlid.close"].tap()243        XCTAssertTrue(app.buttons["Leave"].waitForExistence(timeout: 5))244        dismissDialog(app, cancelLabel: "Stay")245        XCTAssertTrue(app.buttons["Leave"].waitForNonExistence(timeout: 5))246        XCTAssertTrue(app.staticTexts["Front of the document"].waitForExistence(timeout: 5))247        app.buttons["mlid.close"].tap()248        XCTAssertTrue(app.buttons["Withdraw my consent"].waitForExistence(timeout: 5))249        app.buttons["Withdraw my consent"].tap()250        let confirm = app.buttons["Withdraw and destroy everything"]251        XCTAssertTrue(confirm.waitForExistence(timeout: 5))252        XCTAssertFalse(app.staticTexts["Verification cancelled"].exists)253        confirm.tap()254        XCTAssertTrue(app.staticTexts["Verification cancelled"].waitForExistence(timeout: 10))255        app.buttons["Done"].tap()256        XCTAssertTrue(app.staticTexts["canceled"].waitForExistence(timeout: 5))257    }258}259
Files main
Menu

Theme