SPB Git

Repository Public

DecodingTests.swift 5.9 KB 91 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/CoreTests/DecodingTests.swift3// Description: Decoding of responses RECORDED from the real backend (Tests/CoreTests/Fixtures, captured 2026-11-18 on the test instance).4import Foundation5import Testing6@testable import VQuantCore78@Suite struct DecodingTests {9    @Test func indicesAndQuotes() throws {10        let idx = try JSONDecoder().decode([Quote].self, from: fixture("indices"))11        #expect(idx.count == 12)12        #expect(idx[0].symbol == "^GSPC" && idx[0].price > 0 && idx[0].changePercent != nil && idx[0].asOf != nil)13        let q = try JSONDecoder().decode([Quote].self, from: fixture("quote"))14        #expect(q.first?.symbol == "AAPL" && q.first?.previousClose != nil && q.first?.marketCap != nil)15        // movers use `changesPercentage` and carry no timestamp16        let g = try JSONDecoder().decode([Quote].self, from: fixture("gainers"))17        #expect(!g.isEmpty && g[0].changePercent != nil && g[0].timestamp == nil)18    }1920    @Test func quoteWithoutPriceIsRejected() {21        #expect(throws: DecodingError.self) { try JSONDecoder().decode(Quote.self, from: Data(#"{"symbol":"X","name":"x"}"#.utf8)) }22    }2324    @Test func barsAreAscendingAndComplete() throws {25        let daily = BarParser.bars(try JSONValue.parse(fixture("chart-full")).arrayValue ?? [])26        #expect(daily.bars.count == 77 && daily.dropped == 0)27        #expect(zip(daily.bars, daily.bars.dropFirst()).allSatisfy { $0.time < $1.time })28        #expect(daily.bars.allSatisfy { $0.low <= min($0.open, $0.close) && $0.high >= max($0.open, $0.close) })29        let intra = BarParser.bars(try JSONValue.parse(fixture("chart-intraday")).arrayValue ?? [])30        #expect(intra.bars.count == 60)31        #expect(BarParser.calendar.component(.minute, from: intra.bars.last!.time) == 55)32    }3334    @Test func malformedBarsAreDroppedNotInvented() {35        let r = BarParser.bars([["date": "2026-11-18", "close": 10], ["date": "nope", "close": 11], ["date": "2026-11-17"], ["date": "2026-11-18", "close": 12]])36        #expect(r.bars.count == 1 && r.dropped == 3 && r.bars[0].close == 12)37    }3839    @Test func profileSearchHours() throws {40        let p = try JSONDecoder().decode([CompanyProfile].self, from: fixture("profile"))41        #expect(p.first?.companyName == "Apple Inc." && p.first?.sector == "Technology")42        #expect(try JSONDecoder().decode([SymbolMatch].self, from: fixture("search")).isEmpty == false)43        #expect(try JSONDecoder().decode([ExchangeHours].self, from: fixture("market-hours")).contains { $0.exchange == "NASDAQ" })44    }4546    @Test func everyDatasetBecomesATable() throws {47        for (name, key) in [("income", "revenue"), ("balance", "totalCurrentAssets"), ("cashflow", "netIncome"), ("metrics", "marketCap"), ("ratios", "grossProfitMargin"), ("estimates", "epsAvg"),48                            ("price-target", "priceTarget"), ("upgrades", "newGrade"), ("earnings", "epsEstimated"), ("dividends", "dividend"), ("holders", "name"), ("insider", "transactionType"), ("news", "title"), ("esg", "ESGScore")] {49            let t = DataTable(rows: try JSONValue.parse(fixture(name)).arrayValue ?? [])50            #expect(!t.rows.isEmpty, "\(name) is empty")51            #expect(t.columns.contains(key), "\(name) lacks \(key)")52        }53        let prices = try JSONValue.parse(fixture("historical"))["historical"]?.arrayValue ?? []54        #expect(DataTable(rows: prices).columns.prefix(2) == ["date", "symbol"])55    }5657    @Test func quantCatalogueAndJobs() throws {58        let cat = try JSONDecoder().decode(QuantCatalogue.self, from: fixture("quant-tools"))59        #expect(cat.tools.map(\.id) == ["garch", "var", "monte_carlo", "options", "portfolio_optimization", "risk_metrics"])60        #expect(cat.tools[0].params.first { $0.name == "p" }?.max == 5)61        let list = try JSONDecoder().decode(QuantJobList.self, from: fixture("quant-jobs"))62        #expect(list.jobs.allSatisfy { $0.status == .done && $0.result == nil })63        for tool in cat.tools.map(\.id) {64            let job = try JSONDecoder().decode(QuantJobEnvelope.self, from: fixture("quant-job-\(tool)")).job65            #expect(job.tool == tool && job.status == .done)66            #expect(job.result?["success"]?.boolValue == true)67            #expect((job.code ?? "").contains("import"))68            #expect(!job.paramSummary.isEmpty && job.duration != nil)69        }70        let v = try JSONDecoder().decode(QuantJobEnvelope.self, from: fixture("quant-job-var")).job71        #expect(v.result?["var_by_confidence"]?["95%"]?["historical"]?["var_dollar"]?.doubleValue != nil)72        #expect(v.subject == "AAPL")73    }7475    @Test func conversationStoredAsJSONString() throws {76        let body = #"{"sessionId":"s1","title":"T","messages":"[{\"question\":\"q\",\"answer\":\"a\",\"toolResults\":[{\"tool\":\"get_stock_quote\",\"result\":[{\"symbol\":\"AAPL\"}]}],\"sources\":[],\"searchQueries\":[],\"pythonCode\":null,\"monteCarloResults\":null,\"customPythonFigures\":[{\"id\":\"fig-1\",\"figures\":[\"AAAA\"],\"figureUrls\":[\"/figures/fig-1-0.png\"],\"output\":\"ok\"}]}]","createdAt":"2026-11-18T12:00:00.000Z","updatedAt":"2026-11-18 12:05:00"}"#77        let c = try JSONDecoder().decode(Conversation.self, from: Data(body.utf8))78        #expect(c.turns.count == 1 && c.turns[0].toolResults[0].tool == "get_stock_quote")79        #expect(c.turns[0].customPythonFigures[0].figureUrls == ["/figures/fig-1-0.png"])80        // the app's own cache round-trips81        let again = try JSONDecoder().decode(Conversation.self, from: JSONEncoder().encode(c))82        #expect(again == c)83        #expect(ServerDate.parse(c.createdAt) != nil && ServerDate.parse(c.updatedAt) != nil)84    }8586    @Test func generationListAndUsage() throws {87        #expect(try JSONDecoder().decode(GenerationList.self, from: fixture("generations")).running == 0)88        #expect(try JSONDecoder().decode(UsageStats.self, from: fixture("stats")).sessions.total > 0)89    }90}91
Files main
Menu

Theme