SPB Git

Repository Public

CoreTests.swift 24.3 KB 464 lines swift

1//2//  VQuant iOS3//  File: CoreTests/CoreTests.swift4//  Description: Tests of the platform-neutral core. Fixtures are real responses of the VQuant backend (trimmed).5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import Foundation11import Testing12@testable import VQuantCore1314func fixture(_ name: String) throws -> Data {15    let url = try #require(Bundle.module.url(forResource: name, withExtension: "json", subdirectory: "Fixtures"))16    return try Data(contentsOf: url)17}18func decode<T: Decodable>(_ type: T.Type, _ name: String) throws -> T { try JSONDecoder().decode(T.self, from: try fixture(name)) }1920@Suite("Décodage des réponses réelles")21struct DecodingTests {22    @Test func quote() throws {23        let q = try #require(try decode([Quote].self, "quote").first)24        #expect(q.symbol == "AAPL")25        #expect(q.price > 0)26        #expect(q.changePercent != nil)27        #expect(q.timestamp != nil)28        #expect(q.marketCap ?? 0 > 1e12)29    }3031    @Test func indicesUseEitherPercentKey() throws {32        let list = try decode([Quote].self, "indices")33        #expect(list.count >= 10)34        #expect(list.first?.symbol == "^GSPC")35        #expect(list.allSatisfy { $0.changePercent != nil })36    }3738    @Test func moversHaveNoTimestampAndStillDecode() throws {39        let list = try decode([Quote].self, "gainers")40        #expect(!list.isEmpty)41        #expect(list[0].timestamp == nil)42        #expect(list[0].changePercent ?? 0 > 0)43    }4445    @Test func quoteWithoutPriceIsRejectedNotZeroed() {46        let json = Data(#"[{"symbol":"X","name":"x"}]"#.utf8)47        #expect(throws: (any Error).self) { try JSONDecoder().decode([Quote].self, from: json) }48    }4950    @Test func dailyBars() throws {51        let bars = try decode([Bar].self, "chart-full")52        #expect(bars.count > 50)53        let b = try #require(bars.first)54        #expect(b.high >= b.low && b.high >= b.open && b.high >= b.close)55        #expect(MarketDate.day(b.date) == "2026-11-18")56    }5758    @Test func intradayBarsAreExchangeTime() throws {59        let bars = try decode([Bar].self, "chart-intraday")60        let last = try #require(bars.first)                       // the provider sends newest first61        let c = MarketDate.calendar.dateComponents([.hour, .minute], from: last.date)62        #expect(c.hour == 15 && c.minute == 55)63    }6465    @Test func profileNewsHoursSearch() throws {66        #expect(try decode([CompanyProfile].self, "profile").first?.companyName == "Apple Inc.")67        let news = try decode([NewsItem].self, "news")68        #expect(news.first?.published != nil)69        #expect(try decode([ExchangeHours].self, "market-hours").count > 3)70        let matches = try decode([SymbolMatch].self, "search")71        #expect(matches.contains { $0.symbol == "AAPL" && $0.exchangeCode == "NASDAQ" })72    }7374    @Test func fundamentalsStayGeneric() throws {75        let rows = try decode([FundamentalRecord].self, "income")76        #expect(rows.first?["revenue"]?.doubleValue ?? 0 > 0)77        #expect(rows.first?["date"]?.stringValue != nil)78    }7980    @Test func conversationWithMessagesAsString() throws {81        let c = try decode(Conversation.self, "session")82        #expect(c.exchanges.count >= 1)83        let e = c.exchanges[0]84        #expect(!e.answer.isEmpty)85        #expect(e.figures.first?.figureUrls.first?.hasPrefix("/figures/") == true)86        #expect(ReportText.images(in: e.answer).count >= 4)87        // round trip through the cache encoding88        let again = try JSONDecoder().decode(Conversation.self, from: JSONEncoder().encode(c))89        #expect(again == c)90    }9192    @Test func listsAndWorkspace() throws {93        let sessions = try decode([ConversationSummary].self, "sessions")94        #expect(sessions.first?.updatedAt != nil)95        let w = try decode(Workspace.self, "workspace")96        #expect(w.user.id == "simon")97        #expect(try decode(GenerationList.self, "generations").running == 0)98        #expect(try decode([SharedReportSummary].self, "shared-reports").first?.shareId.isEmpty == false)99    }100101    @Test func devices() throws {102        let d = try decode(DeviceList.self, "devices")103        #expect(d.sessions.first?.current == true)104        #expect(d.passkeys.first?.ref.isEmpty == false)105        #expect(d.passkeys.first?.backedUp == true)106    }107108    @Test func quantToolsAndJobs() throws {109        let tools = try decode(QuantToolList.self, "quant-tools")110        #expect(tools.tools.map(\.id).contains("garch"))111        let garch = try #require(tools.tools.first { $0.id == "garch" })112        #expect(garch.params.first { $0.name == "p" }?.default?.intValue == 1)113        struct Envelope: Decodable { var job: QuantJob }114        let job = try decode(Envelope.self, "quant-job-garch").job115        #expect(job.status == .done)116        #expect(job.params["forecast_horizon"]?.intValue == 30)117        #expect(job.code?.contains("arch") == true)118        #expect(job.result?["parameters"]?["persistence"]?.doubleValue ?? 0 > 0)119        let series = try #require(QuantResult.series(job.result?["volatility_forecast"] ?? .null))120        #expect(series.count == 30)121    }122123    @Test func quantResultSections() throws {124        struct Envelope: Decodable { var job: QuantJob }125        let job = try decode(Envelope.self, "quant-job-var").job126        let sections = QuantResult.sections(try #require(job.result))127        let table = sections.first { $0.title == "var_by_confidence" }128        if case .table(let t)? = table?.body { #expect(t.rows.count == 3 && t.columns.contains("historical.var_dollar")) } else { Issue.record("expected a table") }129        let stats = sections.first { $0.title == "distribution_statistics" }130        if case .values(let rows)? = stats?.body { #expect(rows.contains { $0.key == "annual_volatility" }) } else { Issue.record("expected rows") }131        #expect(!sections.contains { $0.title == "success" })132    }133}134135@Suite("Flux SSE et réduction")136struct StreamTests {137    @Test func parserHandlesSplitChunksCRLFAndHeartbeats() {138        var p = SSEParser()139        let wire = "id: 0\r\ndata: {\"type\":\"status\",\"message\":\"Analyse\"}\r\n\r\n: ping\n\nid: 1\ndata: {\"type\":\"text\",\ndata: \"content\":\"é\"}\n\n"140        var out: [SSEParser.Output] = []141        for b in Array(wire.utf8) { if let o = p.feed(b) { out.append(o) } }142        #expect(out.count == 3)143        #expect(out[1] == .heartbeat)144        guard case .event(let e) = out[2] else { Issue.record("expected an event"); return }145        #expect(e.id == 1)146        #expect(AnalysisEvent(sse: e) == .text("é"))147    }148149    private func item(_ i: Int?, _ json: String) -> StreamItem { StreamItem(index: i, event: AnalysisEvent(sse: SSEEvent(event: "message", data: json, id: i))) }150151    @Test func reducerBuildsTheRun() {152        var run = AnalysisRun()153        let events = [154            item(nil, #"{"type":"job","id":"J","sessionId":"S","query":"Q"}"#),155            item(0, #"{"type":"status","message":"Analyse en cours…"}"#),156            item(1, #"{"type":"tool_start","tool":"get_stock_quote","toolId":"t1","input":{"symbol":"AAPL"}}"#),157            item(2, #"{"type":"tool_complete","tool":"get_stock_quote","toolId":"t1","duration":412,"empty":false}"#),158            item(3, #"{"type":"tool_result","tool":"get_stock_quote","result":[{"symbol":"AAPL","price":352.45}]}"#),159            item(4, #"{"type":"custom_python_figures","figureId":"f","figures":["/figures/a.png"],"figureUrls":["/figures/a.png"],"output":"","description":"d"}"#),160            item(5, #"{"type":"text","content":"Bonjour "}"#),161            item(6, #"{"type":"text","content":"monde"}"#),162            item(7, #"{"type":"followups","questions":["Et MSFT ?"]}"#),163            item(8, #"{"type":"done","sessionId":"S"}"#),164        ]165        for e in events { run.apply(e) }166        #expect(run.jobId == "J" && run.sessionId == "S")167        #expect(run.answer == "Bonjour monde")168        #expect(run.steps.count == 1 && run.steps[0].state == .done && run.steps[0].durationMs == 412)169        #expect(run.toolResults.count == 1)170        #expect(run.figures.first?.figureUrls == ["/figures/a.png"])171        #expect(run.followups == ["Et MSFT ?"])172        #expect(run.isFinished && run.error == nil)173        #expect(run.nextIndex == 9)174    }175176    @Test func replayAfterReconnectionDoesNotDuplicate() {177        var run = AnalysisRun()178        run.apply(item(0, #"{"type":"text","content":"A"}"#))179        run.apply(item(1, #"{"type":"text","content":"B"}"#))180        // reconnection replays from an older index181        run.apply(item(0, #"{"type":"text","content":"A"}"#))182        run.apply(item(1, #"{"type":"text","content":"B"}"#))183        run.apply(item(2, #"{"type":"text","content":"C"}"#))184        #expect(run.answer == "ABC")185        #expect(run.nextIndex == 3)186    }187188    @Test func errorThenDoneMarksRunningStepsFailed() {189        var run = AnalysisRun()190        run.apply(item(0, #"{"type":"tool_start","tool":"x","toolId":"t","input":{}}"#))191        run.apply(item(1, #"{"type":"error","error":"L'analyse s'est interrompue"}"#))192        run.apply(item(2, #"{"type":"done"}"#))193        #expect(run.isFinished && run.error != nil)194        #expect(run.steps[0].state == .failed)195    }196197    @Test func unknownEventsAreKeptNotDropped() {198        var run = AnalysisRun()199        run.apply(item(0, #"{"type":"brand_new_thing","x":1}"#))200        #expect(run.unknownEvents == ["brand_new_thing"])201    }202203    @Test func subAgents() {204        var run = AnalysisRun()205        run.apply(item(0, #"{"type":"agent_start","agentId":"a1","name":"Valorisation","kind":"analyst"}"#))206        run.apply(item(1, #"{"type":"agent_tool","agentId":"a1","tool":"get_dcf_valuation","status":"running"}"#))207        run.apply(item(2, #"{"type":"agent_done","agentId":"a1","ok":true,"tools":3,"durationMs":900,"preview":"ok"}"#))208        #expect(run.steps.count == 1 && run.steps[0].kind == .agent && run.steps[0].state == .done)209        #expect(run.steps[0].detail?.contains("3 outils") == true)210    }211}212213@Suite("Indicateurs et portefeuille")214struct QuantTests {215    @Test func movingAverages() {216        let x: [Double] = [1, 2, 3, 4, 5, 6]217        #expect(Indicators.sma(x, period: 3) == [nil, nil, 2, 3, 4, 5])218        let e = Indicators.ema(x, period: 3)219        #expect(e[1] == nil && e[2] == 2)220        #expect(abs((e[3] ?? 0) - 3) < 1e-12)                    // k = 0.5 → 4·0.5 + 2·0.5221    }222223    @Test func rsiBounds() {224        let up = (0..<30).map(Double.init)225        #expect(Indicators.rsi(up).compactMap { $0 }.allSatisfy { $0 == 100 })226        let wave = (0..<60).map { 100 + 5 * sin(Double($0) / 3) }227        #expect(Indicators.rsi(wave).compactMap { $0 }.allSatisfy { $0 >= 0 && $0 <= 100 })228        #expect(Indicators.rsi([1, 2, 3]).allSatisfy { $0 == nil })229    }230231    @Test func bollingerOfConstantSeriesCollapses() {232        let b = Indicators.bollinger([Double](repeating: 10, count: 25))233        #expect(b.upper[24] == 10 && b.lower[24] == 10)234    }235236    @Test func macdShapes() {237        let x = (0..<80).map { 100 + Double($0) * 0.5 + sin(Double($0)) }238        let m = Indicators.macd(x)239        #expect(m.macd.count == 80 && m.signal.count == 80 && m.histogram.count == 80)240        #expect(m.macd[24] == nil && m.macd[25] != nil)241        #expect(m.signal[33] != nil && m.signal[32] == nil)242    }243244    @Test func drawdownAndVolatility() {245        let p: [Double] = [100, 120, 90, 108, 130]246        #expect(Indicators.drawdown(p) == [0, 0, -0.25, 108.0 / 120 - 1, 0])247        #expect(Indicators.maxDrawdown(p) == -0.25)248        #expect(Indicators.rollingVolatility([Double](repeating: 50, count: 40)).compactMap { $0 }.allSatisfy { $0 == 0 })249    }250251    @Test func correlation() {252        let a: [Double] = [1, 2, 3, 4, 5]253        #expect(abs((Indicators.correlation(a, a.map { $0 * 2 + 1 }) ?? 0) - 1) < 1e-12)254        #expect(abs((Indicators.correlation(a, a.map { -$0 }) ?? 0) + 1) < 1e-12)255        #expect(Indicators.correlation(a, [3, 3, 3, 3, 3]) == nil)256    }257258    @Test func aggregationIsExact() throws {259        let bars = try decode([Bar].self, "chart-intraday").sorted { $0.date < $1.date }260        let agg = Indicators.aggregate(bars, factor: 6)261        #expect(agg.count == Int((Double(bars.count) / 6).rounded(.up)))262        #expect(agg[0].open == bars[0].open && agg[0].close == bars[5].close)263        #expect(agg[0].high == bars[0..<6].map(\.high).max())264        #expect(agg.map(\.high).max() == bars.map(\.high).max())265        #expect(agg.map(\.low).min() == bars.map(\.low).min())266        let v1 = agg.compactMap(\.volume).reduce(0, +), v2 = bars.compactMap(\.volume).reduce(0, +)267        #expect(abs(v1 - v2) < 1e-6 * max(1, v2))268        #expect(Indicators.aggregate(bars, factor: 1) == bars)269    }270271    @Test func histogramCountsEverything() {272        let x = (0..<1000).map { Double($0 % 37) }273        #expect(Indicators.histogram(x, bins: 10).reduce(0) { $0 + $1.count } == 1000)274    }275276    @Test func portfolioTotals() {277        let positions = [Position(symbol: "A", quantity: 10, costBasis: 50, note: nil, updatedAt: 0), Position(symbol: "B", quantity: 5, costBasis: nil, note: nil, updatedAt: 0),278                         Position(symbol: "C", quantity: 1, costBasis: 10, note: nil, updatedAt: 0)]279        let quotes = ["A": Quote(symbol: "A", price: 60, changePercent: 20), "B": Quote(symbol: "B", price: 100, changePercent: nil)]280        let lines = PortfolioMath.lines(positions: positions, quotes: quotes)281        let t = PortfolioMath.totals(lines)282        #expect(t.value == 1100)283        #expect(t.unpriced == ["C"])                             // reported, not counted as zero284        #expect(t.cost == 500 && t.gain == 100)                  // only over the positions with a price and a cost basis285        #expect(abs((t.gainPercent ?? 0) - 0.2) < 1e-12)286        #expect(abs((t.dayGain ?? 0) - 100) < 1e-9)              // 600 today was 500 yesterday287        let w = PortfolioMath.weights(lines)288        #expect(w.first?.symbol == "A" && abs(w.reduce(0) { $0 + $1.weight } - 1) < 1e-12)289    }290291    @Test func portfolioHistoryKeepsOnlyCommonDates() {292        func bar(_ d: String, _ c: Double) -> Bar { Bar(date: MarketDate.parse(d)!, open: c, high: c, low: c, close: c) }293        let closes = ["A": [bar("2026-01-02", 10), bar("2026-01-05", 11), bar("2026-01-06", 12)], "B": [bar("2026-01-05", 100), bar("2026-01-06", 90)]]294        let h = PortfolioMath.history(quantities: ["A": 2, "B": 1], closes: closes)295        #expect(h.map(\.value) == [122, 114])296        #expect(PortfolioMath.history(quantities: ["A": 2, "Z": 1], closes: closes).isEmpty)   // a holding without data: no partial curve297        let m = PortfolioMath.correlationMatrix(symbols: ["A", "B"], closes: closes)298        #expect(m[0][0] == 1 && m[1][1] == 1)299    }300}301302@Suite("Cache, fraîcheur, listes locales")303struct CacheTests {304    private func tempDir() -> URL { FileManager.default.temporaryDirectory.appendingPathComponent("vq-" + UUID().uuidString) }305306    @Test func roundTripIsEncryptedOnDisk() async throws {307        let dir = tempDir(); let cache = DiskCache(directory: dir, keyProvider: FixedCacheKey())308        let secret = Data("portefeuille: 123456 AAPL".utf8)309        let when = Date(timeIntervalSince1970: 1_795_000_000)310        await cache.save("k", secret, at: when)311        let hit = try #require(await cache.load("k"))312        #expect(hit.data == secret && hit.savedAt == when)313        let file = try #require(try FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil).first)314        let raw = try Data(contentsOf: file)315        #expect(raw.range(of: Data("AAPL".utf8)) == nil)316        #expect(await cache.size() > 0)317    }318319    @Test func tamperedOrForeignKeyEntriesAreDiscarded() async throws {320        let dir = tempDir()321        let a = DiskCache(directory: dir, keyProvider: FixedCacheKey())322        await a.save("k", Data("x".utf8))323        let b = DiskCache(directory: dir, keyProvider: FixedCacheKey())      // another key324        #expect(await b.load("k") == nil)325        #expect(await a.load("k") == nil)                                    // and the unreadable file was removed326        await a.save("k2", Data("hello".utf8))327        let file = try #require(try FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil).first)328        var raw = try Data(contentsOf: file); raw[3] ^= 0xFF                 // forge the save time329        try raw.write(to: file)330        #expect(await a.load("k2") == nil)331    }332333    @Test func fetcherFallsBackOnlyOnTransportFailure() async throws {334        let fetcher = CachedFetcher(cache: DiskCache(directory: tempDir(), keyProvider: FixedCacheKey()))335        let first = try await fetcher.load("q", [Int].self) { [1, 2, 3] }336        #expect(first.origin == .network)337        let offline = try await fetcher.load("q", [Int].self) { throw URLError(.notConnectedToInternet) }338        #expect(offline.value == [1, 2, 3] && offline.isFromCache)339        await #expect(throws: APIError.self) { _ = try await fetcher.load("q", [Int].self) { throw APIError(kind: .unauthorized, message: "") } }340        await #expect(throws: APIError.self) { _ = try await fetcher.load("never", [Int].self) { throw URLError(.timedOut) } }341    }342343    @Test func freshness() {344        let now = Date(timeIntervalSince1970: 1_795_000_000)345        #expect(DataFreshness.classify(origin: .network, quoteTime: now.addingTimeInterval(-30), marketOpen: true, now: now) == .live)346        #expect(DataFreshness.classify(origin: .network, quoteTime: now.addingTimeInterval(-900), marketOpen: true, now: now) == .delayed(asOf: now.addingTimeInterval(-900)))347        #expect(DataFreshness.classify(origin: .network, quoteTime: now.addingTimeInterval(-30), marketOpen: false, now: now) == .historical(asOf: now.addingTimeInterval(-30)))348        #expect(DataFreshness.classify(origin: .network, quoteTime: now.addingTimeInterval(-7200), marketOpen: nil, now: now) == .historical(asOf: now.addingTimeInterval(-7200)))349        #expect(DataFreshness.classify(origin: .network, quoteTime: nil, marketOpen: true, now: now) == .historical(asOf: nil))350        #expect(DataFreshness.classify(origin: .cache(savedAt: now), quoteTime: now, marketOpen: true, now: now) == .cached(savedAt: now))351    }352353    @Test func watchlist() {354        let url = tempDir().appendingPathComponent("w.json"); let file = WatchlistFile(url: url)355        var list = file.load()356        #expect(list.isEmpty)357        list = WatchlistFile.adding(" aapl ", name: "Apple", to: list)358        list = WatchlistFile.adding("AAPL", name: nil, to: list)             // no duplicate359        list = WatchlistFile.adding("^gspc", name: nil, to: list)360        list = WatchlistFile.adding("DROP TABLE;", name: nil, to: list)      // refused361        file.save(list)362        #expect(file.load().map(\.symbol) == ["AAPL", "^GSPC"])363        #expect(WatchlistFile.removing("aapl", from: list).map(\.symbol) == ["^GSPC"])364    }365366    @Test func markersAndImages() {367        #expect(ReportText.pieces("Verdict :check: net, ratio 3:2:1 et https://x.io/a:up:b") == [.text("Verdict "), .marker("check"), .text(" net, ratio 3:2:1 et https://x.io/a:up:b")])368        #expect(ReportText.image(in: "![Courbe](/figures/a-0.png)") == .init(alt: "Courbe", url: "/figures/a-0.png"))369        #expect(ReportText.image(in: "texte ![x](y)") == nil)370        #expect(ReportText.plain("## Titre\n**gras** :up: ![a](b)") == "Titre gras")371    }372373    @Test func csv() {374        let b = [Bar(date: MarketDate.parse("2026-11-18 09:30:00")!, open: 1, high: 2.5, low: 0.5, close: 2, volume: 100)]375        #expect(CSVExport.bars(b, intraday: true) == "date,open,high,low,close,volume\n2026-11-18 09:30,1,2.5,0.5,2,100\n")376        #expect(CSVExport.bars(b, intraday: false).contains("2026-11-18,1,"))377    }378}379380@Suite("Client HTTP", .serialized)381struct ClientTests {382    final class Stub: URLProtocol, @unchecked Sendable {383        nonisolated(unsafe) static var handler: (@Sendable (URLRequest) -> (Int, [String: String], Data))?384        nonisolated(unsafe) static var seen: [URLRequest] = []385        override class func canInit(with request: URLRequest) -> Bool { true }386        override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }387        override func startLoading() {388            Stub.seen.append(request)389            let (status, headers, body) = Stub.handler?(request) ?? (500, [:], Data())390            client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: headers)!, cacheStoragePolicy: .notAllowed)391            client?.urlProtocol(self, didLoad: body)392            client?.urlProtocolDidFinishLoading(self)393        }394        override func stopLoading() {}395    }396397    private func make(token: String? = "vqn_test") -> (VQuantAPI, MemoryTokenStore) {398        let cfg = URLSessionConfiguration.ephemeral; cfg.protocolClasses = [Stub.self]399        let store = MemoryTokenStore(token)400        Stub.seen = []401        return (VQuantAPI(client: APIClient(baseURL: URL(string: "https://vquant.spboucher.ai")!, tokens: store, session: URLSession(configuration: cfg))), store)402    }403404    @Test func sendsBearerAndClientTagAndEncodesIndexSymbols() async throws {405        let (api, _) = make()406        Stub.handler = { _ in (200, [:], Data(#"[{"symbol":"^GSPC","price":1}]"#.utf8)) }407        _ = try await api.quote("^GSPC")408        let r = try #require(Stub.seen.first)409        #expect(r.value(forHTTPHeaderField: "Authorization") == "Bearer vqn_test")410        #expect(r.value(forHTTPHeaderField: "X-VQ-Client")?.hasPrefix("vquant-ios/") == true)411        #expect(r.value(forHTTPHeaderField: "Origin") == nil)412        #expect(r.url?.absoluteString == "https://vquant.spboucher.ai/api/fmp/quote/%5EGSPC")413    }414415    @Test func revokedSessionSignsOutLocally() async {416        let (api, _) = make()417        let fired = Flag()418        api.client.onUnauthorized { fired.set() }419        Stub.handler = { _ in (401, ["x-vq-locked": "1"], Data(#"{"error":"Accès verrouillé"}"#.utf8)) }420        do { _ = try await api.me(); Issue.record("expected 401") } catch { #expect((error as? APIError)?.kind == .unauthorized) }421        #expect(fired.value)422    }423424    @Test func errorMapping() async {425        let (api, _) = make()426        let cases: [(Int, String, APIError.Kind)] = [(403, "reauth_required", .reauthRequired), (409, "last_passkey", .conflict), (429, "limited", .rateLimited), (404, "not_found", .notFound), (500, "internal", .server)]427        for (status, code, kind) in cases {428            Stub.handler = { _ in (status, [:], Data("{\"error\":\"\(code)\"}".utf8)) }429            do { try await api.revokePasskey(ref: "abc"); Issue.record("expected \(status)") } catch { #expect((error as? APIError)?.kind == kind) }430        }431    }432433    @Test func refusesPlainHTTPToARemoteHost() {434        let client = APIClient(baseURL: URL(string: "http://vquant.spboucher.ai")!, tokens: MemoryTokenStore("t"))435        #expect(throws: APIError.self) { try client.urlRequest(.get("/api/me")) }436        let local = APIClient(baseURL: URL(string: "http://127.0.0.1:5056")!, tokens: MemoryTokenStore("t"))437        #expect(throws: Never.self) { try local.urlRequest(.get("/api/me")) }438    }439440    @Test func barsAreSortedAndDayRangeKeepsOneSession() async throws {441        let (api, _) = make()442        Stub.handler = { _ in (200, [:], Data(#"[{"date":"2026-11-18 09:35:00","open":2,"high":2,"low":2,"close":2,"volume":1},{"date":"2026-11-18 09:30:00","open":1,"high":1,"low":1,"close":1,"volume":1},{"date":"2026-11-17 15:55:00","open":9,"high":9,"low":9,"close":9,"volume":1}]"#.utf8)) }443        let bars = try await api.bars("AAPL", range: .day, now: MarketDate.parse("2026-11-18 16:00:00")!)444        #expect(bars.map(\.close) == [1, 2])445        let url = try #require(Stub.seen.first?.url?.absoluteString)446        #expect(url.contains("/api/fmp/chart/intraday/AAPL") && url.contains("interval=5min") && url.contains("to=2026-11-18"))447    }448449    @Test func quantJobSubmissionSendsExplicitParams() async throws {450        let (api, _) = make()451        Stub.handler = { _ in (202, [:], Data(#"{"job":{"id":"j","tool":"garch","params":{"symbol":"AAPL","p":1},"status":"running","startedAt":1,"finishedAt":null,"error":null}}"#.utf8)) }452        let job = try await api.startQuantJob(tool: "garch", params: ["symbol": .string("AAPL"), "p": .number(1)])453        #expect(job.status == .running)454        let r = try #require(Stub.seen.first)455        #expect(r.httpMethod == "POST" && r.url?.path == "/api/quant/jobs")456    }457}458459final class Flag: @unchecked Sendable {460    private let lock = NSLock(); private var v = false461    func set() { lock.withLock { v = true } }462    var value: Bool { lock.withLock { v } }463}464
Files main
Menu

Theme