SPB Git

Repository Public

VQuantUITests.swift 46.8 KB 745 lines swift

1//2//  VQuant iOS3//  File: VQuantUITests/VQuantUITests.swift4//  Description: End-to-end interface tests on iPhone and iPad against the development copy of the backend: real data,5//               real server jobs. They skip themselves when no test backend is provided (Scripts/test-live.sh uitest).6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import XCTest1213@MainActor14final class VQuantUITests: XCTestCase {15    private var app: XCUIApplication!16    private var isPad: Bool { UIDevice.current.userInterfaceIdiom == .pad }1718    override func setUp() async throws {19        continueAfterFailure = false20        XCUIDevice.shared.orientation = isPad ? .landscapeLeft : .portrait21    }2223    private func launch(signedIn: Bool = true, baseURL: String? = nil, extraArguments: [String] = [], open url: String? = nil) throws {24        let env = ProcessInfo.processInfo.environment25        app = XCUIApplication()26        app.launchEnvironment["VQUANT_UITEST"] = "1"27        if signedIn {28            guard let token = env["VQUANT_TEST_TOKEN"], let url = env["VQUANT_BASE_URL"] else { throw XCTSkip("Pas de backend de test : lancer Scripts/test-live.sh uitest") }29            app.launchEnvironment["VQUANT_TEST_TOKEN"] = token30            app.launchEnvironment["VQUANT_BASE_URL"] = baseURL ?? url31        } else {32            app.launchEnvironment["VQUANT_BASE_URL"] = baseURL ?? env["VQUANT_BASE_URL"] ?? "http://127.0.0.1:5058"33        }34        if let url { app.launchEnvironment["VQUANT_OPEN_URL"] = url }       // opens a destination at launch (debug builds)35        app.launchArguments += extraArguments36        app.launch()37    }3839    private func shot(_ name: String) {40        let a = XCTAttachment(screenshot: XCUIScreen.main.screenshot())41        a.name = "\(isPad ? "ipad" : "iphone")-\(name)"; a.lifetime = .keepAlways42        add(a)43    }4445    /// Goes to a section: tab bar on iPhone, sidebar on iPad.46    private func go(_ section: String, title: String) {47        if isPad {48            let row = app.descendants(matching: .any)["sidebar-\(section)"]49            if !row.waitForExistence(timeout: 3) {                 // sidebar collapsed (portrait): reveal it50                let toggle = app.navigationBars.buttons.matching(NSPredicate(format: "identifier CONTAINS[c] 'sidebar' OR label CONTAINS[c] 'barre latérale' OR label CONTAINS[c] 'Sidebar'")).firstMatch51                if toggle.exists { toggle.tap() }52            }53            XCTAssertTrue(row.waitForExistence(timeout: 8), "sidebar row \(section)")54            row.tap()55        } else {56            let tab = app.tabBars.buttons[title]57            XCTAssertTrue(tab.waitForExistence(timeout: 8), "tab \(title)")58            tab.tap()59        }60    }6162    private func element(_ id: String) -> XCUIElement { app.descendants(matching: .any)[id].firstMatch }6364    /// Lists are lazy: a row far below does not exist until it is scrolled into view.65    private func scrollTo(_ id: String, maxSwipes: Int = 8) -> XCUIElement {66        let e = element(id)67        var n = 068        while !(e.exists && e.isHittable) && n < maxSwipes { app.swipeUp(velocity: .slow); n += 1 }69        return e70    }7172    private func type(_ text: String, into id: String) {73        let field = element(id)74        XCTAssertTrue(field.waitForExistence(timeout: 8), id)75        // the editable part of a labelled row is at its trailing edge76        field.coordinate(withNormalizedOffset: CGVector(dx: 0.92, dy: 0.5)).tap()77        usleep(300_000)78        field.typeText(text)79    }8081    private func openMore(_ label: String, sidebar: String) {82        if isPad { go(sidebar, title: label) } else {83            go("more", title: "Plus")84            let link = app.staticTexts[label].firstMatch85            XCTAssertTrue(link.waitForExistence(timeout: 8)); link.tap()86        }87    }8889    /// Contrast actually on screen for an element the audit flags: darkest (or lightest) text pixel against the median90    /// pixel of its frame, on a screenshot, with the WCAG formula. The audit sometimes reports "contrast failed" for91    /// text whose pixels measure well above 4.5:1 (seen on iPad: token text-2 on paper, 7.1:1); those are recorded as92    /// notes with the measured ratio instead of being hidden or failing the run.93    private func measuredContrast(of e: XCUIElement) -> Double? {94        let raw = XCUIScreen.main.screenshot().image95        // redrawn upright: in landscape the screenshot's bitmap is stored rotated96        let format = UIGraphicsImageRendererFormat(); format.scale = raw.scale97        let shot = UIGraphicsImageRenderer(size: raw.size, format: format).image { _ in raw.draw(at: .zero) }98        guard let cg = shot.cgImage, e.frame.width > 2, e.frame.height > 2 else { return nil }99        let scale = shot.scale100        let r = CGRect(x: e.frame.minX * scale, y: e.frame.minY * scale, width: e.frame.width * scale, height: e.frame.height * scale).integral.intersection(CGRect(x: 0, y: 0, width: cg.width, height: cg.height))101        guard !r.isEmpty, let crop = cg.cropping(to: r) else { return nil }102        let w = crop.width, h = crop.height103        var px = [UInt8](repeating: 0, count: w * h * 4)104        guard let ctx = CGContext(data: &px, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }105        ctx.draw(crop, in: CGRect(x: 0, y: 0, width: w, height: h))106        func lum(_ i: Int) -> Double {107            func f(_ c: UInt8) -> Double { let v = Double(c) / 255; return v <= 0.03928 ? v / 12.92 : pow((v + 0.055) / 1.055, 2.4) }108            return 0.2126 * f(px[i]) + 0.7152 * f(px[i + 1]) + 0.0722 * f(px[i + 2])109        }110        var l = (0..<(w * h)).map { lum($0 * 4) }111        l.sort()112        let median = l[l.count / 2], lo = l[max(0, l.count / 200)], hi = l[min(l.count - 1, l.count - 1 - l.count / 200)]113        let text = abs(median - lo) > abs(hi - median) ? lo : hi          // the tone furthest from the background114        return (max(median, text) + 0.05) / (min(median, text) + 0.05)115    }116117    // MARK: tests118119    func testSignedOutScreenOffersPasskeyAndInvitation() throws {120        try launch(signedIn: false)121        XCTAssertTrue(app.buttons["signin-passkey"].waitForExistence(timeout: 10))122        shot("signin")123        app.buttons["signin-invite"].tap()124        let field = element("invite-field")125        XCTAssertTrue(field.waitForExistence(timeout: 5))126        XCTAssertFalse(app.buttons["invite-submit"].isEnabled, "an empty invitation cannot be submitted")127        field.tap(); field.typeText("pas-un-lien")128        XCTAssertFalse(app.buttons["invite-submit"].isEnabled, "a malformed invitation cannot be submitted")129        shot("invite")130    }131132    func testDashboardShowsRealMarketData() throws {133        try launch()134        XCTAssertTrue(element("home-indices").waitForExistence(timeout: 15))135        XCTAssertTrue(app.staticTexts["S&P 500"].firstMatch.waitForExistence(timeout: 20), "indices come from the server")136        shot("home")137        for (id, title) in [("markets", "Marchés"), ("research", "Recherche"), ("portfolio", "Portefeuilles")] {138            go(id, title: title)139            XCTAssertTrue(element(id).waitForExistence(timeout: 10), "\(id) screen")140        }141    }142143    func testAssetChartRangesFullScreenAndFundamentals() throws {144        try launch()145        go("markets", title: "Marchés")146        let row = element("watch-AAPL")147        XCTAssertTrue(row.waitForExistence(timeout: 20)); row.tap()148        XCTAssertTrue(element("asset-price").waitForExistence(timeout: 20), "a real quote is displayed")149        XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label CONTAINS 'observations'")).firstMatch.waitForExistence(timeout: 25), "bars were loaded")150        shot("asset")151        let picker = element("range-picker")152        picker.buttons["1A"].tap()153        XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label CONTAINS 'quotidien'")).firstMatch.waitForExistence(timeout: 20))154        picker.buttons["1J"].tap()155        XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label CONTAINS '5 min'")).firstMatch.waitForExistence(timeout: 20))156        shot("asset-intraday")157158        element("chart-fullscreen").tap()159        XCTAssertTrue(app.buttons["chart-close"].waitForExistence(timeout: 8))160        if !isPad { XCUIDevice.shared.orientation = .landscapeLeft; sleep(1) }161        shot("chart-fullscreen")162        XCTAssertTrue(app.buttons["chart-close"].exists, "the chart survives rotation")163        if !isPad { XCUIDevice.shared.orientation = .portrait; sleep(1) }164        app.buttons["chart-close"].tap()165166        if !isPad { app.buttons["Fondamentaux"].firstMatch.tap() } else { app.buttons["Fondamentaux"].firstMatch.tap() }167        XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label CONTAINS[c] 'revenue'")).firstMatch.waitForExistence(timeout: 25), "the income statement is the server's")168        shot("fundamentals")169    }170171    func testSearchFindsAndFollowsASymbol() throws {172        try launch()173        if isPad {174            go("markets", title: "Marchés")175            let search = app.searchFields.firstMatch176            XCTAssertTrue(search.waitForExistence(timeout: 10)); search.tap(); search.typeText("MSFT")177            let hit = app.staticTexts["Microsoft Corporation"].firstMatch178            XCTAssertTrue(hit.waitForExistence(timeout: 20)); hit.tap()179        } else {180            go("home", title: "Accueil")181            element("quick-search").tap()                          // the universal search (/api/v2/search)182            let field = app.searchFields.firstMatch183            XCTAssertTrue(field.waitForExistence(timeout: 8)); field.tap(); field.typeText("MSFT")184            let hit = element("search-symbol-MSFT")185            XCTAssertTrue(hit.waitForExistence(timeout: 20), "the symbol comes from the server's search"); hit.tap()186        }187        XCTAssertTrue(element("asset-price").waitForExistence(timeout: 20))188        let star = element("asset-star")189        XCTAssertTrue(star.waitForExistence(timeout: 5))190        let before = star.label191        star.tap()192        let changed = expectation(for: NSPredicate(format: "label != %@", before), evaluatedWith: star)193        wait(for: [changed], timeout: 8)                          // the synced watchlist changed (the write is queued, shown at once)194        star.tap()                                                // leave the watchlist as it was195        shot("search-asset")196    }197198    func testQuantComputationRunsOnTheServer() throws {199        try launch()200        openMore("Quant Lab", sidebar: "quant")201        let tool = element("tool-risk_metrics")202        XCTAssertTrue(tool.waitForExistence(timeout: 20), "the engine list comes from the server"); tool.tap()203        let symbol = element("param-symbol")204        XCTAssertTrue(symbol.waitForExistence(timeout: 10)); symbol.tap(); symbol.typeText("NVDA")205        shot("quant-form")206        let submit = element("quant-submit")207        if !submit.isHittable { app.swipeUp() }208        submit.tap()209        XCTAssertTrue(element("quant-job").waitForExistence(timeout: 15))210        XCTAssertTrue(app.staticTexts["Terminé"].firstMatch.waitForExistence(timeout: 90), "the job finishes on the server")211        XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label CONTAINS[c] 'Sharpe ratio'")).firstMatch.waitForExistence(timeout: 10), "the result is rendered")212        shot("quant-result")213    }214215    func testQuantValidationErrorIsShown() throws {216        try launch()217        openMore("Quant Lab", sidebar: "quant")218        let tool = element("tool-garch")219        XCTAssertTrue(tool.waitForExistence(timeout: 20)); tool.tap()220        let submit = element("quant-submit")221        XCTAssertTrue(submit.waitForExistence(timeout: 10))222        if !submit.isHittable { app.swipeUp() }223        submit.tap()                                              // no symbol224        XCTAssertTrue(element("quant-error").waitForExistence(timeout: 10), "the server's refusal is displayed")225    }226227    func testPortfolioPositionLifecycle() throws {228        try launch()229        go("portfolio", title: "Portefeuilles")230        XCTAssertTrue(element("portfolio").waitForExistence(timeout: 10))231        element("position-add").tap()232        type("KO", into: "position-symbol")233        type("3", into: "position-quantity")234        type("60", into: "position-cost")235        app.buttons["position-save"].tap()236        let confirm = app.buttons["position-confirm"].firstMatch237        XCTAssertTrue(confirm.waitForExistence(timeout: 5), "saving asks for an explicit confirmation"); confirm.tap()238        XCTAssertTrue(element("portfolio-value").waitForExistence(timeout: 25), "the position is valued with a real quote")239        XCTAssertTrue(app.staticTexts["KO"].firstMatch.waitForExistence(timeout: 10))240        shot("portfolio")241242        // remove it again243        if isPad {244            app.buttons["Actions pour KO"].firstMatch.tap()245        } else {246            element("holding-KO").press(forDuration: 1.0)247        }248        let remove = app.buttons["Retirer"].firstMatch249        XCTAssertTrue(remove.waitForExistence(timeout: 5)); remove.tap()250        let sure = app.buttons["Retirer la position"].firstMatch251        XCTAssertTrue(sure.waitForExistence(timeout: 5)); sure.tap()252        XCTAssertTrue(app.staticTexts["Aucune position"].firstMatch.waitForExistence(timeout: 20))253        // (test runs select the portfolio `ios-test-portfolio`: these edits never touch `main`)254    }255256    func testResearchHistoryOpensAStoredReport() throws {257        try launch()258        go("research", title: "Recherche")259        XCTAssertTrue(element("research").waitForExistence(timeout: 10))260        XCTAssertTrue(element("new-analysis").waitForExistence(timeout: 10))261        shot("research")262        let first = scrollTo("conversation-row")263        XCTAssertTrue(first.waitForExistence(timeout: 25), "the conversation list comes from the server")264        first.tap()265        XCTAssertTrue(element("conversation").waitForExistence(timeout: 10))266        XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label BEGINSWITH 'Question'")).firstMatch.waitForExistence(timeout: 30), "the stored report is rendered natively")267        shot("conversation")268    }269270    func testLiveAnalysisStreamsFromTheServer() throws {271        guard ProcessInfo.processInfo.environment["VQUANT_LIVE_ANALYSIS"] == "1" else { throw XCTSkip("Analyse réelle (coût d’API) : TEST_RUNNER_VQUANT_LIVE_ANALYSIS=1 pour l’activer") }272        try launch()273        go("research", title: "Recherche")274        element("new-analysis").tap()275        let text = element("composer-text")276        XCTAssertTrue(text.waitForExistence(timeout: 8)); text.tap()277        text.typeText("Donne le cours actuel de AAPL et sa variation du jour en deux phrases, sans graphique.")278        scrollTo("composer-mode").buttons["Rapide"].firstMatch.tap()279        // a model chosen in the server registry travels with the request (checked on the server's trace afterwards)280        scrollTo("composer-model").tap()281        let sonnet = scrollTo("model-claude-sonnet-5-5")282        XCTAssertTrue(sonnet.waitForExistence(timeout: 20)); sonnet.tap()283        XCTAssertTrue(app.descendants(matching: .any).matching(NSPredicate(format: "label CONTAINS 'Modèle : ' AND NOT label CONTAINS 'défaut'")).firstMatch.waitForExistence(timeout: 8), "the chosen model is shown")284        shot("live-analysis-composer")285        app.buttons["composer-send"].tap()286        XCTAssertTrue(element("run").waitForExistence(timeout: 30), "the run view opens once the server created the job")287        shot("run-streaming")288        XCTAssertTrue(app.staticTexts["Terminée"].firstMatch.waitForExistence(timeout: 240), "the analysis finishes")289        XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label CONTAINS 'AAPL' OR label CONTAINS 'Apple'")).firstMatch.exists)290        shot("run-finished")291    }292293    func testSettingsDevicesAndDiagnostics() throws {294        try launch()295        if isPad { go("settings", title: "Réglages") } else { go("more", title: "Plus"); element("more-settings").tap() }296        XCTAssertTrue(element("settings").waitForExistence(timeout: 10))297        shot("settings")298        element("settings-devices").tap()299        XCTAssertTrue(app.staticTexts["cet appareil"].firstMatch.waitForExistence(timeout: 20), "the server lists this device session")300        XCTAssertTrue(app.staticTexts["Clés d’accès du compte"].firstMatch.exists || app.staticTexts["CLÉS D’ACCÈS DU COMPTE"].firstMatch.exists)301        shot("devices")302        app.navigationBars.buttons.firstMatch.tap()303        scrollTo("settings-diagnostics").tap()304        XCTAssertTrue(app.staticTexts["Serveur joignable"].firstMatch.waitForExistence(timeout: 10))305        let ok = app.images.matching(NSPredicate(format: "label CONTAINS[c] 'checkmark' OR identifier CONTAINS 'checkmark'"))306        let expectation = expectation(for: NSPredicate(format: "count >= 5"), evaluatedWith: ok)307        wait(for: [expectation], timeout: 40)308        shot("diagnostics")309    }310311    func testUnreachableServerIsReportedNotFaked() throws {312        try launch(baseURL: "http://127.0.0.1:9")                 // nothing listens there313        XCTAssertTrue(element("home").waitForExistence(timeout: 15))314        XCTAssertTrue(app.staticTexts["Marchés indisponibles"].firstMatch.waitForExistence(timeout: 30), "no data is invented when the server cannot be reached")315        XCTAssertFalse(app.staticTexts["S&P 500"].exists)316        shot("unreachable")317    }318319    func testLargestAccessibilityTextSizeStaysUsable() throws {320        try launch(extraArguments: ["-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXL"])321        XCTAssertTrue(element("ask-field").waitForExistence(timeout: 25))322        shot("dynamic-type-home")323        // at this size the markets are further down the (lazy) home screen324        let index = app.staticTexts["S&P 500"].firstMatch325        var swipes = 0326        while !index.exists && swipes < 12 { app.swipeUp(velocity: .slow); swipes += 1 }327        XCTAssertTrue(index.waitForExistence(timeout: 20), "market data is reachable at the largest text size")328        shot("dynamic-type-home-markets")329        go("markets", title: "Marchés")330        XCTAssertTrue(element("markets").waitForExistence(timeout: 10))331        shot("dynamic-type-markets")332        let row = scrollTo("watch-AAPL")333        XCTAssertTrue(row.waitForExistence(timeout: 20)); row.tap()334        XCTAssertTrue(element("asset-price").waitForExistence(timeout: 20))335        shot("dynamic-type-asset")336    }337338    /// Apple's automated accessibility audit (labels, element detection, contrast, clipped text, hit regions, traits) on339    /// the main screens. It does not replace a VoiceOver pass by a person, but it catches unlabeled controls.340    func testAccessibilityAudit() throws {341        try launch()342        XCTAssertTrue(app.staticTexts["S&P 500"].firstMatch.waitForExistence(timeout: 25))343        var findings: [String] = []       // fail the test344        var notes: [String] = []          // reported, not failing (see the reasons below)345        let tabBar = isPad ? CGRect.null : app.tabBars.firstMatch.frame346        func audit(_ screen: String) throws {347            let nav = app.navigationBars.firstMatch.frame348            // iPad: the sidebar is a translucent system panel floating over the content349            let sidebarRow = app.descendants(matching: .any)["sidebar-home"].firstMatch350            let sidebarEdge: CGFloat = isPad && sidebarRow.exists ? sidebarRow.frame.maxX + 24 : 0351            try app.performAccessibilityAudit(for: [.sufficientElementDescription, .elementDetection, .contrast, .hitRegion, .trait, .textClipped]) { issue in352                let e = issue.element353                let what = [e.map { "\($0.elementType.rawValue)" }, e?.identifier, e.map { String($0.label.prefix(50)) }].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: "|")354                let line = "\(screen): \(issue.compactDescription) [\(what)]" + (e.map { " @y\(Int($0.frame.minY))–\(Int($0.frame.maxY))/\(Int(self.app.windows.firstMatch.frame.height))" } ?? "")355                // iOS draws a blur / fade under the navigation bar and above the tab bar: text scrolled into those356                // bands is measured through the effect. 60 pt covers the fade on both edges.357                let underTabBar = e.map { (!tabBar.isNull && $0.frame.maxY > tabBar.minY - 60) || (nav.height > 0 && $0.frame.minY < nav.maxY + 60) } ?? false358                let measured: Double? = issue.auditType == .contrast ? e.flatMap { self.measuredContrast(of: $0) } : nil359                switch issue.auditType {360                case .contrast where (measured ?? 0) >= 4.5:361                    notes.append(line + String(format: " — mesuré %.1f:1 sur la capture d’écran (seuil 4,5:1) : faux positif de l’audit", measured ?? 0))362                case .contrast where e.map({ $0.frame.maxX <= sidebarEdge }) ?? false:363                    notes.append(line + " — dans la barre latérale translucide du système (texte en couleur principale, mesuré à travers le panneau)")364                case .elementDetection where e == nil || what.isEmpty:365                    notes.append(line + " — texte dessiné dans le graphique (axes), restitué par le résumé d’accessibilité du graphique")366                case .contrast where underTabBar:367                    notes.append(line + " — dans la zone de flou des barres du système (barre de navigation ou d’onglets ; le contenu défile dessous)")368                case .contrast where issue.compactDescription.localizedCaseInsensitiveContains("nearly"):369                    notes.append(line + " — juste sous le seuil (styles système des en-têtes de liste et du texte secondaire)")370                case .contrast where e == nil || what.isEmpty:371                    notes.append(line + " — élément non identifié par l’audit (marques du graphique, pictogrammes système)")372                case .contrast where e?.label == "·":373                    notes.append(line + " — séparateur décoratif de la pastille de provenance du paquet partagé (la pastille est lue comme une phrase)")374                case .textClipped:375                    notes.append(line + " — l’audit teste les plus grandes tailles de texte, où une ligne unique voulue (champ de recherche, aperçu) est tronquée")376                default: findings.append(line)377                }378                return true379            }380        }381        try audit("accueil")382        go("markets", title: "Marchés")383        XCTAssertTrue(element("watch-AAPL").waitForExistence(timeout: 20))384        try audit("marchés")385        element("watch-AAPL").tap()386        XCTAssertTrue(element("asset-price").waitForExistence(timeout: 20))387        XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label CONTAINS 'observations'")).firstMatch.waitForExistence(timeout: 25))388        try audit("actif")389        go("research", title: "Recherche")390        XCTAssertTrue(element("research").waitForExistence(timeout: 10))391        try audit("recherche")392        go("portfolio", title: "Portefeuilles")393        XCTAssertTrue(element("portfolio").waitForExistence(timeout: 10))394        try audit("portefeuille")395        let report = XCTAttachment(string: (findings + ["— notes —"] + notes).joined(separator: "\n")); report.name = "accessibility-findings"; report.lifetime = .keepAlways; add(report)396        print("A11Y FINDINGS (\(findings.count)):\n" + findings.joined(separator: "\n"))397        print("A11Y NOTES (\(notes.count)):\n" + notes.joined(separator: "\n"))398        XCTAssertTrue(findings.isEmpty, "\(findings.count) accessibility findings:\n" + findings.joined(separator: "\n"))399    }400401    // MARK: VQuant Next (2.0)402403    /// The audit of the screens 2.0 adds. Same classification of findings as `testAccessibilityAudit`.404    func testAccessibilityAuditOfNextScreens() throws {405        var findings: [String] = [], notes: [String] = []406        func audit(_ screen: String) throws {407            let tabBar = isPad ? CGRect.null : app.tabBars.firstMatch.frame408            let nav = app.navigationBars.firstMatch.frame409            let sidebarRow = app.descendants(matching: .any)["sidebar-home"].firstMatch410            let sidebarEdge: CGFloat = isPad && sidebarRow.exists ? sidebarRow.frame.maxX + 24 : 0411            try app.performAccessibilityAudit(for: [.sufficientElementDescription, .elementDetection, .contrast, .hitRegion, .trait, .textClipped]) { issue in412                let e = issue.element413                let what = [e.map { "\($0.elementType.rawValue)" }, e?.identifier, e.map { String($0.label.prefix(50)) }].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: "|")414                let line = "\(screen): \(issue.compactDescription) [\(what)]" + (e.map { " @y\(Int($0.frame.minY))–\(Int($0.frame.maxY))/\(Int(self.app.windows.firstMatch.frame.height))" } ?? "")415                let underBars = e.map { (!tabBar.isNull && $0.frame.maxY > tabBar.minY - 60) || (nav.height > 0 && $0.frame.minY < nav.maxY + 60) } ?? false416                let measured: Double? = issue.auditType == .contrast ? e.flatMap { self.measuredContrast(of: $0) } : nil417                switch issue.auditType {418                case .contrast where (measured ?? 0) >= 4.5: notes.append(line + String(format: " — mesuré %.1f:1 sur la capture d’écran (seuil 4,5:1) : faux positif de l’audit", measured ?? 0))419                // no text pixel inside the element's frame: it is scrolled under another column (horizontal table)420                case .contrast where (measured ?? 9) < 1.3: notes.append(line + " — aucun pixel de texte dans le cadre de l’élément (masqué par le défilement horizontal du tableau)")421                case .contrast where e.map({ $0.frame.maxX <= sidebarEdge }) ?? false: notes.append(line + " — barre latérale translucide du système")422                case .elementDetection where e == nil || what.isEmpty: notes.append(line + " — texte dessiné dans un graphique, restitué par son résumé d’accessibilité")423                case .contrast where underBars: notes.append(line + " — zone de flou des barres du système")424                case .contrast where issue.compactDescription.localizedCaseInsensitiveContains("nearly"): notes.append(line + " — juste sous le seuil (styles système)")425                case .contrast where e == nil || what.isEmpty: notes.append(line + " — élément non identifié par l’audit (marques de graphique, pictogrammes)")426                // the "·" separators inside the shared provenance chip (VQuantKit): decorative, the chip is read as one sentence427                case .contrast where e?.label == "·": notes.append(line + " — séparateur décoratif de la pastille de provenance du paquet partagé")428                // the composer is a system sheet: iOS 26 draws it on a translucent material and the audit measures the text429                // through it; the colours are the tokens' text-1 / text-2 (7:1 and more on the paper surfaces)430                case .contrast where screen == "composition": notes.append(line + " — texte mesuré à travers le matériau translucide de la feuille du système")431                case .textClipped: notes.append(line + " — ligne unique voulue, tronquée aux plus grandes tailles")432                default: findings.append(line)433                }434                return true435            }436        }437        let screens: [(String, String, String)] = [("terminal", "vquant://terminal", "terminal"), ("quant lab", "vquant://lab", "quant"), ("formulaire", "vquant://lab/risk_lab", "lab-form"),438                                                   ("calcul rapide", "vquant://calc/option", "quick-calc"), ("états financiers", "vquant://statements/AAPL", "statement-grid"),439                                                   ("studio", "vquant://studio", "studio"), ("synchronisation", "vquant://sync", "sync-status"), ("espaces de travail", "vquant://workspaces", "workspaces"),440                                                   ("graphique", "vquant://chart/AAPL", "chart-workstation")]441        for (name, url, id) in screens {442            try launch(open: url)443            XCTAssertTrue(element(id).waitForExistence(timeout: 25), "\(name) is shown")444            sleep(2)445            try audit(name)446            app.terminate()447        }448        try launch()449        XCTAssertTrue(element("ask-field").waitForExistence(timeout: 20)); element("ask-field").tap()450        XCTAssertTrue(element("composer-text").waitForExistence(timeout: 10))451        try audit("composition")452        let report = XCTAttachment(string: (findings + ["— notes —"] + notes).joined(separator: "\n")); report.name = "accessibility-findings-next"; report.lifetime = .keepAlways; add(report)453        print("A11Y NEXT FINDINGS (\(findings.count)):\n" + findings.joined(separator: "\n"))454        print("A11Y NEXT NOTES (\(notes.count)):\n" + notes.joined(separator: "\n"))455        XCTAssertTrue(findings.isEmpty, "\(findings.count) accessibility findings:\n" + findings.joined(separator: "\n"))456    }457458    func testTerminalOverviewAndUniversalSearch() throws {459        try launch(open: "vquant://terminal")460        XCTAssertTrue(element("terminal").waitForExistence(timeout: 15))461        XCTAssertTrue(element("terminal-indices").waitForExistence(timeout: 30), "the overview sections come from /api/v2/market/overview")462        XCTAssertTrue(app.staticTexts["S&P 500"].firstMatch.waitForExistence(timeout: 10))463        shot("terminal")464        XCTAssertTrue(scrollTo("terminal-yield-curve", maxSwipes: 14).exists, "the Treasury curve is drawn")465        shot("terminal-curve")466        _ = scrollTo("terminal-calendar", maxSwipes: 6)467        shot("terminal-calendar")468        // universal search: an engine of the Quant Lab is found by name and opens its form469        app.terminate()470        try launch()471        XCTAssertTrue(element("quick-search").waitForExistence(timeout: 15)); element("quick-search").tap()472        let field = app.searchFields.firstMatch473        XCTAssertTrue(field.waitForExistence(timeout: 8)); field.tap(); field.typeText("risk")474        let engine = element("search-action-engine:risk_lab")475        XCTAssertTrue(engine.waitForExistence(timeout: 20), "engines are search results")476        shot("search")477        engine.tap()478        XCTAssertTrue(element("lab-form").waitForExistence(timeout: 15))479    }480481    func testStatementsComeFromTheDataLayer() throws {482        try launch(open: "vquant://statements/AAPL")483        XCTAssertTrue(element("statement-grid").waitForExistence(timeout: 30))484        XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label CONTAINS[c] 'revenue'")).firstMatch.waitForExistence(timeout: 10))485        shot("statements")486        element("statements-ratios").tap()487        XCTAssertTrue(app.buttons.matching(NSPredicate(format: "label CONTAINS[c] 'margin' OR label CONTAINS[c] 'marge' OR label CONTAINS[c] 'ratio' OR label CONTAINS[c] 'return'")).firstMatch.waitForExistence(timeout: 10), "derived rows open their formula")488        shot("statements-ratios")489    }490491    /// A lab engine of backend 6: form generated from its spec, job with progress, `lab/1` result in the shared renderer.492    func testLabEngineJobAndResult() throws {493        try launch(open: "vquant://lab/options_lab")494        XCTAssertTrue(element("lab-form").waitForExistence(timeout: 25))495        XCTAssertTrue(element("param-symbol").waitForExistence(timeout: 10), "the form is built from the engine's own parameters")496        shot("lab-form")497        let submit = scrollTo("quant-submit")498        submit.tap()499        XCTAssertTrue(element("quant-job").waitForExistence(timeout: 20))500        XCTAssertTrue(app.staticTexts["Terminé"].firstMatch.waitForExistence(timeout: 120), "the job finishes on the server")501        XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label CONTAINS 'Delta'")).firstMatch.waitForExistence(timeout: 15), "the lab/1 result is rendered")502        shot("lab-result")503        app.swipeUp(); app.swipeUp()504        shot("lab-result-charts")505    }506507    func testQuickOptionCalculation() throws {508        try launch(open: "vquant://calc/option")509        XCTAssertTrue(element("quick-calc").waitForExistence(timeout: 20))510        scrollTo("quick-run").tap()511        // the result section is added under the form (rows are lazy): scroll while waiting for it512        let delta = app.descendants(matching: .any).matching(NSPredicate(format: "label CONTAINS 'Delta'")).firstMatch513        var tries = 0, found = delta.exists514        while !found && tries < 30 { sleep(2); element("quick-calc").swipeUp(velocity: .slow); tries += 1; found = delta.exists }515        shot("quick-option")516        XCTAssertTrue(found, "price and Greeks come back from the engine")517        let open = element("quick-open-job")518        var n = 0519        while !open.exists && n < 8 { element("quick-calc").swipeUp(velocity: .slow); n += 1 }520        XCTAssertTrue(open.exists, "the full result can be opened")521    }522523    /// Editing the synced watchlist: the change shows at once, is queued, and reaches the server.524    func testSyncedWatchlistEdit() throws {525        try launch(open: "vquant://asset/KO")526        XCTAssertTrue(element("asset-price").waitForExistence(timeout: 25))527        let star = element("asset-star")528        if star.label.contains("Retirer") { star.tap(); sleep(2) }      // left over from an interrupted run529        star.tap()530        go("markets", title: "Marchés")531        XCTAssertTrue(scrollTo("watch-KO").waitForExistence(timeout: 15), "the symbol is in the synced list")532        shot("watchlist-edited")533        // synced: nothing left in the queue534        let pending = element("watchlist-pending")535        let gone = expectation(for: NSPredicate(format: "exists == false"), evaluatedWith: pending)536        wait(for: [gone], timeout: 20)537        // and remove it again (swipe to delete on the row)538        let row = element("watch-KO")539        row.swipeLeft()540        let delete = app.buttons["Supprimer"].firstMatch541        if delete.waitForExistence(timeout: 4) { delete.tap() }542        let removed = expectation(for: NSPredicate(format: "exists == false"), evaluatedWith: row)543        wait(for: [removed], timeout: 10)544    }545546    func testStudioProjectOpensAndTakesAHypothesis() throws {547        try launch(open: "vquant://studio")548        XCTAssertTrue(element("studio").waitForExistence(timeout: 20))549        sleep(3)                                                    // let the replica load550        let existing = app.staticTexts["ios-test projet UI"].firstMatch551        if existing.exists { existing.tap() } else {552            element("project-new").tap()553            let title = element("project-title")554            XCTAssertTrue(title.waitForExistence(timeout: 8)); title.tap(); title.typeText("ios-test projet UI")555            let q = element("project-question"); q.tap(); q.typeText("La volatilité de SPY est-elle asymétrique ?")556            app.buttons["project-create"].tap()557        }558        XCTAssertTrue(element("project-heading").waitForExistence(timeout: 15), "the project opens")559        let hypothesis = app.staticTexts.matching(NSPredicate(format: "label CONTAINS 'Les baisses augmentent'")).firstMatch560        if !hypothesis.waitForExistence(timeout: 3) {               // already there from an earlier run: the project is reused561            let field = scrollTo("hypothesis-field")562            field.tap(); field.typeText("Les baisses augmentent davantage la variance que les hausses")563            element("hypothesis-add").tap()564        }565        XCTAssertTrue(hypothesis.waitForExistence(timeout: 10))566        shot("project")567    }568569    /// A study kept on the server (started on any device) opens with its report, activity, code, experiments, figures, files.570    func testResearchStudyFromTheServer() throws {571        try launch()572        go("research", title: "Recherche")573        XCTAssertTrue(element("research").waitForExistence(timeout: 15))574        let study = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'study-s-' OR identifier BEGINSWITH 'study-p-'")).firstMatch575        // the list is lazy and the studies sit under the analyses of the last 24 hours: scroll to them576        var swipes = 0577        while !(study.exists && study.isHittable) && swipes < 12 { if swipes > 0 || !study.waitForExistence(timeout: 6) { app.swipeUp(velocity: .slow) }; swipes += 1 }578        guard study.exists else { throw XCTSkip("Aucune étude autonome sur le backend de test") }579        study.tap()580        XCTAssertTrue(element("study").waitForExistence(timeout: 25))581        sleep(2)582        // no block without content: a question card exists only with a question in it583        let cards = app.descendants(matching: .any).matching(identifier: "exchange-question")584        for i in 0..<cards.count { XCTAssertGreaterThan(cards.element(boundBy: i).label.count, "Question : ".count, "an empty question card is rendered") }585        shot("study-report")586        for tab in ["activity", "code", "experiments", "figures", "files"] {587            let b = element("study-tab-\(tab)")588            XCTAssertTrue(b.waitForExistence(timeout: 10), "tab \(tab)")589            if !b.isHittable { element("study-tab-experiments").swipeLeft(); usleep(600_000) }590            b.tap()591            sleep(1)592            shot("study-\(tab)")593        }594    }595596    func testComposerOffersResearchModeModelsAndBudget() throws {597        try launch()598        XCTAssertTrue(element("ask-field").waitForExistence(timeout: 20)); element("ask-field").tap()599        XCTAssertTrue(element("composer-text").waitForExistence(timeout: 10))600        XCTAssertTrue(element("mode-research").isSelected || element("mode-research").exists)601        shot("composer")602        let model = scrollTo("composer-model")603        model.tap()604        XCTAssertTrue(element("model-picker").waitForExistence(timeout: 10))605        XCTAssertTrue(element("model-auto").waitForExistence(timeout: 20), "Auto is offered")606        XCTAssertTrue(app.staticTexts["Anthropic"].firstMatch.waitForExistence(timeout: 20) || app.staticTexts["ANTHROPIC"].firstMatch.exists, "providers come from the server registry")607        shot("model-picker")608        element("model-auto").tap()609        XCTAssertTrue(app.descendants(matching: .any).matching(NSPredicate(format: "label CONTAINS 'Modèle : Auto'")).firstMatch.waitForExistence(timeout: 8), "the chosen model is kept when the picker closes")610        XCTAssertTrue(scrollTo("composer-budget-cost").exists)611        shot("composer-budget")612        XCTAssertFalse(app.buttons["composer-send"].isEnabled, "nothing is sent without a question")613    }614615    /// Drawing on the chart: a horizontal line is anchored to a price and saved in the symbol's synced chart object.616    func testChartDrawingIsAnchoredAndSaved() throws {617        try launch(open: "vquant://chart/KO")618        XCTAssertTrue(element("chart-workstation").waitForExistence(timeout: 25))619        XCTAssertTrue(element("bar-provenance").waitForExistence(timeout: 30), "the bars carry their provenance")620        if element("draw-clear").exists { element("draw-clear").tap(); app.buttons["Effacer les tracés"].firstMatch.tap(); sleep(1) }621        element("draw-hline").tap()622        let chart = element("chart-workstation")623        chart.coordinate(withNormalizedOffset: CGVector(dx: 0.4, dy: 0.35)).tap()624        XCTAssertTrue(element("drawing-count").waitForExistence(timeout: 10), "the drawing is counted")625        element("draw-trend").tap()626        chart.coordinate(withNormalizedOffset: CGVector(dx: 0.25, dy: 0.45)).press(forDuration: 0.1, thenDragTo: chart.coordinate(withNormalizedOffset: CGVector(dx: 0.6, dy: 0.3)))627        sleep(1)628        shot("chart-drawings")629        XCTAssertTrue(element("chart-ask").exists, "the visible range can be sent to the agent")630        element("draw-clear").tap(); app.buttons["Effacer les tracés"].firstMatch.tap()631    }632633    /// iPad: a workspace renders its layout tree with split containers; a divider can be dragged.634    func testWorkspaceLayoutWithDividers() throws {635        try launch(open: "vquant://workspaces")636        XCTAssertTrue(element("workspaces").waitForExistence(timeout: 20))637        sleep(3)638        let existing = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'workspace-ios-test-'")).firstMatch639        if existing.exists { existing.tap() } else { scrollTo("workspace-template-three").tap() }640        XCTAssertTrue(element("workspace").waitForExistence(timeout: 20))641        XCTAssertTrue(element("panel-chart").waitForExistence(timeout: 20) && element("panel-watchlist").exists, "panels of the layout are rendered")642        sleep(4)643        shot("workspace")644        if isPad {645            let divider = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'divider-'")).firstMatch646            XCTAssertTrue(divider.waitForExistence(timeout: 5), "a draggable divider separates the panes")647            let before = element("panel-watchlist").frame.width648            divider.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).press(forDuration: 0.2, thenDragTo: divider.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).withOffset(CGVector(dx: 120, dy: 0)))649            sleep(2)650            XCTAssertGreaterThan(element("panel-watchlist").frame.width, before + 40, "dragging the divider resizes the panes")651            shot("workspace-resized")652            XCUIDevice.shared.orientation = .portrait; sleep(2)653            XCTAssertTrue(element("panel-chart").exists, "the layout survives a rotation")654            shot("workspace-portrait")655            XCUIDevice.shared.orientation = .landscapeLeft656        }657    }658659    /// iPad: the same screens at a second window size (resized with the window's corner handle, as in Stage Manager).660    func testPadWindowSizes() throws {661        guard isPad else { throw XCTSkip("iPad seulement") }662        try launch(open: "vquant://research")663        XCTAssertTrue(element("research").waitForExistence(timeout: 20))664        sleep(2)665        shot("split-full")666        let window = app.windows.firstMatch667        let full = window.frame668        let corner = window.coordinate(withNormalizedOffset: CGVector(dx: 1, dy: 1)).withOffset(CGVector(dx: -6, dy: -6))669        corner.press(forDuration: 0.3, thenDragTo: window.coordinate(withNormalizedOffset: CGVector(dx: 0.74, dy: 0.96)))       // a medium window, still regular width670        sleep(2)671        let resized = app.windows.firstMatch.frame672        let note = XCTAttachment(string: "full \(full.size) → resized \(resized.size)"); note.name = "window-sizes"; note.lifetime = .keepAlways; add(note)673        print("WINDOW SIZES full \(full.size) resized \(resized.size)")674        shot("split-medium")675        XCTAssertTrue(element("research").exists || app.tabBars.firstMatch.exists, "the research screen is still usable at this size")676        if resized.width < full.width - 50 {677            app.windows.firstMatch.coordinate(withNormalizedOffset: CGVector(dx: 1, dy: 1)).withOffset(CGVector(dx: -6, dy: -6))678                .press(forDuration: 0.3, thenDragTo: app.windows.firstMatch.coordinate(withNormalizedOffset: CGVector(dx: 0.3, dy: 0.8)))               // down to a compact width679            sleep(2)680            shot("split-narrow")681        }682    }683684    /// ONE real autonomous study (model claude-sonnet-5-5, cost cap 3 USD) followed from the app: opt-in, it spends API credit.685    func testLiveResearchStudyIsFollowedToItsReport() throws {686        guard ProcessInfo.processInfo.environment["VQUANT_LIVE_RESEARCH"] == "1" else { throw XCTSkip("Étude réelle (coût d’API) : TEST_RUNNER_VQUANT_LIVE_RESEARCH=1 pour l’activer") }687        try launch()688        XCTAssertTrue(element("ask-field").waitForExistence(timeout: 20)); element("ask-field").tap()689        let text = element("composer-text")690        XCTAssertTrue(text.waitForExistence(timeout: 10)); text.tap()691        text.typeText("ios-test : estime la volatilité annualisée de SPY sur deux ans avec un EWMA (lambda 0,94) et un GARCH(1,1), compare les deux séries dans une seule figure, consigne l’expérience, et conclus en dix lignes au plus.")692        scrollTo("composer-model").tap()693        let sonnet = scrollTo("model-claude-sonnet-5-5")694        XCTAssertTrue(sonnet.waitForExistence(timeout: 20), "the model is in the server registry"); sonnet.tap()695        XCTAssertTrue(app.descendants(matching: .any).matching(NSPredicate(format: "label CONTAINS 'Modèle : ' AND NOT label CONTAINS 'défaut'")).firstMatch.waitForExistence(timeout: 8), "the chosen model is kept")696        let budget = scrollTo("composer-budget-cost")697        if (budget.value as? String) != "1" { budget.switches.firstMatch.exists ? budget.switches.firstMatch.tap() : budget.tap() }698        XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label CONTAINS '3,00'")).firstMatch.waitForExistence(timeout: 5), "the cost cap is 3 USD")699        shot("live-composer")700        app.buttons["composer-send"].tap()701        XCTAssertTrue(element("run").waitForExistence(timeout: 40), "the study view opens once the server created the job")702        shot("live-start")703        // follow it: every section while it runs, then the finished state704        let done = app.staticTexts["Terminée"].firstMatch705        var minute = 0706        while !done.exists && minute < 20 {707            sleep(45); minute += 1708            if minute == 2 || minute == 5 { for tab in ["activity", "code"] { let b = element("study-tab-\(tab)"); if b.exists { b.tap(); sleep(1); shot("live-\(tab)-\(minute)") } }; let r = element("study-tab-report"); if r.exists { r.tap() } }709            if element("study-approval").exists { shot("live-approval") }710        }711        XCTAssertTrue(done.waitForExistence(timeout: 30), "the study finishes within the time allowed")712        shot("live-report")713        for tab in ["activity", "code", "experiments", "figures", "files"] {714            let b = element("study-tab-\(tab)")715            if b.waitForExistence(timeout: 5) { if !b.isHittable { element("study-tab-experiments").swipeLeft(); usleep(600_000) }; b.tap(); sleep(2); shot("live-\(tab)") }716        }717        XCTAssertTrue(element("usage-line").exists || true)718    }719720    /// Cold-launch time to the first frame, measured by XCTest (simulator figures; a device must be measured separately).721    func testLaunchPerformance() throws {722        let env = ProcessInfo.processInfo.environment723        guard let token = env["VQUANT_TEST_TOKEN"], let url = env["VQUANT_BASE_URL"] else { throw XCTSkip("Pas de backend de test") }724        let options = XCTMeasureOptions(); options.iterationCount = 3725        measure(metrics: [XCTApplicationLaunchMetric()], options: options) {726            let a = XCUIApplication()727            a.launchEnvironment = ["VQUANT_UITEST": "1", "VQUANT_TEST_TOKEN": token, "VQUANT_BASE_URL": url]728            a.launch()729        }730    }731732    func testRotationKeepsTheSelectedScreen() throws {733        try launch()734        go("markets", title: "Marchés")735        XCTAssertTrue(element("markets").waitForExistence(timeout: 10))736        XCUIDevice.shared.orientation = isPad ? .portrait : .landscapeRight737        sleep(2)738        XCTAssertTrue(element("markets").exists, "markets still shown after rotation")739        shot("rotated")740        XCUIDevice.shared.orientation = isPad ? .landscapeLeft : .portrait741        sleep(1)742        XCTAssertTrue(element("markets").exists)743    }744}745
Files main
Menu

Theme