SPB Git

Repository Public

FuturesUITests.swift 22.6 KB 428 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : UITests/FuturesUITests.swift10// Description      : Interface tests of the perp terminal against the THROWAWAY11//                    local stack (random keys, every live lock at its default12//                    OFF, software passkey; market data read from the venue's13//                    public API). Markets and market page, a PAPER account end14//                    to end (create → order with an explicitly chosen leverage15//                    → position labelled PAPIER → close), the order button that16//                    stays disabled until a leverage is chosen, the extra17//                    confirmation from 5×, and the live section showing the18//                    server's locks honestly. No test opens a lock, approves a19//                    live authorization or sends an order to a venue.20// Module           : UITests21// Repository       : https://git.spboucher.ai/sp-wallet-ios22// Created          : 2026-11-1823// Last Modified    : 2026-11-1824//25// =============================================================================26// AUTHOR & PROFESSIONAL AFFILIATION27// =============================================================================28//29// Author           : Simon-Pierre Boucher30// Position         : Professor of Finance31// Institution      : Université du Québec en Outaouais (UQO)32// Department       : Département des sciences administratives33// Organization     : SP Boucher34//35// Website          : https://spboucher.ai36// Git              : https://git.spboucher.ai37//38// =============================================================================39// OFFICIAL CONTACT DIRECTORY40// =============================================================================41//42// General          : info@spboucher.ai43// Professional     : contact@spboucher.ai44// Direct           : simon@spboucher.ai45// Research         : research@spboucher.ai46// Development      : dev@spboucher.ai47// Support          : support@spboucher.ai48// Security/Admin   : admin@spboucher.ai49// Notifications    : notifications@spboucher.ai50//51// Preferred Contact: support@spboucher.ai52//53// =============================================================================54// COPYRIGHT & INTELLECTUAL PROPERTY55// =============================================================================56//57// Copyright (c) 202658// Simon-Pierre Boucher59//60// All rights reserved where applicable.61//62// This file is governed by the applicable project license,63// copyright notices, institutional agreements and relevant law.64//65// Unless expressly authorized by the applicable license or66// rights holder, copying, redistribution, sublicensing,67// publication and commercial exploitation are not permitted.68//69// Existing third-party rights and notices remain unaffected.70//71// =============================================================================72// CONFIDENTIALITY & SECURITY73// =============================================================================74//75// Classification   : Public76// Distribution     : Public repository; use is governed by the project license77// Security Contact : admin@spboucher.ai78//79// Access to this source does not independently grant permission80// to redistribute or disclose confidential materials.81//82// Do not embed credentials, private keys, access tokens,83// certificates or confidential personal information.84//85// =============================================================================86// LICENSE & MAINTENANCE87// =============================================================================88//89// License          : None specified (no license file in this repository)90// Maintainer       : Simon-Pierre Boucher91// Technical Contact: dev@spboucher.ai92//93// =============================================================================94// END OF SP BOUCHER SOURCE HEADER95// =============================================================================9697import XCTest9899@MainActor100final class FuturesUITests: XCTestCase {101    override func setUpWithError() throws {102        continueAfterFailure = false103        try XCTSkipUnless(Stack.isUp, "throwaway stack not running (../SPWalletCore/Scripts/dev-stack.sh up-fork)")104    }105106    // MARK: helpers107108    private func openFutures(_ app: XCUIApplication) {109        if isPad { go(app, "futures") } else {110            go(app, "explore")111            let link = app.descendants(matching: .any)["explore.futures"].firstMatch112            XCTAssertTrue(link.waitForExistence(timeout: 10)); link.tap()113        }114        XCTAssertTrue(app.descendants(matching: .any)["futures.mode.band"].firstMatch.waitForExistence(timeout: 15), "the mode band is on the terminal's first screen")115    }116117    private func any(_ app: XCUIApplication, _ id: String) -> XCUIElement { app.descendants(matching: .any)[id].firstMatch }118119    private func tab(_ app: XCUIApplication, _ title: String) {120        let b = app.segmentedControls["futures.tab"].buttons[title]121        XCTAssertTrue(b.waitForExistence(timeout: 10), "tab \(title)"); b.tap()122    }123124    private func type(_ app: XCUIApplication, _ id: String, _ text: String) {125        let f = app.textFields[id]126        XCTAssertTrue(f.waitForExistence(timeout: 10), "field \(id)")127        if !f.isHittable { app.swipeUp() }128        f.tap(); f.typeText(text)129        let done = app.buttons["futures.keyboardDone"]130        if done.exists { done.tap() }131    }132133    /** Scrolls until the element can be tapped (the keyboard or the fold may hide it). */134    private func reach(_ app: XCUIApplication, _ e: XCUIElement, file: StaticString = #filePath, line: UInt = #line) {135        XCTAssertTrue(e.waitForExistence(timeout: 15), "\(e)", file: file, line: line)136        var tries = 0137        while !e.isHittable, tries < 8 { app.swipeUp(velocity: .slow); tries += 1 }138    }139140    private func openMarket(_ app: XCUIApplication, _ symbol: String) {141        if !isPad { tab(app, "Marchés") }142        let row = app.buttons["futures.markets.row.\(symbol)"]143        XCTAssertTrue(row.waitForExistence(timeout: 60), "the venue's instruments are listed (public market data)")144        row.tap()145        XCTAssertTrue(any(app, "futures.market.mark").waitForExistence(timeout: 30))146    }147148    private func openTicket(_ app: XCUIApplication) {149        if isPad { tab(app, "Ordre") } else { let b = app.buttons["futures.market.order"]; XCTAssertTrue(b.waitForExistence(timeout: 10)); b.tap() }150        XCTAssertTrue(app.buttons["futures.order.side.long"].waitForExistence(timeout: 10))151    }152153    /** A paper account exists on the stack (created once; later tests reuse it). */154    private func ensurePaperAccount(_ app: XCUIApplication) {155        tab(app, "Compte")156        let create = app.buttons["futures.paper.create"]157        XCTAssertTrue(create.waitForExistence(timeout: 20))158        if app.buttons["futures.paper.account"].waitForExistence(timeout: 6) { return }159        create.tap()160        type(app, "futures.paper.new.label", "Essai UI")161        type(app, "futures.paper.new.collateral", "10000")162        let submit = app.buttons["futures.paper.new.submit"]163        reach(app, submit); XCTAssertTrue(submit.isEnabled); submit.tap()164        XCTAssertTrue(app.buttons["futures.paper.account"].waitForExistence(timeout: 20), "the paper account is listed after creation")165    }166167    private func fillMarketOrder(_ app: XCUIApplication, size: String) {168        app.buttons["futures.order.side.long"].tap()169        app.segmentedControls["futures.order.kind"].buttons["Marché"].tap()170        type(app, "futures.order.size", size)171        type(app, "futures.order.slippage", "50")172    }173174    // MARK: tests175176    func test1MarketsLoadAndTheMarketPageShowsChartBookAndSpecifications() {177        let app = signIn(Stack.app())178        openFutures(app)179        XCTAssertTrue(any(app, "futures.mode.band").label.contains("PAPIER"), "paper is the mode the terminal opens in")180        XCTAssertTrue(app.buttons["futures.markets.row.BTC"].waitForExistence(timeout: 60), "markets load from the venue")181        shot("futures-01-markets")182        let search = app.textFields["futures.markets.search"]183        search.tap(); search.typeText("ETH")184        XCTAssertTrue(app.buttons["futures.markets.row.ETH"].waitForExistence(timeout: 10))185        XCTAssertFalse(app.buttons["futures.markets.row.BTC"].exists, "the search narrows the list")186        shot("futures-02-search")187        app.buttons["futures.markets.row.ETH"].tap()188        XCTAssertTrue(any(app, "futures.market.mark").waitForExistence(timeout: 30))189        XCTAssertTrue(any(app, "futures.market.chart").waitForExistence(timeout: 40), "candles are drawn")190        sleep(3)191        shot("futures-03-market-chart")192        app.swipeUp()193        XCTAssertTrue(any(app, "futures.market.book").waitForExistence(timeout: 20) || any(app, "futures.market.bookUnavailable").exists, "a verified book, or the statement that there is none")194        shot("futures-04-market-book")195        app.swipeUp(); app.swipeUp()196        shot("futures-05-market-specs")197        XCTAssertTrue(app.staticTexts["Spécifications"].waitForExistence(timeout: 5))198    }199200    func test2PaperAccountOrderWithChosenLeveragePositionLabelledPaperThenClose() {201        let app = signIn(Stack.app())202        openFutures(app)203        ensurePaperAccount(app)204        shot("futures-10-paper-account")205        openMarket(app, "BTC")206        openTicket(app)207        fillMarketOrder(app, size: "0.01")208209        // no leverage chosen: neither the preview nor the order button can be used210        let submit = app.buttons["futures.order.submit"], preview = app.buttons["futures.order.preview"]211        reach(app, submit)212        XCTAssertFalse(submit.isEnabled, "the order button stays disabled until a leverage is chosen")213        XCTAssertFalse(preview.isEnabled)214        shot("futures-11-ticket-no-leverage")215216        type(app, "futures.order.leverage", "3")217        reach(app, preview); XCTAssertTrue(preview.isEnabled);218        XCTAssertFalse(submit.isEnabled, "still disabled before the server's preview")219        preview.tap()220        XCTAssertTrue(any(app, "futures.order.riskOk").waitForExistence(timeout: 30), "the server's risk engine accepted the previewed paper order")221        shot("futures-12-ticket-preview")222        reach(app, submit); XCTAssertTrue(submit.isEnabled); submit.tap()223        let state = any(app, "futures.paper.orderState")224        XCTAssertTrue(state.waitForExistence(timeout: 30), "the paper engine answered the order")225        XCTAssertTrue(state.label.contains("PAPIER"), state.label)226        shot("futures-13-paper-placed")227228        if !isPad { app.buttons["futures.order.close"].tap(); app.navigationBars.buttons.firstMatch.tap() }229        tab(app, "Positions")230        let position = any(app, "futures.position.close.BTC")231        XCTAssertTrue(position.waitForExistence(timeout: 30), "the position appears")232        XCTAssertTrue(app.staticTexts["PAPIER"].firstMatch.exists, "labelled PAPIER")233        shot("futures-14-paper-position")234235        reach(app, position); position.tap()236        let all = app.buttons["futures.close.pct.100"]237        XCTAssertTrue(all.waitForExistence(timeout: 10)); all.tap()238        type(app, "futures.close.slippage", "50")239        let close = app.buttons["futures.close.submit"]240        reach(app, close); XCTAssertTrue(close.isEnabled)241        shot("futures-15-close-form")242        close.tap()243        XCTAssertTrue(any(app, "futures.paper.orderState").waitForExistence(timeout: 30))244        shot("futures-16-close-result")245        app.buttons["futures.close.done"].tap()246        XCTAssertTrue(any(app, "futures.blotter.noPosition").waitForExistence(timeout: 30), "the position is gone after the close")247        shot("futures-17-paper-flat")248    }249250    func test3FromFiveTimesTheOrderNeedsAnExtraConfirmation() {251        let app = signIn(Stack.app())252        openFutures(app)253        ensurePaperAccount(app)254        // the paper account's own policy caps the leverage (3× as created by the server): 5× needs the owner to raise it first255        let edit = app.buttons["Modifier"].firstMatch256        reach(app, edit); edit.tap()257        let cap = app.textFields["futures.policy.maxLeverage"]258        XCTAssertTrue(cap.waitForExistence(timeout: 10), "the policy editor opens")259        cap.tap(); cap.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: 4) + "10")260        if app.buttons["futures.keyboardDone"].exists { app.buttons["futures.keyboardDone"].tap() }261        shot("futures-19-policy-editor")262        let save = app.buttons["futures.policy.save"]263        reach(app, save); XCTAssertTrue(save.isEnabled); save.tap()264        XCTAssertTrue(app.buttons["futures.paper.create"].waitForExistence(timeout: 20), "the policy was saved and the editor closed")265        openMarket(app, "BTC")266        openTicket(app)267        fillMarketOrder(app, size: "0.001")268        type(app, "futures.order.leverage", "5")269        let preview = app.buttons["futures.order.preview"]270        reach(app, preview); XCTAssertTrue(preview.isEnabled); preview.tap()271        XCTAssertTrue(any(app, "futures.order.riskOk").waitForExistence(timeout: 30) || any(app, "futures.order.riskRefused").exists, "the server answered the preview")272        let confirm = app.buttons["futures.order.highConfirm"], submit = app.buttons["futures.order.submit"]273        reach(app, confirm)274        reach(app, submit)275        XCTAssertFalse(submit.isEnabled, "5× is not placed without the explicit confirmation")276        shot("futures-20-high-leverage")277        reach(app, confirm); confirm.tap()278        if any(app, "futures.order.riskOk").exists { XCTAssertTrue(submit.isEnabled) }279        shot("futures-21-high-leverage-confirmed")280    }281282    func test4TheLiveSectionShowsTheLocksHonestlyAndCreatesOnlyAReadOnlyAccount() {283        let app = signIn(Stack.app())284        openFutures(app)285        app.segmentedControls["futures.mode"].buttons.element(boundBy: 1).tap()286        XCTAssertTrue(any(app, "futures.mode.band").label.contains("RÉEL"))287        tab(app, "Compte")288        let lock = any(app, "futures.lock.mainnet")289        XCTAssertTrue(lock.waitForExistence(timeout: 30), "the server's locks are displayed")290        XCTAssertTrue(lock.label.contains("verrou serveur fermé"), "mainnet is closed on the throwaway stack and the screen says so: \(lock.label)")291        shot("futures-30-live-locks")292293        // a mainnet account while the lock is closed: whatever the server answers is shown, nothing is worked around294        let create = app.buttons["futures.live.create"]295        reach(app, create); create.tap()296        let submit = app.buttons["futures.live.new.submit"]297        XCTAssertTrue(submit.waitForExistence(timeout: 10))298        XCTAssertFalse(submit.isEnabled, "no network is preselected")299        if app.buttons["futures.live.new.network.testnet"].exists {300            app.buttons["futures.live.new.network.testnet"].tap()301            type(app, "futures.live.new.label", "Essai lecture seule")302            reach(app, submit); submit.tap()303            let created = app.buttons["futures.live.account.testnet"]304            let failed = any(app, "futures.live.new.error")305            XCTAssertTrue(created.waitForExistence(timeout: 30) || failed.exists, "the account is listed, or the server's refusal is shown")306            shot("futures-31-live-created")307            if failed.exists { app.buttons["futures.live.new.cancel"].tap() }308        } else { app.buttons["futures.live.new.cancel"].tap() }309310        if app.buttons["futures.live.account.testnet"].waitForExistence(timeout: 5) {311            let state = any(app, "futures.live.state")312            reach(app, state)313            XCTAssertTrue(state.label.contains("LECTURE SEULE"), "a new account is read-only: \(state.label)")314            XCTAssertTrue(any(app, "futures.mode.band").label.contains("TESTNET") || app.staticTexts["TESTNET"].firstMatch.exists)315            shot("futures-32-live-read-only")316            app.swipeUp(); shot("futures-33-live-account-more")317            app.swipeUp(); shot("futures-34-live-account-collateral")318        }319    }320321    func test5AuthorizationFormPreselectsNothingAndItsReviewIsNeverApprovedHere() throws {322        let app = signIn(Stack.app())323        openFutures(app)324        app.segmentedControls["futures.mode"].buttons.element(boundBy: 1).tap()325        tab(app, "Compte")326        try XCTSkipUnless(app.buttons["futures.live.account.testnet"].waitForExistence(timeout: 20), "needs the read-only testnet account of the previous test")327        let authorize = app.buttons["futures.live.authorize"]328        reach(app, authorize); authorize.tap()329        let prepare = app.buttons["futures.auth.prepare"]330        XCTAssertTrue(app.textFields["futures.auth.search"].waitForExistence(timeout: 10))331        for id in ["futures.auth.maxLeverage", "futures.auth.maxOrder", "futures.auth.maxPosition", "futures.auth.maxGross", "futures.auth.ordersPerDay", "futures.auth.deviation", "futures.auth.days"] {332            let f = app.textFields[id]333            reach(app, f)334            XCTAssertTrue((f.value as? String ?? "") == "à saisir" || (f.value as? String ?? "").isEmpty, "\(id) starts empty: \(String(describing: f.value))")335        }336        reach(app, prepare)337        XCTAssertFalse(prepare.isEnabled, "nothing typed, nothing prepared")338        shot("futures-40-authorization-empty")339        app.swipeDown(); app.swipeDown(); app.swipeDown()340        type(app, "futures.auth.search", "BTC")341        let btc = app.buttons["futures.auth.instrument.BTC"]342        XCTAssertTrue(btc.waitForExistence(timeout: 10)); btc.tap()343        type(app, "futures.auth.maxLeverage", "2")344        type(app, "futures.auth.maxOrder", "100")345        type(app, "futures.auth.maxPosition", "200")346        type(app, "futures.auth.maxGross", "300")347        type(app, "futures.auth.ordersPerDay", "10")348        type(app, "futures.auth.deviation", "200")349        type(app, "futures.auth.days", "1")350        reach(app, prepare); XCTAssertTrue(prepare.isEnabled)351        shot("futures-41-authorization-typed")352        prepare.tap()353        let review = any(app, "futures.auth.review.title"), refused = any(app, "futures.auth.error")354        XCTAssertTrue(review.waitForExistence(timeout: 40) || refused.exists, "the verified authorization is shown for review, or the server's refusal is")355        shot("futures-42-authorization-review-or-refusal")356        if review.exists {357            let approve = app.buttons["futures.auth.approve"]358            reach(app, approve)359            XCTAssertFalse(approve.isEnabled, "the passkey is not offered before the acknowledgement checkbox is ticked")360            shot("futures-43-authorization-ack")361            // never approved in a test: approving would sign an agent approval for a venue362            let decline = app.buttons["futures.auth.decline"]363            reach(app, decline); decline.tap()364        } else { app.buttons["futures.auth.cancel"].tap() }365    }366367    func test6LiveTicketLeverageCollateralAndResumeSheetsOpenAndTheServerRefusesAReadOnlyAccount() throws {368        let app = signIn(Stack.app())369        openFutures(app)370        app.segmentedControls["futures.mode"].buttons.element(boundBy: 1).tap()371        tab(app, "Compte")372        try XCTSkipUnless(app.buttons["futures.live.account.testnet"].waitForExistence(timeout: 20), "needs the read-only testnet account of test 4")373374        // collateral: the sheet opens, nothing is pre-filled, nothing is prepared375        let withdraw = app.buttons["futures.collateral.withdraw"]376        reach(app, withdraw)377        if withdraw.isEnabled {378            withdraw.tap()379            XCTAssertTrue(app.textFields["futures.collateral.amount"].waitForExistence(timeout: 10), "the collateral sheet opens")380            XCTAssertFalse(app.buttons["futures.collateral.prepare"].isEnabled, "no amount typed, nothing prepared")381            shot("futures-50-collateral-sheet")382            app.buttons["futures.collateral.close"].tap()383        }384385        // halting needs no passkey; lifting the halt opens the risk review (or shows why the server will not prepare one)386        let halt = app.buttons["futures.live.halt"]387        reach(app, halt)388        if halt.isEnabled {389            halt.tap()390            let confirm = app.buttons["Arrêter les nouveaux ordres"].firstMatch391            XCTAssertTrue(confirm.waitForExistence(timeout: 5)); confirm.tap()392        }393        let resume = app.buttons["futures.live.resume"]394        XCTAssertTrue(resume.waitForExistence(timeout: 20), "the account is halted without any passkey")395        reach(app, resume); resume.tap()396        XCTAssertTrue(app.navigationBars["Lever l’arrêt"].waitForExistence(timeout: 10), "the resume sheet opens")397        sleep(3)398        shot("futures-51-resume-sheet")399        app.navigationBars["Lever l’arrêt"].buttons.firstMatch.tap()400401        // the order ticket on a real (testnet, read-only) account: the leverage sheet opens; the server's refusal is shown as is402        openMarket(app, "BTC")403        openTicket(app)404        XCTAssertTrue(any(app, "futures.mode.band").label.contains("TESTNET"), "RÉEL · TESTNET is stated on the ticket")405        app.buttons["futures.order.side.long"].tap()406        XCTAssertTrue(app.buttons["futures.order.side.long"].isSelected, "the side is chosen by the owner")407        type(app, "futures.order.size", "0.001")408        type(app, "futures.order.price", "50000")409        let change = app.buttons["futures.order.leverage.change"]410        reach(app, change); change.tap()411        XCTAssertTrue(app.textFields["futures.leverage.value"].waitForExistence(timeout: 10), "the leverage sheet opens")412        XCTAssertFalse(app.buttons["futures.leverage.prepare"].isEnabled, "no leverage and no margin mode are preselected")413        shot("futures-52-leverage-sheet")414        app.buttons["futures.leverage.close"].tap()415        XCTAssertTrue(app.textFields["futures.leverage.value"].waitForNonExistence(timeout: 10))416        sleep(1)   // let the sheet's dismissal animation end417        let preview = app.buttons["futures.order.preview"], submit = app.buttons["futures.order.submit"]418        reach(app, preview); XCTAssertTrue(preview.isEnabled); preview.tap()419        let answered = any(app, "futures.order.error").waitForExistence(timeout: 20) || any(app, "futures.order.riskRefused").exists || any(app, "futures.order.riskOk").exists420        app.swipeUp(velocity: .slow)421        shot("futures-53-live-ticket-preview")422        XCTAssertTrue(answered, "the server answered the preview")423        reach(app, submit)424        XCTAssertFalse(submit.isEnabled, "nothing can be proposed on a read-only account without a chosen leverage")425        shot("futures-54-live-ticket-refused")426    }427}428
Files main
Menu

Theme