SPB Git

Repository Public

AlertsResearchTests.swift 29.5 KB 478 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : Tests/AlertsResearchTests.swift10// Description      : Logic of the alerts / notifications / background refresh /11//                    research screens: a row is notified at most once per12//                    device, which kinds notify, the lock-screen text never13//                    carries an amount or an address (checked over the whole14//                    catalogue), severity → interruption level, provenance15//                    labels never merge, the background pass does nothing when16//                    signed out and never wipes on a 401. Fakes are injected17//                    through the small protocols of Core/System.18// Module           : Tests19// Repository       : https://git.spboucher.ai/sp-wallet-ios20// Created          : 2026-11-1821// Last Modified    : 2026-11-1822//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author           : Simon-Pierre Boucher28// Position         : Professor of Finance29// Institution      : Université du Québec en Outaouais (UQO)30// Department       : Département des sciences administratives31// Organization     : SP Boucher32//33// Website          : https://spboucher.ai34// Git              : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General          : info@spboucher.ai41// Professional     : contact@spboucher.ai42// Direct           : simon@spboucher.ai43// Research         : research@spboucher.ai44// Development      : dev@spboucher.ai45// Support          : support@spboucher.ai46// Security/Admin   : admin@spboucher.ai47// Notifications    : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification   : Public74// Distribution     : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License          : None specified (no license file in this repository)88// Maintainer       : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import Foundation96import Testing97import SPWalletCore98@testable import SPWallet99100// MARK: fakes101102private func decode<T: Decodable>(_ json: String, as: T.Type = T.self) -> T { try! APICoding.decoder().decode(T.self, from: Data(json.utf8)) }103104private func alertJSON(id: Int64, kind: String = "transfer.confirmed", severity: String = "info", group: String = "transfers", ageSec: Double = 5, read: Bool = false, delivery: String = "inapp", params: String = #"{"network":"Base","symbol":"ETH","amount":"0.001","count":1}"#) -> String {105    let ts = Int64((Date().timeIntervalSince1970 - ageSec) * 1000)106    return #"{"id":\#(id),"ts":\#(ts),"kind":"\#(kind)","severity":"\#(severity)","group":"\#(group)","params":\#(params),"subject":{"type":"proposal","id":"p1","network":"base"},"count":1,"readAt":\#(read ? String(ts) : "null"),"delivery":"\#(delivery)","channels":{}}"#107}108private func alert(id: Int64, kind: String = "transfer.confirmed", severity: String = "info", group: String = "transfers", ageSec: Double = 5, read: Bool = false, delivery: String = "inapp") -> WalletAlert {109    decode(alertJSON(id: id, kind: kind, severity: severity, group: group, ageSec: ageSec, read: read, delivery: delivery))110}111112/** A scripted server: the rows it holds; counters and pages are derived from them like the real routes do. */113private final class FakeAlertServer: AlertSource, @unchecked Sendable {114    private let lock = NSLock()115    private var rows: [String] = []116    private var ids: [Int64] = []117    private(set) var listCalls = 0118    private(set) var unreadCalls = 0119    var failWith: APIError?120121    func add(_ id: Int64, kind: String = "transfer.confirmed", severity: String = "info", ageSec: Double = 5, read: Bool = false, delivery: String = "inapp") {122        lock.withLock { rows.insert(alertJSON(id: id, kind: kind, severity: severity, ageSec: ageSec, read: read, delivery: delivery), at: 0); ids.append(id) }123    }124    private func countersJSON() -> String {125        let items: [WalletAlert] = rows.map { decode($0) }126        return #""unread":\#(items.filter { !$0.isRead }.count),"critical":\#(items.filter { !$0.isRead && $0.severity == .critical }.count),"lastId":\#(ids.max() ?? 0)"#127    }128    func unread() async throws -> AlertUnread {129        try lock.withLock { unreadCalls += 1; if let failWith { throw failWith }; return decode("{\(countersJSON())}") }130    }131    func list(_ q: AlertListQuery) async throws -> AlertPage {132        try lock.withLock {133            listCalls += 1134            if let failWith { throw failWith }135            let kept = rows.filter { !q.unreadOnly || !(decode($0) as WalletAlert).isRead }136            return decode("{\"items\":[\(kept.joined(separator: ","))],\(countersJSON())}")137        }138    }139}140141@MainActor private final class MemorySeen: AlertSeenStore { var lastSeenId: Int64? }142143@MainActor private final class RecordingNotifier: AlertNotifying {144    var notified: [Int64] = []145    var badges: [Int] = []146    func notify(_ rows: [WalletAlert]) async { notified += rows.map(\.id) }147    func setBadge(_ unread: Int) async { badges.append(unread) }148}149150@MainActor private final class RecordingPoster: NotificationPosting {151    var authorized = true152    var posted: [AlertNotificationPolicy.Content] = []153    var badges: [Int] = []154    func isAuthorized() async -> Bool { authorized }155    func post(_ c: AlertNotificationPolicy.Content) async { posted.append(c) }156    func setBadge(_ n: Int) async { badges.append(n) }157}158159@MainActor private final class Switch { var on = false }160161// MARK: at most once162163@MainActor @Suite struct AlertSyncTests {164    @Test func firstContactIsABaselineAndNotifiesNothing() async throws {165        let server = FakeAlertServer(), seen = MemorySeen(), notifier = RecordingNotifier()166        server.add(1); server.add(2)167        let r = try await AlertSync(source: server, seen: seen, notifier: notifier).pass()168        #expect(notifier.notified.isEmpty, "history that predates this device is never notified")169        #expect(seen.lastSeenId == 2 && r.counters.unread == 2 && r.fresh.isEmpty)170        #expect(notifier.badges.last == 2)171    }172173    @Test func aNewRowIsNotifiedOnceAndNeverAgain() async throws {174        let server = FakeAlertServer(), seen = MemorySeen(), notifier = RecordingNotifier()175        server.add(1)176        let sync = AlertSync(source: server, seen: seen, notifier: notifier)177        _ = try await sync.pass()178        server.add(2); server.add(3)179        let r = try await sync.pass()180        #expect(notifier.notified == [2, 3] && r.fresh.count == 2)181        _ = try await sync.pass()182        _ = try await sync.pass(forceRows: true) // a forced re-read of the same rows must not notify them again183        #expect(notifier.notified == [2, 3])184        // another AlertSync on the same device store (the background pass) does not notify them either185        _ = try await AlertSync(source: server, seen: seen, notifier: notifier).pass(forceRows: true)186        #expect(notifier.notified == [2, 3])187    }188189    @Test func unchangedLastIdCostsOneRequestOnly() async throws {190        let server = FakeAlertServer(), seen = MemorySeen()191        let sync = AlertSync(source: server, seen: seen, notifier: nil)192        _ = try await sync.pass()193        let lists = server.listCalls194        _ = try await sync.pass(); _ = try await sync.pass()195        #expect(server.listCalls == lists, "no list fetch while lastId did not move")196    }197198    @Test func rowsAlreadyReadOrTooOldAreNotNews() async throws {199        let server = FakeAlertServer(), seen = MemorySeen(), notifier = RecordingNotifier()200        let sync = AlertSync(source: server, seen: seen, notifier: notifier)201        _ = try await sync.pass()202        server.add(1, read: true); server.add(2, ageSec: 7200); server.add(3)203        _ = try await sync.pass()204        #expect(notifier.notified == [3])205        #expect(seen.lastSeenId == 3, "skipped rows are still behind the watermark: they will not come back later")206    }207208    @Test func aFailedPassLeavesTheWatermarkAlone() async throws {209        let server = FakeAlertServer(), seen = MemorySeen(), notifier = RecordingNotifier()210        let sync = AlertSync(source: server, seen: seen, notifier: notifier)211        _ = try await sync.pass()212        server.add(1)213        server.failWith = APIError(status: 0, code: "offline", message: "offline")214        await #expect(throws: APIError.self) { _ = try await sync.pass() }215        #expect(seen.lastSeenId == 0 && notifier.notified.isEmpty)216        server.failWith = nil217        _ = try await sync.pass()218        #expect(notifier.notified == [1])219    }220221    @Test func centerExposesTheServersCountAndHighestSeverity() async {222        let server = FakeAlertServer(), seen = MemorySeen()223        var changes = 0224        let center = AlertCenter(source: server, seen: seen, notifier: nil, eligible: { true }, onChange: { changes += 1 })225        #expect(center.widgetFields().unreadAlerts == nil, "nothing read yet: no number, not zero")226        server.add(1, kind: "transfer.failed", severity: "warning")227        await center.poll()228        #expect(center.counters?.unread == 1 && center.highestUnreadSeverity == .warning && center.widgetFields().criticalAlert == nil)229        server.add(2, kind: "security.signer_halted", severity: "critical")230        await center.poll()231        #expect(center.highestUnreadSeverity == .critical)232        #expect(center.widgetFields().unreadAlerts == 2 && center.widgetFields().criticalAlert == "Signataire à l’arrêt" || center.widgetFields().criticalAlert == "Signer halted")233        #expect(changes >= 2)234        server.failWith = APIError(status: 0, code: "offline", message: "offline")235        #expect(await center.poll() == false)236        #expect(center.counters?.unread == 2, "a failed poll keeps the last server figures; it does not zero them")237        center.reset()238        #expect(center.counters == nil && seen.lastSeenId == nil)239    }240}241242// MARK: which kinds notify, with what text243244@MainActor @Suite struct AlertNotificationPolicyTests {245    @Test func kindsOfTheBriefNotifyAndTheOthersStayInApp() {246        typealias P = AlertNotificationPolicy247        #expect(P.category(.transferConfirmed) == .transaction && P.category(.transferFailed) == .transaction && P.category(.swapFailed) == .transaction && P.category(.bridgeConfirmed) == .transaction)248        #expect(P.category(.agentOrderFilled) == .order && P.category(.derivLiveFilled) == .order)249        #expect(P.category(.derivLiveLiquidation) == .liquidation)250        #expect(P.category(.derivLossLimit) == .riskLimit)251        #expect(P.category(.securitySignerRefused) == .signingError)252        #expect(P.category(.agentStopped) == .agentStopped && P.category(.agentStoppedLoss) == .agentStopped)253        #expect(P.category(.securitySignerUnreachable) == .signerState && P.category(.securitySignerHalted) == .signerState && P.category(.securityKillSwitchOn) == .signerState)254        // simulated events, housekeeping and anything unknown stay in the app255        for k: AlertKind in [.derivPaperFilled, .derivPaperLiquidation, .depositReceived, .systemApiRestarted, .systemTest, .connDown, .agentResearchSubmitted, .unknown("portfolio.large_move")] { #expect(P.category(k) == nil, "\(k)") }256        for c in P.Category.allCases { #expect(AlertKind.allKnown.contains { P.category($0) == c }, "category \(c) has a kind") }257        // every notifying kind has a lock-screen wording in the catalogue258        for k in AlertKind.allKnown where P.category(k) != nil { #expect(AlertCatalog.definition(k)?.priv != nil, "\(k)") }259    }260261    @Test func severityMapsToInterruptionLevelAndNeverToCritical() {262        #expect(AlertNotificationPolicy.level(.critical) == .timeSensitive)263        #expect(AlertNotificationPolicy.level(.warning) == .active && AlertNotificationPolicy.level(.info) == .active && AlertNotificationPolicy.level(.unknown("x")) == .active)264        #expect(AlertSeverity.critical.tone == .danger && AlertSeverity.warning.tone == .warn && AlertSeverity.info.tone == .info && AlertSeverity.unknown("odd").word == "odd")265        #expect(Set([AlertSeverity.info, .warning, .critical].map(\.symbol)).count == 3 && Set([AlertSeverity.info, .warning, .critical].map(\.word)).count == 3)266    }267268    /** Property over the whole catalogue: whatever the unsafe parameters contain, none of it reaches the notification. */269    @Test func lockScreenTextCarriesNoAmountAddressOrReason() {270        func placeholders(_ t: String) -> [String] { t.matches(of: /\{([a-zA-Z]+)\}/).map { String($0.1) } }271        var checked = 0272        for def in AlertCatalog.definitions {273            let keys = Set((def.body + (def.priv ?? [])).flatMap(placeholders)).union(["amount", "symbol", "reason", "from", "address", "price", "txid"])274            var params = ""275            for (i, k) in keys.sorted().enumerated() {276                let safe = AlertCatalog.safeParams.contains(k)277                params += (i > 0 ? "," : "") + "\"\(k)\":\"" + (safe ? "safe\(i)" : "LEAK-\(k)-0xDeadBeef00000000000000000000000000001234-987654.321") + "\""278            }279            let a: WalletAlert = decode(alertJSON(id: 9, kind: def.kind.rawValue, severity: def.severity.rawValue, group: def.group.rawValue, params: "{\(params)}"))280            for locale in AlertLocale.allCases {281                let t = a.text(locale: locale, detail: false)282                for s in [t.title, t.body] { #expect(!s.contains("LEAK") && !s.contains("0xDeadBeef") && !s.contains("987654"), "\(def.kind) \(locale): \(s)") }283                if let c = AlertNotificationPolicy.content(for: a, locale: locale) {284                    checked += 1285                    #expect(!c.title.contains("LEAK") && !c.body.contains("LEAK") && !c.body.contains("0x") && !c.body.contains("987654"), "\(def.kind): \(c.body)")286                    #expect(c.title == t.title && c.body == t.body && c.identifier == "alert-9")287                }288            }289        }290        #expect(checked >= 40, "every notifying kind was checked in both languages (\(checked))")291        // and the detailed wording does contain them: the test would notice a catalogue that stopped using its parameters292        let d: WalletAlert = decode(alertJSON(id: 1, params: #"{"network":"Base","symbol":"ETH","amount":"987654.321"}"#))293        #expect(d.text(locale: .fr, detail: true).body.contains("987654.321"))294    }295296    @Test func serviceNotifiesOnlyWithTheSwitchAndThePermission() async {297        let poster = RecordingPoster()298        let sw = Switch()299        let service = NotificationService(enabled: { sw.on }, poster: poster, locale: { .fr })300        let rows = [alert(id: 1), alert(id: 2, kind: "deposit.received"), alert(id: 3, kind: "security.signer_halted", severity: "critical", group: "security"), alert(id: 4, delivery: "quiet"), alert(id: 5, read: true)]301        await service.notify(rows); await service.setBadge(3)302        #expect(poster.posted.isEmpty && poster.badges.isEmpty, "switch off: nothing")303        sw.on = true; poster.authorized = false304        await service.notify(rows)305        #expect(poster.posted.isEmpty, "permission refused: nothing")306        poster.authorized = true307        await service.notify(rows); await service.setBadge(3)308        #expect(poster.posted.map(\.alertId) == [1, 3], "the in-app kind, the row held back by the server's quiet hours and the read row do not notify")309        #expect(poster.posted[0].title == "Transfert confirmé" && poster.posted[0].body == "Sur Base." && poster.posted[0].level == .active)310        #expect(poster.posted[1].level == .timeSensitive && poster.posted[1].category == .signerState)311        #expect(poster.badges == [3])312    }313314    @Test func catalogPathsLandOnNativeSections() {315        typealias A = AlertPresentation316        #expect(A.destination(path: "/activity") == .section(.activity) && A.destination(path: "/agents/abc") == .section(.agents) && A.destination(path: "/agents") == .section(.agents))317        #expect(A.destination(path: "/futures?v=accounts") == .section(.futures) && A.destination(path: "/security") == .section(.security) && A.destination(path: "/plan/x") == .section(.swap))318        #expect(A.destination(path: "/monitor") == .systemState && A.destination(path: "/alerts") == A.Destination.none && A.destination(path: "/whatever") == A.Destination.none)319        #expect(A.destination(alert(id: 1)) == .section(.activity))320        for k in AlertKind.allKnown { _ = A.destination(path: AlertCatalog.path(kind: k, subject: nil)) } // total: never traps321    }322323    @Test func settingsInputsAreValidatedBeforeAnythingIsSent() {324        #expect(NumberSettingRow.parse("60", range: 1...500, integer: true) == 60 && NumberSettingRow.parse("0", range: 1...500, integer: true) == nil && NumberSettingRow.parse("2,5", range: 1...50, integer: false) == 2.5)325        #expect(NumberSettingRow.parse("2.5", range: 1...500, integer: true) == nil && NumberSettingRow.parse("", range: 1...5, integer: true) == nil && NumberSettingRow.parse("abc", range: 1...5, integer: true) == nil)326        #expect(AlertTime.date("22:30").map { AlertTime.text($0) } == "22:30" && AlertTime.date("24:00") == nil && AlertTime.date("x") == nil)327        #expect(WebhookSection.urlProblem("https://example.org/hook") == nil && WebhookSection.urlProblem("http://example.org") != nil && WebhookSection.urlProblem("") == nil)328    }329}330331// MARK: background pass332333@MainActor @Suite struct BackgroundRefreshTests {334    @Test func signedOutDoesNothingAtAll() async {335        var alerts = 0, portfolio = 0, rescheduled = 0336        let o = await BackgroundRefresh.run(hasToken: { false }, alerts: { alerts += 1; throw CancellationError() }, refreshPortfolio: { portfolio += 1 }, reschedule: { rescheduled += 1 })337        #expect(o == .signedOut && alerts == 0 && portfolio == 0 && rescheduled == 0)338    }339340    @Test func signedInDoesOnePassAndReschedules() async {341        let server = FakeAlertServer(), seen = MemorySeen(), notifier = RecordingNotifier()342        let sync = AlertSync(source: server, seen: seen, notifier: notifier)343        _ = try? await sync.pass()344        server.add(1)345        var portfolio = 0, rescheduled = 0346        let o = await BackgroundRefresh.run(hasToken: { true }, alerts: { try await sync.pass() }, refreshPortfolio: { portfolio += 1 }, reschedule: { rescheduled += 1 })347        #expect(o == .completed(newAlerts: 1) && portfolio == 1 && rescheduled == 1 && notifier.notified == [1] && server.unreadCalls == 2)348    }349350    @Test func aRefusedSessionStopsThePassWithoutTouchingData() async {351        var portfolio = 0352        let o = await BackgroundRefresh.run(hasToken: { true }, alerts: { throw APIError(status: 401, code: "unauthenticated", message: "no") }, refreshPortfolio: { portfolio += 1 }, reschedule: {})353        #expect(o == .sessionRefused && portfolio == 0, "no portfolio read, no wipe: the pass only stops")354        let off = await BackgroundRefresh.run(hasToken: { true }, alerts: { throw APIError(status: 0, code: "offline", message: "x") }, refreshPortfolio: { portfolio += 1 }, reschedule: {})355        #expect(off == .unreachable && portfolio == 0)356    }357358    @Test func thePassGivesUpWithinItsBudget() async {359        let server = FakeAlertServer(), sync = AlertSync(source: server, seen: MemorySeen(), notifier: nil)360        let started = Date()361        let o = await BackgroundRefresh.run(hasToken: { true }, alerts: { try await Task.sleep(for: .seconds(20)); return try await sync.pass() }, refreshPortfolio: {}, budget: .milliseconds(150), reschedule: {})362        #expect(o == .expired && Date().timeIntervalSince(started) < 5)363        #expect(BackgroundRefresh.identifier == "ai.spboucher.spwallet.ios.refresh" && BackgroundRefresh.earliest >= 1800 && BackgroundRefresh.budget < .seconds(30))364        #expect((Bundle.main.object(forInfoDictionaryKey: "BGTaskSchedulerPermittedIdentifiers") as? [String])?.contains(BackgroundRefresh.identifier) == true)365    }366}367368// MARK: research369370private func prov(_ n: ResearchNature, _ a: ResearchAuthor) -> ResearchProvenance { decode(#"{"nature":"\#(n.rawValue)","author":"\#(a.rawValue)"}"#) }371372private let researchDetailJSON = #"""373{"id":"9a1b2c3d-0000-4000-8000-000000000002","agentId":null,"kind":"spot","mission":"Find a momentum rule on BTC","universe":["BTC"],"interval":"4h","capitalUsd":5000,374 "budgets":{"wallSeconds":3600,"maxTrials":200,"maxDiskMb":512,"maxModelTokens":5000000,"maxModelUsd":10},"tools":["Read","Bash"],"state":"submitted","reason":null,"strategy":"job-x/1",375 "cancelRequested":false,"createdAt":1795000000000,376 "usage":{"wallMs":120000,"trials":33,"diskMb":4.2,"modelTokens":900000,"modelRequests":41,"modelUsd":1.25,"ledgerTampered":false,"sandbox":"sandbox-exec","agent":"claude","labCommit":"abc","exitCode":0,"signal":null},377 "holdout":{"start":"2025-01-01","devEnd":"2026-06-01","end":"2026-11-01","devBars":3000,"testBars":900},378 "submission":{"sha256":"aa11","files":{"README.md":"See [the docs](https://evil.example/x) and **trust me**","strategy.py":"print(1)"},"claims":{"train":{"total_return":0.9,"sharpe":3.1,"max_drawdown":-0.05,"trades":40},"summary":"Sharpe 3.1, visit https://evil.example"}},379 "server":{"status":"ok","deflatedSharpe":0.412,"sharpeCi":[-0.3,null],"metrics":{"test":{"total_return":-0.02,"sharpe":-0.1,"max_drawdown":-0.2,"trades":12}},380   "comparison":[{"split":"train","metric":"sharpe","claimed":3.1,"measured":0.4,"differs":true},{"split":"train","metric":"total_return","claimed":0.9,"measured":null,"differs":true}],"claimsDiffer":true},381 "report":{"metrics":{"test":{"sharpe":-0.1}},"equity_curve":[[1780272000,5000],["2026-06-01T04:00:00+00:00",4990.5],["bad",1],[1780300800,"x"]]}}382"""#383384@MainActor @Suite struct ResearchPresentationTests {385    let detail: ResearchJobDetail = decode(researchDetailJSON)386387    @Test func everySectionHasExactlyOneNatureAndTheFourLabelsAreDistinct() {388        let sections = ResearchSections.build(detail)389        #expect(sections.map(\.kind) == [.holdout, .usage, .submission, .serverSimulation, .serverEstimate, .comparison, .labReport])390        let by = Dictionary(uniqueKeysWithValues: sections.map { ($0.kind, $0.provenance) })391        #expect(by[.holdout] == prov(.observedData, .server))392        #expect(by[.usage] == prov(.observedData, .runner))393        #expect(by[.submission] == prov(.generatedAnalysis, .agent))394        #expect(by[.serverSimulation] == prov(.simulation, .server))395        #expect(by[.serverEstimate] == prov(.estimate, .server), "the statistics are not under the simulation's badge")396        #expect(by[.labReport] == prov(.simulation, .server))397        #expect(by[.comparison] == .some(nil), "the comparison carries two provenances side by side, not one")398        #expect(Set(sections.map(\.title)).count == sections.count)399        #expect(Set(ResearchNature.allCases.map(ResearchLabels.nature)).count == 4 && Set(ResearchAuthor.allCases.map(ResearchLabels.author)).count == 3)400        #expect(ResearchLabels.nature(.generatedAnalysis) == "ANALYSE GÉNÉRÉE" || ResearchLabels.nature(.generatedAnalysis) == "GENERATED ANALYSIS")401        #expect(ResearchLabels.claimed != ResearchLabels.measured)402    }403404    @Test func claimedAndMeasuredStayTwoCells() throws {405        let rows = ResearchSections.comparison(try #require(detail.server?.comparison))406        #expect(rows.count == 2 && rows[0].differs)407        #expect(rows[0].claimed != rows[0].measured && rows[0].claimed.contains("3") && rows[0].measured.contains("0"))408        #expect(rows[1].claimed.contains("90") && rows[1].measured == ResearchLabels.value(nil, metric: "total_return"), "a missing measurement is said, never replaced by the claim or by 0")409        #expect(!rows[1].measured.contains("0"))410    }411412    @Test func aJobWithoutAnswerHasNoResultSection() {413        let queued: ResearchJobDetail = decode(#"{"id":"j","agentId":null,"kind":"spot","mission":"0123456789","universe":["BTC"],"interval":"1h","capitalUsd":1000,"budgets":{"wallSeconds":60,"maxTrials":1,"maxDiskMb":16,"maxModelTokens":10000,"maxModelUsd":1},"tools":[],"state":"queued","strategy":"s/1","cancelRequested":false,"createdAt":1795000000000}"#)414        #expect(ResearchSections.build(queued).isEmpty && queued.job.state.isCancellable)415        #expect(ResearchLabels.state(.submitted).0 != ResearchLabels.state(.queued).0 && ResearchLabels.state(.unknown("weird")).0 == "weird")416    }417418    @Test func equityCurveKeepsOnlyWellFormedPoints() {419        let pts = ResearchSections.equity(detail.report?.equityCurve)420        #expect(pts.count == 2 && pts[0].value == 5000 && pts[1].value == 4990.5)421        #expect(pts[0].date == Date(timeIntervalSince1970: 1780272000))422        #expect(ResearchSections.equity(nil).isEmpty && ResearchSections.equity(.string("x")).isEmpty)423    }424425    @Test func generatedTextHasNoLiveLink() throws {426        let readme = try #require(detail.submission?.files["README.md"])427        let a = ResearchText.render(readme)428        #expect(a.runs.allSatisfy { $0.link == nil })429        let plain = String(a.characters)430        #expect(plain.contains("the docs (https://evil.example/x)") && plain.contains("trust me") && !plain.contains("**"))431        #expect(ResearchText.render("plain https://evil.example text").runs.allSatisfy { $0.link == nil })432        #expect(ResearchText.render("<https://evil.example>").runs.allSatisfy { $0.link == nil })433    }434435    @Test func nothingIsPrefilledAndTheDraftFollowsTheServersSchema() {436        var d = ResearchDraft()437        #expect(d.request == nil && d.problem != nil && d.capital.isEmpty && d.maxUsd.isEmpty && d.kind == nil && d.interval == nil && d.agentId == nil)438        d.mission = "Trouver une règle de momentum"; d.agentId = ""; d.kind = "spot"; d.symbols = "btc, eth"; d.interval = "1d"439        d.capital = "1000"; d.minutes = "60"; d.maxTrials = "200"; d.tokensMillions = "5"; d.maxUsd = "10"440        #expect(d.request == nil, "one budget still missing")441        d.diskMb = "512"442        let r = try! #require(d.request)443        #expect(r.universe == ["BTC", "ETH"] && r.agentId == nil && r.kind == "spot" && r.interval == "1d" && r.capitalUsd == 1000)444        #expect(r.budgets == .init(wallSeconds: 3600, maxTrials: 200, maxDiskMb: 512, maxModelTokens: 5_000_000, maxModelUsd: 10))445        d.interval = "4h"; #expect(d.request == nil, "the server runs spot jobs at 1h or 1d only"); d.interval = "1d"446        d.symbols = "BTC, BTC"; #expect(d.request == nil)447        d.symbols = "BTC"; d.maxUsd = "0.01"; #expect(d.request == nil)448        d.maxUsd = "10"; d.mission = "court"; #expect(d.request == nil)449    }450451    @Test func logBufferKeepsOrderWithoutDuplicates() {452        func line(_ id: Int64) -> ResearchLogLine { decode(#"{"id":\#(id),"ts":1795000001000,"s":"out","t":"l\#(id)"}"#) }453        var b = ResearchLogBuffer(); b.limit = 3454        b.append([line(2), line(1)]); b.append([line(2), line(3)]); b.append([line(4)])455        #expect(b.lines.map(\.id) == [2, 3, 4] && b.lastId == 4 && b.dropped == 1)456        #expect(ResearchLabels.footer.isEmpty == false)457    }458}459460// MARK: rendering check (test data, never shipped)461462import SwiftUI463464@MainActor @Suite struct ResearchRenderingTests {465    /** Renders the result sections from the TEST job above to a PNG (path printed) so that the layout can be looked at; asserts only that it draws. */466    @Test func resultSectionsRender() throws {467        let detail: ResearchJobDetail = decode(researchDetailJSON)468        for scheme in [ColorScheme.light, .dark] {469            let view = VStack(alignment: .leading, spacing: 16) { ResearchResultsView(detail: detail); ResearchFooter() }470                .padding(20).frame(width: 402).background(Theme.bg).environment(\.colorScheme, scheme)471            let r = ImageRenderer(content: view); r.scale = 2472            let image = try #require(r.uiImage)473            #expect(image.size.height > 800)474            try image.pngData()?.write(to: URL(fileURLWithPath: "/tmp/ops-research-result-\(scheme == .dark ? "dark" : "light").png"))475        }476    }477}478
Files main
Menu

Theme