SPB Git

Repository Public

NextTests.swift 28.1 KB 440 lines swift

1//2//  VQuant iOS3//  File: VQuantTests/NextTests.swift4//  Description: Tests of what VQuant Next adds: the transport adapter, the sync centre (migration of the 1.05//               watchlist, offline queue, merge between two devices), layout and chart arithmetic, forms, and the6//               backend-6 routes against the frozen test backend (M2U64:5058) when a test token is injected.7//8//  Author: Simon-Pierre Boucher9//  Contact: contact@spboucher.ai10//1112import Foundation13import Testing14import VQuantKit15import VQuantKitTesting16@testable import VQuant1718private func tempDir() -> URL {19    let u = FileManager.default.temporaryDirectory.appendingPathComponent("vq-next-\(UUID().uuidString)", isDirectory: true)20    try? FileManager.default.createDirectory(at: u, withIntermediateDirectories: true)21    return u22}23private func defaults() -> UserDefaults { UserDefaults(suiteName: "vq.next.\(UUID().uuidString)")! }2425/// Waits for a condition that depends on asynchronous engine work.26@MainActor private func eventually(_ timeout: TimeInterval = 4, _ condition: @MainActor () async -> Bool) async -> Bool {27    let end = Date().addingTimeInterval(timeout)28    while Date() < end { if await condition() { return true }; try? await Task.sleep(for: .milliseconds(30)) }29    return await condition()30}3132@MainActor33@Suite("Adaptateur de transport VQuantKit")34struct NextTransportTests {35    private func transport() -> IOSVQTransport {36        IOSVQTransport(client: APIClient(baseURL: URL(string: "https://vquant.spboucher.ai")!, tokens: MemoryTokenStore("vqn_test"), clientTag: "vquant-ios/2.0.0 (2)"))37    }3839    @Test func symbolsWithACaretAreEncodedOnce() throws {40        let r = try transport().urlRequest(.get("/api/v2/data/bars/\(VQRequest.segment("^GSPC"))", [VQQueryItem("interval", "1d")]))41        #expect(r.url?.absoluteString == "https://vquant.spboucher.ai/api/v2/data/bars/%5EGSPC?interval=1d")42        let dotted = try transport().urlRequest(.get("/api/v2/data/statements/\(VQRequest.segment("BRK-B"))"))43        #expect(dotted.url?.path == "/api/v2/data/statements/BRK-B")44        let spaced = try transport().urlRequest(.get("/api/v2/research/sessions/\(VQRequest.segment("s-abc"))/file", [VQQueryItem("path", "data/my file.csv")]))45        #expect(spaced.url?.query?.contains("my%20file.csv") == true)46    }4748    @Test func headersCarryTheSessionAndTheNextClientVersion() throws {49        let r = try transport().urlRequest(VQRequest(.put, "/api/v2/objects/note/ios-test-n1", body: ["data": ["title": "t", "body": "b"], "baseRev": 0]))50        #expect(r.value(forHTTPHeaderField: "Authorization") == "Bearer vqn_test")51        #expect(r.value(forHTTPHeaderField: "X-VQ-Client") == "vquant-ios/2.0.0 (2)")52        #expect(r.value(forHTTPHeaderField: "Content-Type") == "application/json")53        #expect(r.value(forHTTPHeaderField: "Origin") == nil)54        #expect(r.httpMethod == "PUT" && r.httpBody != nil)55    }5657    @Test func multipartUploadKeepsItsContentType() throws {58        let form = VQDatasetUpload.multipart(name: "a.csv", data: Data("x,y\n1,2\n".utf8))59        let r = try transport().urlRequest(.raw(.post, "/api/v2/research/sessions/s-1/upload", body: form.body, contentType: form.contentType, timeout: 600))60        #expect(r.value(forHTTPHeaderField: "Content-Type")?.hasPrefix("multipart/form-data") == true)61        #expect(r.httpBody == form.body)62    }6364    @Test func cipherRoundTripsAndRejectsAnotherKey() throws {65        let a = AppSyncCipher(keys: FixedCacheKey(Data(repeating: 1, count: 32))), b = AppSyncCipher(keys: FixedCacheKey(Data(repeating: 2, count: 32)))66        let sealed = try a.seal(Data("secret".utf8))67        #expect(sealed != Data("secret".utf8))68        #expect(try a.open(sealed) == Data("secret".utf8))69        #expect(throws: (any Error).self) { try b.open(sealed) }70    }71}7273@MainActor74@Suite("Synchronisation : migration, file hors ligne, deux appareils", .serialized)75struct SyncCenterTests {76    private func center(_ server: VQFakeServer, device: String, legacy: URL, root: URL = tempDir(), defaults d: UserDefaults = defaults()) -> SyncCenter {77        SyncCenter(client: VQClient(transport: server.transport(device: device)), keys: FixedCacheKey(Data(repeating: 9, count: 32)), defaults: d, isTest: true, root: root, legacyWatchlist: legacy)78    }79    private func legacyFile(_ symbols: [String]) -> URL {80        let url = tempDir().appendingPathComponent("watchlist.json")81        WatchlistFile(url: url).save(symbols.map { WatchlistFile.Entry(symbol: $0, name: nil, addedAt: Date()) })82        return url83    }8485    @Test func theLocalWatchlistOfVersionOneBecomesOneSyncedObject() async {86        let server = VQFakeServer()87        let file = legacyFile(["AAPL", "MSFT", "^GSPC"])88        let d = defaults()89        let sync = center(server, device: "iphone", legacy: file, defaults: d)90        sync.start(person: "simon"); await sync.ready()91        #expect(await eventually { server.stored(.watchlist, sync.watchlistId)?.rev == 1 })92        #expect(VQWatchlist(json: server.stored(.watchlist, sync.watchlistId)!.data).symbols == ["AAPL", "MSFT", "^GSPC"])93        // the file is kept as a backup, and a second launch does not migrate again94        #expect(!FileManager.default.fileExists(atPath: file.path))95        #expect(FileManager.default.fileExists(atPath: file.deletingLastPathComponent().appendingPathComponent("watchlist.migrated.json").path))96        let again = center(server, device: "iphone", legacy: file, defaults: d)97        again.start(person: "simon"); await again.ready()98        try? await Task.sleep(for: .milliseconds(200))99        #expect(server.stored(.watchlist, sync.watchlistId)?.rev == 1)100        await sync.engine.stop(); await again.engine.stop()101    }102103    @Test func twoDevicesMigratingTheSameAccountMergeWithoutLossOrDuplicate() async {104        let server = VQFakeServer()105        let phone = center(server, device: "iphone", legacy: legacyFile(["AAPL", "MSFT"]))106        let pad = center(server, device: "ipad", legacy: legacyFile(["MSFT", "NVDA"]))107        phone.start(person: "simon"); await phone.ready()108        #expect(await eventually { server.stored(.watchlist, phone.watchlistId) != nil })109        pad.start(person: "simon"); await pad.ready()110        #expect(await eventually { VQWatchlist(json: server.stored(.watchlist, pad.watchlistId)?.data ?? .null).symbols.count == 3 })111        let symbols = VQWatchlist(json: server.stored(.watchlist, pad.watchlistId)!.data).symbols112        #expect(Set(symbols) == ["AAPL", "MSFT", "NVDA"] && symbols.count == 3)113        // one object, not two114        #expect(await pad.engine.objects(of: VQWatchlist.self).count == 1)115        await phone.engine.stop(); await pad.engine.stop()116    }117118    @Test func editsMadeOfflineAreQueuedThenSent() async {119        let server = VQFakeServer()120        let transport = server.transport(device: "iphone")121        let sync = SyncCenter(client: VQClient(transport: transport), keys: FixedCacheKey(Data(repeating: 9, count: 32)), defaults: defaults(), isTest: true, root: tempDir(), legacyWatchlist: tempDir().appendingPathComponent("none.json"))122        sync.start(person: "simon"); await sync.ready()123        #expect(await eventually { await sync.engine.status.connection == .connected })124        let store = WatchlistStore(sync: sync, defaults: defaults())125        transport.offline = true126        store.add("TSLA", name: nil); store.add("AMD", name: nil); await store.settle()127        #expect(store.symbols.contains("TSLA") && store.symbols.contains("AMD"))      // shown at once128        #expect(await sync.engine.pendingWrites.count >= 1)129        #expect(server.stored(.watchlist, sync.watchlistId).map { VQWatchlist(json: $0.data).symbols.contains("TSLA") } != true)130        transport.offline = false131        _ = await sync.syncNow()132        #expect(await eventually { await sync.engine.pendingWrites.isEmpty })133        #expect(VQWatchlist(json: server.stored(.watchlist, sync.watchlistId)!.data).symbols.contains("AMD"))134        await sync.engine.stop()135    }136137    @Test func preferenceFieldsChangedOnTwoDevicesDoNotUndoEachOther() async {138        let server = VQFakeServer()139        server.serverWrite(.preference, "ios-test-default", data: ["defaultMode": "standard", "upDownColors": "classic"])140        let a = center(server, device: "iphone", legacy: tempDir().appendingPathComponent("n.json"))141        let padTransport = server.transport(device: "ipad")142        let b = SyncCenter(client: VQClient(transport: padTransport), keys: FixedCacheKey(Data(repeating: 9, count: 32)), defaults: defaults(), isTest: true, root: tempDir(), legacyWatchlist: tempDir().appendingPathComponent("n.json"))143        a.start(person: "simon"); b.start(person: "simon"); await a.ready(); await b.ready()144        #expect(await eventually { a.preferences["ios-test-default"] != nil && b.preferences["ios-test-default"] != nil })145        // the iPad is offline while the iPhone changes one field, and changes another one itself146        padTransport.offline = true147        await a.preferences.update("ios-test-default") { $0.defaultMode = "research" }148        #expect(await eventually { VQPreference(json: server.stored(.preference, "ios-test-default")?.data ?? .null).defaultMode == "research" })149        await b.preferences.update("ios-test-default") { $0.upDownColors = .known(.cvd) }150        padTransport.offline = false151        _ = await b.syncNow()152        #expect(await eventually {153            let p = VQPreference(json: server.stored(.preference, "ios-test-default")?.data ?? .null)154            return p.defaultMode == "research" && p.upDownColors == .cvd155        }, "stored: \(server.stored(.preference, "ios-test-default")?.json.text() ?? "nil")")156        await a.engine.stop(); await b.engine.stop()157    }158159    @Test func signOutErasesTheReplica() async {160        let server = VQFakeServer()161        let root = tempDir()162        let sync = center(server, device: "iphone", legacy: legacyFile(["AAPL"]), root: root)163        sync.start(person: "simon"); await sync.ready()164        #expect(await eventually { !sync.watchlists.items.isEmpty })165        let dir = SyncCenter.directory(person: "simon", isTest: true, root: root)166        #expect(FileManager.default.fileExists(atPath: dir.path))167        // the replica on disk is sealed: the symbol does not appear in clear168        let files = (FileManager.default.enumerator(at: dir, includingPropertiesForKeys: nil)?.allObjects as? [URL] ?? []).filter { !$0.hasDirectoryPath }169        #expect(!files.isEmpty && files.allSatisfy { (try? Data(contentsOf: $0)).map { !String(decoding: $0, as: UTF8.self).contains("AAPL") } ?? true })170        sync.wipe()171        #expect(!FileManager.default.fileExists(atPath: dir.path))172        #expect(sync.watchlists.items.isEmpty && sync.person == nil)173    }174175    @Test func chartIdsFollowTheWebConvention() {176        let sync = SyncCenter(client: VQClient(transport: VQFakeServer().transport(device: "x")), keys: FixedCacheKey(), defaults: defaults(), isTest: false, root: tempDir(), legacyWatchlist: tempDir())177        #expect(sync.chartId("aapl") == "sym-AAPL")178        #expect(sync.chartId("SHOP.TO") == "sym-SHOP_2eTO")179        #expect(sync.chartId("^GSPC") == "sym-_5eGSPC")180        #expect(VQObjectID.isValid(sync.chartId("BTC-USD=X^")))181        #expect(SyncCenter.configuration.granularity == .field)182    }183}184185@MainActor186@Suite("Dispositions, graphiques, formulaires")187struct NextLogicTests {188    @Test func dividerKeepsTheTotalAndTheMinimum() {189        let f = SplitMath.moved([0.5, 0.3, 0.2], divider: 0, by: 0.1)190        #expect(abs(f[0] - 0.6) < 1e-9 && abs(f[1] - 0.2) < 1e-9 && f[2] == 0.2)191        let clamped = SplitMath.moved([0.5, 0.5], divider: 0, by: 0.9)192        #expect(abs(clamped[0] - 0.88) < 1e-9 && abs(clamped.reduce(0, +) - 1) < 1e-9)193        #expect(SplitMath.moved([0.5, 0.5], divider: 3, by: 0.1) == [0.5, 0.5])194        let p = SplitMath.percentages([1, 1, 1])195        #expect(abs(p.reduce(0, +) - 100) < 1e-9 && p[0] == 33.3)196    }197198    @Test func resizingANestedSplitRewritesOnlyThatNode() {199        let layout = VQLayoutNode.split(.row, sizes: [50, 50], children: [.panel("a"), .split(.column, sizes: [50, 50], children: [.panel("b"), .panel("c")])])200        let out = SplitMath.setting([30, 70], at: [1], in: layout)201        #expect(out.sizes == [50, 50] && out.children[1].sizes == [30, 70] && out.panelIds == ["a", "b", "c"])202        // unknown keys of the web client survive a typed edit203        var w = VQWorkspace(json: ["name": "W", "activeSymbol": "NVDA", "template": "t1", "layout": layout.json, "panels": ["a": ["type": "chart", "config": ["symbol": "AAPL", "linked": false, "extra": 1]]]])204        w.layout = out205        #expect(w.raw["activeSymbol"] == "NVDA" && w.raw["template"] == "t1" && w.panels["a"]?.config["extra"] == 1)206    }207208    @Test func drawingPointsMapBetweenTimeAndBarIndex() {209        let times: [Double] = [0, 86_400, 2 * 86_400, 5 * 86_400]          // a weekend between the last two210        #expect(ChartTime.index(of: 86_400, times: times) == 1)211        #expect(abs(ChartTime.index(of: 3.5 * 86_400, times: times) - 2.5) < 1e-9)212        #expect(ChartTime.index(of: -86_400, times: times) == -1)213        #expect(abs(ChartTime.time(at: 2.5, times: times) - 3.5 * 86_400) < 1e-6)214        #expect(ChartTime.time(at: 4, times: times) == 6 * 86_400)215        for t in [0.0, 43_200, 200_000, 400_000] { #expect(abs(ChartTime.time(at: ChartTime.index(of: t, times: times), times: times) - t) < 1e-6) }216    }217218    @Test func dailyBarsKeepTheirSessionDateInExchangeTime() {219        // 2026-11-20 00:00 UTC is still the 19th in New York: the bar must be shown as the 20th.220        let series = VQBarSeries(json: ["symbol": "AAPL", "interval": "1d", "bars": [[1_795_132_800, 10, 12, 9, 11, 1000], [1_795_219_200, 11, .null, 10, 12, 5]], "provenance": ["provider": "fmp"]])221        let bars = ChartTime.bars(series, intraday: false)222        #expect(bars.count == 1)                                             // the bar without a high is not drawn as a zero223        #expect(MarketDate.day(bars[0].date) == "2026-11-20")224        #expect(ChartTime.t(bars[0], intraday: false) == 1_795_132_800)225    }226227    @Test func fibonacciMeasureAndLevels() {228        let fib = ChartDrawingMath.fib(a: 100, b: 200)229        #expect(fib.first?.price == 200 && fib.last?.price == 100 && abs(fib[3].price - 150) < 1e-9)230        let m = ChartDrawingMath.measure(.init(t: 0, p: 100), .init(t: 2 * 86_400, p: 110), times: [0, 86_400, 2 * 86_400])231        #expect(m.bars == 2 && m.days == 2 && abs((m.deltaPct ?? 0) - 0.1) < 1e-9)232        let levels = ChartDrawingMath.levels([VQChart.Drawing(type: "hline", points: [.init(t: 0, p: 123)]), VQChart.Drawing(type: "pencil", points: [.init(t: 0, p: 1), .init(t: 1, p: 2)])])233        #expect(levels.count == 1 && levels[0].price == 123)234        #expect(DrawingLayer.thin((0..<1000).map { VQChart.Drawing.Point(t: Double($0), p: 1) }, to: 160).count <= 161)235    }236237    @Test func theQuestionToTheAgentCarriesTheVisibleWindow() {238        let a = Bar(date: MarketDate.parse("2026-01-05")!, open: 1, high: 2, low: 1, close: 100), b = Bar(date: MarketDate.parse("2026-03-31")!, open: 1, high: 2, low: 1, close: 120)239        var c = ChartConfiguration(); c.overlays = [.sma50]; c.panels = [.rsi]240        let q = ChartWorkstation.question(symbol: "NVDA", range: .quarter, first: a, last: b, count: 60, configuration: c, levels: [("Ligne horizontale", 110)], provider: "fmp")241        #expect(q.contains("NVDA") && q.contains("2026-01-05") && q.contains("2026-03-31") && q.contains("60 barres") && q.contains("MM 50") && q.contains("RSI 14") && q.contains("110"))242    }243244    @Test func jsonParametersBecomeNativeLists() {245        if case .rows(let f) = JSONParamEditor.shape(hint: #"[{"type": "call|put|stock", "side": "long|short", "strike": 100, "expiry_days": 30, "quantity": 1, "premium": 2.5}]"#) {246            #expect(f.map(\.key) == ["type", "side", "strike", "expiry_days", "quantity", "premium"])247            #expect(f[0].choices == ["call", "put", "stock"] && f[2].isNumber && !f[0].isNumber)248        } else { Issue.record("legs should be rows") }249        #expect(JSONParamEditor.shape(hint: #"{"USD": 2500, "CAD": 1000}"#) == .map(valueIsNumber: true, sampleKey: "CAD"))250        #expect(JSONParamEditor.shape(hint: #"{"SPY": -0.20, "TLT": 0.05}  or  {"Equity crash": {"SPY": -0.20}}"#) == .map(valueIsNumber: true, sampleKey: "SPY"))251        if case .rows = JSONParamEditor.shape(hint: #"[{"symbol": "AAPL", "date": "2025-05-01"}, …]  or  ["2025-05-01"] with one symbol"#) {} else { Issue.record("events should be rows") }252        #expect(JSONParamEditor.shape(hint: #"buy_hold {} · ma_cross {"fast": 50}"#) == .raw)253        #expect(JSONParamEditor.shape(hint: nil) == .raw)254    }255256    @Test func positionSizeIsRiskBudgetOverVaR() {257        let s = SizingQuickCalc.size(capital: 100_000, riskFraction: 0.01, varFraction: 0.025, price: 200)258        #expect(s?.budget == 1000 && s?.value == 40_000 && s?.shares == 200 && s?.weight == 0.4)259        #expect(SizingQuickCalc.size(capital: 100_000, riskFraction: 0.01, varFraction: 0, price: 200) == nil)260    }261262    @Test func themeIsPerDeviceWhileResearchPreferencesSync() {263        let prefs = Preferences(defaults: defaults())264        prefs.appearance = .light265        var p = VQPreference(); p.theme = "dark"; p.defaultMode = "deep"; p.defaultModel = "auto"; p.upDownColors = .known(.cvd); p.budget = .init(maxCostUsd: 3, maxMinutes: nil)266        prefs.apply(p)267        #expect(prefs.appearance == .light)                                  // not applied268        #expect(prefs.defaultMode == .deep && prefs.defaultModel == "auto" && prefs.colourVisionSafe && prefs.budgetCostUsd == 3)269        var out = VQPreference(json: ["theme": "dark", "recentSearches": ["x"], "futureKey": 1])270        prefs.write(to: &out)271        #expect(out.theme == "dark" && out.raw["futureKey"] == 1 && out.recentSearches == ["x"])      // untouched272        #expect(out.defaultMode == "deep" && out.upDownColors == .cvd && out.budget?.maxCostUsd == 3)273    }274275    @Test func nextDeepLinksAndSearchResults() {276        let r = Router()277        r.handle(URL(string: "vquant://research/s-abc")!, compact: true)278        #expect(r.section == .research && r.paths[.research]?.last == .researchSession("s-abc"))279        r.handle(URL(string: "vquant://approvals")!, compact: true)280        #expect(r.paths[.research]?.last == .approvals)281        r.handle(URL(string: "vquant://ask?q=Volatilit%C3%A9%20de%20SPY")!, compact: true)282        #expect(r.showComposer && r.composerDraft == "Volatilité de SPY" && r.composerPreset.mode == .research)283        let pad = Router()284        pad.handle(URL(string: "vquant://project/p1")!, compact: false)285        #expect(pad.section == .studio && pad.padDetail[.studio] == .project("p1") && (pad.paths[.studio] ?? []).isEmpty)286        pad.open(.quantJob("j1"), compact: false)287        #expect(pad.section == .quant && pad.padDetail[.quant] == .quantJob("j1"))288        SearchRouting.open(VQSearchResult(json: ["type": "action", "id": "engine:risk_lab", "title": "Risk Lab"]), router: pad, compact: false)289        #expect(pad.padDetail[.quant] == .quantTool("risk_lab"))290        SearchRouting.open(VQSearchResult(json: ["type": "symbol", "id": "^GSPC", "symbol": "^GSPC", "title": "S&P 500"]), router: pad, compact: false)291        #expect(pad.section == .markets && pad.padDetail[.markets] == .asset("^GSPC"))292    }293294    @Test func syncChipSaysWhatIsHappening() {295        var s = VQSyncStatus(); s.connection = .connected296        #expect(SyncStatusChip.spec(s, online: true).text == "Synchronisé")297        s.pendingWrites = 2298        #expect(SyncStatusChip.spec(s, online: true).text.contains("2 modifications en attente"))299        s.connection = .reconnecting(attempt: 1, retryIn: 2)300        #expect(SyncStatusChip.spec(s, online: false).text.hasPrefix("Hors ligne"))301        s.connection = .locked302        #expect(SyncStatusChip.spec(s, online: true).text == "Session fermée")303    }304305    @Test func researchEventsFeedTheSharedStoreAndAreNotUnknown() {306        var run = AnalysisRun()307        let store = VQResearchSessionStore()308        let events: [String] = [309            #"{"type":"job","id":"g1","sessionId":"s1","query":"q"}"#,310            #"{"type":"research_workspace","workspaceId":"s-s1","kind":"session"}"#,311            #"{"type":"approval_request","approval":{"id":"a1","action":"open_network","reason":"télécharger un jeu public","status":"pending","createdAt":1795000000000}}"#,312            #"{"type":"experiment","experiment":{"id":"e1","seq":1,"kind":"experiment","title":"GARCH vs IV","status":"ok"}}"#,313            #"{"type":"quality_gate","passed":true,"findings":[]}"#,314            #"{"type":"some_future_event"}"#,315        ]316        for (i, raw) in events.enumerated() {317            let e = AnalysisEvent(sse: SSEEvent(event: "message", data: raw, id: i))318            run.apply(StreamItem(index: i, event: e, raw: raw))319            store.apply(try! VQJSON.parse(raw), index: i)320        }321        #expect(run.unknownEvents == ["some_future_event"])                  // the research events are known, the future one is reported322        #expect(store.workspaceId == "s-s1" && store.pendingApprovals.map(\.id) == ["a1"] && store.experiments.count == 1)323    }324325    /// The live study view passes no question to the report (it shows it in its header): no empty card may be drawn.326    @Test func emptyBlocksOfAReportAreNotRendered() {327        #expect(!ExchangeView.showsQuestion(Exchange(question: "", answer: "Résultat")))328        #expect(!ExchangeView.showsQuestion(Exchange(question: "  \n ", answer: "Résultat")))329        #expect(ExchangeView.showsQuestion(Exchange(question: "Volatilité de SPY ?", answer: "")))330        #expect(!ExchangeView.showsAnswer(Exchange(question: "q", answer: " \n")))331        #expect(ExchangeView.showsAnswer(Exchange(question: "", answer: "Texte")))332    }333334    @Test func modesIncludeAutonomousResearchAndTheRequestCarriesBudgetAndProject() throws {335        #expect(AnalysisMode.allCases.contains(.research) && AnalysisMode.classic.count == 4)336        let body = try JSONEncoder().encode(ChatRequest(query: "q", mode: "research", model: "auto", budget: .init(maxCostUsd: 3, maxMinutes: nil), projectId: "p1"))337        let j = try VQJSON.parse(body)338        #expect(j.str("mode") == "research" && j.str("model") == "auto" && j["budget"]?.num("maxCostUsd") == 3 && j.str("projectId") == "p1")339        let plain = try VQJSON.parse(try JSONEncoder().encode(ChatRequest(query: "q")))340        #expect(plain["budget"] == nil && plain["projectId"] == nil && plain["model"] == nil)      // 1.0 body unchanged when unused341    }342}343344@MainActor345@Suite("Backend 6 réel (M2U64:5058)", .enabled(if: ProcessInfo.processInfo.environment["VQUANT_TEST_TOKEN"] != nil), .serialized)346struct NextLiveTests {347    private let kit: KitAPI348    private let client: APIClient349    init() {350        let env = ProcessInfo.processInfo.environment351        client = APIClient(baseURL: URL(string: env["VQUANT_BASE_URL"] ?? "http://127.0.0.1:5058")!, tokens: MemoryTokenStore(env["VQUANT_TEST_TOKEN"]), clientTag: "vquant-ios/2.0.0 (2)")352        kit = KitAPI(transport: IOSVQTransport(client: client))353    }354355    @Test func theNextHeaderUnlocksTheLabEngines() async throws {356        let catalog = try await kit.lab.catalog()357        #expect(catalog.tools.count >= 19 && catalog.labEngines.count >= 13)358        #expect(catalog.tool("options_lab")?.params.contains { $0.name == "legs" && $0.type == .json } == true)359        // a 1.x header still gets the six legacy tools only (the server's compatibility rule)360        let old = KitAPI(transport: IOSVQTransport(client: APIClient(baseURL: client.baseURL, tokens: client.tokens, clientTag: "vquant-ios/1.0.0 (1)")))361        #expect(try await old.lab.catalog().tools.count == 6)362    }363364    @Test func dataLayerThroughTheAdapter() async throws {365        let bars = try await kit.data.bars("^GSPC", interval: "1d", limit: 30)             // the caret survives the app's encoder366        #expect(bars.bars.count > 10 && !bars.provenance.provider.isEmpty)367        let quotes = try await kit.data.quotes(["AAPL", "MSFT"])368        #expect(quotes["AAPL"]?.price != nil && quotes.freshness != nil)369        let st = try await kit.data.statements("AAPL", period: "annual", limit: 3)370        #expect(st.periods.count == 3 && !st.income.isEmpty && st.ratios.contains { $0.formula != nil })371        let o = try await kit.data.marketOverview()372        #expect(o.sections.contains { $0.id == "indices" && !$0.items.isEmpty })373        let s = try await kit.data.search("apple", limit: 10)374        #expect(s.results.contains { $0.type == .symbol } || s.unavailable.contains("symbol"))375        let models = try await kit.models.catalog()376        #expect(!models.selectableModels.isEmpty && !models.defaultModel.isEmpty)377    }378379    @Test func marketStoreUsesBatchedQuotesAndV2Bars() async throws {380        let dir = tempDir()381        let market = MarketStore(api: VQuantAPI(client: client), fetcher: CachedFetcher(cache: DiskCache(directory: dir, keyProvider: FixedCacheKey())))382        market.kit = kit383        await market.refreshQuotes(["AAPL", "^GSPC", "ZZZZNOTASYMBOL"])384        #expect(market.quotes["AAPL"] != nil && market.quoteFreshness["AAPL"]?.provider != nil)385        #expect(market.quotes["ZZZZNOTASYMBOL"] == nil)                         // never a zero for an unknown symbol386        let bars = try await market.bars("AAPL", range: .quarter)387        #expect(bars.value.count > 40 && market.provenance("AAPL", range: .quarter)?.provider.isEmpty == false)388        #expect(bars.value.map(\.date) == bars.value.map(\.date).sorted())389    }390391    @Test func aLabEngineRunsOnTheServerAndReturnsALabResult() async throws {392        let job = try await kit.lab.run(tool: "options_lab", params: ["symbol": "AAPL", "mode": "price", "expiry_days": 30])393        #expect(job.status == .done)394        let r = try #require(job.labResult)395        #expect(r.success && r.summary.contains { $0.label == "Delta" } && !r.charts.isEmpty && r.provenance != nil)396        try await kit.lab.delete(job.id)397    }398399    @Test func aSyncedObjectRoundTripsThroughTheEngine() async throws {400        let id = "ios-test-unit-\(UUID().uuidString.prefix(8).lowercased())"401        let engine = VQSyncEngine(client: kit.client, storage: VQMemorySyncStorage(), configuration: SyncCenter.configuration)402        try await engine.pull()403        _ = try await engine.put(VQNote(title: "ios-test note", body: "écrite par les tests iOS"), id: id)404        await engine.flush()405        #expect(await eventually(8) { await engine.pendingWrites.isEmpty })       // a flush may already be in flight: wait for the queue406        let stored = try await kit.objects.get(.note, id)407        #expect(stored.rev == 1 && VQNote(json: stored.data).title == "ios-test note")408        try await engine.delete(.note, id)409        await engine.flush()410        #expect(await eventually(8) { await engine.pendingWrites.isEmpty })411        await #expect(throws: VQError.self) { _ = try await kit.objects.get(.note, id) }412    }413414    /// The position round trip of 1.0, on the test portfolio (never `main`), through the engine.415    @Test func aPositionRoundTripsOnTheTestPortfolio() async throws {416        let id = "ios-test-portfolio"417        let engine = VQSyncEngine(client: kit.client, storage: VQMemorySyncStorage(), configuration: SyncCenter.configuration)418        try await engine.pull()419        var p = await engine.object(VQPortfolio.self, id: id)?.data ?? VQPortfolio(name: "ios-test — portefeuille", baseCurrency: "USD")420        p.upsert(VQPortfolio.Position(symbol: "PEP", quantity: 2, costBasis: 150.5, note: "test iOS"))421        _ = try await engine.put(p, id: id)422        await engine.flush()423        #expect(await eventually(8) { await engine.pendingWrites.isEmpty })424        let stored = VQPortfolio(json: try await kit.objects.get(.portfolio, id).data)425        #expect(stored.position("PEP")?.quantity == 2 && stored.position("PEP")?.costBasis == 150.5)426        p.removePosition("PEP")427        _ = try await engine.put(p, id: id)428        await engine.flush()429        #expect(await eventually(8) { await engine.pendingWrites.isEmpty })430        #expect(VQPortfolio(json: try await kit.objects.get(.portfolio, id).data).position("PEP") == nil)431    }432433    @Test func researchRoutesAnswer() async throws {434        let sandbox = try await kit.researchAgent.sandbox()435        #expect(sandbox.uploadMaxBytes > 0)436        _ = try await kit.researchAgent.sessions()437        _ = try await kit.researchAgent.approvals(pendingOnly: true)438    }439}440
Files main
Menu

Theme