Repository Public
1//2// VQuant iOS3// File: VQuantTests/AppTests.swift4// Description: Unit tests of the app layer: biometric lock, invitation parsing, routing, quant form parameters,5// background completion detection, Shortcuts summary, stream re-attachment, chart snapshot.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import Foundation12import SwiftUI13import Testing14import UIKit15@testable import VQuant1617@MainActor18@Suite("Verrou biométrique")19struct AppLockTests {20 private func defaults() -> UserDefaults { UserDefaults(suiteName: "vq.test.\(UUID().uuidString)")! }2122 @Test func enablingRequiresPassingTheCheck() async {23 let refused = AppLock(defaults: defaults()) { _ in .failure(.refused) }24 #expect(await refused.setEnabled(true) == false)25 #expect(!refused.isEnabled && refused.lastError != nil)2627 let ok = AppLock(defaults: defaults()) { _ in .success(true) }28 #expect(await ok.setEnabled(true))29 #expect(ok.isEnabled && !ok.isLocked)30 }3132 @Test func disablingAlsoRequiresPassingTheCheck() async {33 let d = defaults(); d.set(true, forKey: "applock.enabled")34 let lock = AppLock(defaults: d) { _ in .failure(.cancelled) }35 #expect(lock.isEnabled && lock.isLocked) // a cold start with the lock on begins locked36 #expect(await lock.setEnabled(false) == false)37 #expect(lock.isEnabled)38 await lock.unlock()39 #expect(lock.isLocked) // cancelled: still locked, and no error shown for a cancel40 #expect(lock.lastError == nil)41 }4243 @Test func graceWindow() async {44 let d = defaults(); d.set(true, forKey: "applock.enabled"); d.set(60, forKey: "applock.grace")45 let lock = AppLock(defaults: d) { _ in .success(true) }46 await lock.unlock()47 #expect(!lock.isLocked)48 let t0 = Date()49 lock.didEnterBackground(now: t0); lock.willEnterForeground(now: t0.addingTimeInterval(30))50 #expect(!lock.isLocked)51 lock.didEnterBackground(now: t0); lock.willEnterForeground(now: t0.addingTimeInterval(61))52 #expect(lock.isLocked)53 }5455 @Test func resetForgetsTheSetting() async {56 let d = defaults()57 let lock = AppLock(defaults: d) { _ in .success(true) }58 _ = await lock.setEnabled(true)59 lock.reset()60 #expect(!lock.isEnabled && d.object(forKey: "applock.enabled") == nil)61 }62}6364@MainActor65@Suite("Session, routage, formulaires")66struct AppLogicTests {67 @Test func invitationParsing() {68 let token = String(repeating: "aB3_-", count: 9)69 #expect(AppModel.inviteToken(from: "https://vquant.spboucher.ai/setup/\(token)") == token)70 #expect(AppModel.inviteToken(from: " https://vquant.spboucher.ai/setup/\(token)?x=1 \n") == token)71 #expect(AppModel.inviteToken(from: token) == token)72 #expect(AppModel.inviteToken(from: "https://vquant.spboucher.ai/setup/short") == nil)73 #expect(AppModel.inviteToken(from: "https://evil.example/setup/\(token)/../x") == token) // only the token is kept; the host is never used74 #expect(AppModel.inviteToken(from: "javascript:alert(1)") == nil)75 }7677 @Test func deepLinks() {78 let r = Router()79 r.handle(URL(string: "vquant://asset/%5EGSPC")!, compact: true)80 #expect(r.section == .markets && r.paths[.markets] == [.asset("^GSPC")])81 r.handle(URL(string: "vquant://quant/abc")!, compact: true)82 #expect(r.section == .research && r.paths[.research]?.last == .quantJob("abc"))83 r.handle(URL(string: "vquant://quant/abc")!, compact: false)84 #expect(r.section == .quant)85 r.handle(URL(string: "vquant://asset/DROP%20TABLE")!, compact: true)86 #expect(r.paths[.markets] == [.asset("^GSPC")]) // refused, nothing pushed87 r.handle(URL(string: "https://example.com/asset/AAPL")!, compact: true)88 #expect(r.paths[.markets] == [.asset("^GSPC")])89 }9091 @Test func quantParametersAreTypedAndEmptyOptionalsOmitted() {92 let tool = QuantTool(id: "var", title: "", summary: "", params: [93 QuantParam(name: "symbol", type: "symbol", label: "Symbol", required: true),94 QuantParam(name: "portfolio_value", type: "number", label: "Value", default: .number(100000), min: 1, max: 1e12),95 QuantParam(name: "confidence_levels", type: "numbers", label: "Levels", default: .array([.number(0.9)]), min: 0.5, max: 0.9999),96 QuantParam(name: "time_horizon", type: "int", label: "Horizon", default: .number(1), min: 1, max: 252),97 QuantParam(name: "volatility", type: "number", label: "Vol", min: 0, max: 10),98 QuantParam(name: "generate_frontier", type: "bool", label: "Frontier", default: .bool(true)),99 QuantParam(name: "symbols", type: "symbols", label: "Symbols", min: 2, max: 30),100 ])101 let p = QuantFormView.parameters(tool: tool, values: ["symbol": " spy ", "portfolio_value": "250000", "confidence_levels": "0,95; 0.99", "time_horizon": "5", "volatility": "", "symbols": "aapl, msft;nvda"],102 flags: ["generate_frontier": false])103 #expect(p["symbol"] == .string("SPY"))104 #expect(p["portfolio_value"] == .number(250000))105 #expect(p["confidence_levels"] == .array([.number(0.95), .number(0.99)]))106 #expect(p["time_horizon"] == .number(5))107 #expect(p["volatility"] == nil)108 #expect(p["generate_frontier"] == .bool(false))109 #expect(p["symbols"] == .array([.string("AAPL"), .string("MSFT"), .string("NVDA")]))110 #expect(QuantFormView.numberList("0.9, 0.95, 0.99") == [0.9, 0.95, 0.99])111 #expect(QuantFormView.numberList("0.9,0.95,0.99") == [0.9, 0.95, 0.99])112 #expect(QuantFormView.numberList("0,9 0,95") == [0.9, 0.95])113 }114115 @Test func positionDraftNumbers() {116 var d = PositionDraft(); d.quantity = "1 250,5"; d.costBasis = "12,34"117 #expect(d.quantityValue == 1250.5 && d.costValue == 12.34)118 d.quantity = "abc"; d.costBasis = "-3"119 #expect(d.quantityValue == nil && d.costValue == nil)120 d.costBasis = ""121 #expect(d.costValue == nil)122 }123124 @Test func backgroundCompletionDetection() {125 let t0 = Date()126 let gens = [Generation(id: "a", sessionId: "s", query: "q", status: .done, startedAt: t0), Generation(id: "b", sessionId: "s2", query: "q", status: .running, startedAt: t0),127 Generation(id: "c", sessionId: "s3", query: "q", status: .done, startedAt: t0)]128 let jobs = [QuantJob(id: "j1", tool: "garch", params: [:], status: .error, startedAt: 0), QuantJob(id: "j2", tool: "var", params: [:], status: .running, startedAt: 0)]129 let r = BackgroundRefresh.finished(tracked: .init(analyses: ["a", "b"], quant: ["j1", "j2"]), generations: gens, jobs: jobs)130 #expect(r.analyses.map(\.id) == ["a"]) // "c" was never tracked on this device: no notification for it131 #expect(r.quant.map(\.id) == ["j1"])132 #expect(r.still.analyses == ["b"] && r.still.quant == ["j2"])133 }134135 @Test func shortcutSummary() {136 let now = Date()137 let gens = [Generation(id: "a", sessionId: "s", query: "secret question", status: .running, startedAt: now),138 Generation(id: "b", sessionId: "s", query: "x", status: .done, startedAt: now, finishedAt: now.addingTimeInterval(-60))]139 let jobs = [QuantJob(id: "j", tool: "garch", params: [:], status: .done, startedAt: 0, finishedAt: now.timeIntervalSince1970 * 1000 - 1000)]140 let s = CheckJobsIntent.sentence(generations: gens, jobs: jobs, now: now)141 #expect(s.contains("En cours : 1 analyse"))142 #expect(s.contains("1 analyse et 1 calcul"))143 #expect(!s.contains("secret")) // never the content of a question144 #expect(CheckJobsIntent.sentence(generations: [], jobs: [], now: now) == "Rien n’est en cours sur le serveur.")145 }146147 @Test func passkeyAssertionShape() {148 let j = PasskeyService.assertionJSON(credentialID: Data([0xfb, 0xff]), clientData: Data("{}".utf8), authenticatorData: Data([1, 2, 3]), signature: Data([9]), userID: Data("simon".utf8), attachment: "platform")149 #expect(j["id"]?.stringValue == "-_8" && j["rawId"]?.stringValue == "-_8") // base64url, no padding150 #expect(j["type"]?.stringValue == "public-key")151 #expect(j["response"]?["userHandle"]?.stringValue == "c2ltb24")152 #expect(j["response"]?["clientDataJSON"]?.stringValue == "e30")153 #expect(Data(base64URLEncoded: "-_8") == Data([0xfb, 0xff]))154 }155156 @Test func preferencesPersist() {157 let d = UserDefaults(suiteName: "vq.test.\(UUID().uuidString)")!158 let p = Preferences(defaults: d)159 #expect(p.hideAmountsInWidgets && p.notifyAnalyses && p.chartRange == .quarter)160 p.chartRange = .year; p.chartConfiguration.overlays = [.sma50, .bollinger]; p.appearance = .dark; p.hideAmountsInWidgets = false161 let q = Preferences(defaults: d)162 #expect(q.chartRange == .year && q.chartConfiguration.overlays == [.sma50, .bollinger] && q.appearance == .dark && !q.hideAmountsInWidgets)163 }164165 @Test func fieldNames() {166 #expect(RecordTable.humanise("netIncomeRatio") == "Net Income Ratio")167 #expect(RecordTable.humanise("evToEBITDA") == "Ev To EBITDA")168 #expect(Fmt.label("forecast_horizon") == "Forecast horizon")169 #expect(Fmt.percent(1.256) == "+1,26 %")170 #expect(Fmt.percent(nil) == "—")171 #expect(Fmt.duration(125) == "2 min 5 s")172 }173}174175/// Serves scripted responses to URLSession: lets a test cut an event stream in the middle.176final class ScriptedProtocol: URLProtocol, @unchecked Sendable {177 struct Step { var status = 200; var headers: [String: String] = [:]; var chunks: [Data] = []; var fail = false }178 nonisolated(unsafe) static var script: [@Sendable (URLRequest) -> Step] = []179 nonisolated(unsafe) static var requests: [URLRequest] = []180 private static let lock = NSLock()181182 override class func canInit(with request: URLRequest) -> Bool { true }183 override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }184 override func startLoading() {185 let step: Step = Self.lock.withLock {186 Self.requests.append(request)187 return Self.script.isEmpty ? Step(status: 500) : Self.script.removeFirst()(request)188 }189 client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: step.status, httpVersion: "HTTP/1.1", headerFields: step.headers)!, cacheStoragePolicy: .notAllowed)190 for c in step.chunks { client?.urlProtocol(self, didLoad: c) }191 if step.fail { client?.urlProtocol(self, didFailWithError: URLError(.networkConnectionLost)) } else { client?.urlProtocolDidFinishLoading(self) }192 }193 override func stopLoading() {}194195 static func api(token: String? = "vqn_test") -> VQuantAPI {196 let cfg = URLSessionConfiguration.ephemeral; cfg.protocolClasses = [ScriptedProtocol.self]197 lock.withLock { requests = []; script = [] }198 return VQuantAPI(client: APIClient(baseURL: URL(string: "https://vquant.spboucher.ai")!, tokens: MemoryTokenStore(token), session: URLSession(configuration: cfg)))199 }200 static func sse(_ events: [(Int?, String)]) -> Data {201 Data(events.map { ($0.0.map { "id: \($0)\n" } ?? "") + "data: \($0.1)\n\n" }.joined().utf8)202 }203}204205@MainActor206@Suite("Suivi d’une analyse", .serialized)207struct RunControllerTests {208 private func wait(_ condition: @MainActor () -> Bool, seconds: Double = 8) async -> Bool {209 let end = Date().addingTimeInterval(seconds)210 while Date() < end { if condition() { return true }; try? await Task.sleep(for: .milliseconds(20)) }211 return condition()212 }213214 @Test func droppedStreamIsResumedFromTheLastEvent() async {215 let api = ScriptedProtocol.api()216 ScriptedProtocol.script = [217 // POST /api/chat: the job starts, two events arrive, then the connection closes before any `done` (a proxy cut, the phone slept)218 { _ in .init(headers: ["Content-Type": "text/event-stream"], chunks: [ScriptedProtocol.sse([(nil, #"{"type":"job","id":"J1","sessionId":"S1","query":"Q"}"#), (0, #"{"type":"text","content":"Bon"}"#), (1, #"{"type":"text","content":"jour"}"#)])]) },219 // GET /api/generations/J1/stream?from=2220 { _ in .init(headers: ["Content-Type": "text/event-stream"], chunks: [ScriptedProtocol.sse([(nil, #"{"type":"job","id":"J1","sessionId":"S1","query":"Q"}"#), (2, #"{"type":"text","content":" !"}"#), (3, #"{"type":"done","sessionId":"S1"}"#)])]) },221 ]222 var finished: AnalysisRun?223 let c = RunController(api: api) { finished = $0.run }224 c.start(ChatRequest(query: "Q"))225 #expect(await wait({ c.run.isFinished }))226 #expect(c.run.answer == "Bonjour !") // nothing lost, nothing duplicated227 #expect(finished?.sessionId == "S1")228 let urls = ScriptedProtocol.requests.map { $0.url!.absoluteString }229 #expect(urls.count == 2)230 guard urls.count == 2 else { return }231 #expect(urls[0].hasSuffix("/api/chat") && ScriptedProtocol.requests[0].httpMethod == "POST")232 #expect(urls[1].hasSuffix("/api/generations/J1/stream?from=2"))233 }234235 @Test func refusedSubmissionIsNotRetried() async {236 let api = ScriptedProtocol.api()237 ScriptedProtocol.script = [{ _ in .init(status: 429, chunks: [Data(#"{"error":"4 analyses tournent déjà."}"#.utf8)]) }]238 let c = RunController(api: api)239 c.start(ChatRequest(query: "Q"))240 #expect(await wait({ c.run.isFinished }))241 #expect(c.run.error == "4 analyses tournent déjà.")242 try? await Task.sleep(for: .milliseconds(300))243 #expect(ScriptedProtocol.requests.count == 1) // a paid analysis is never re-submitted automatically244 }245246 @Test func responseWithoutAJobIsAnErrorNotAnEndlessWait() async {247 let api = ScriptedProtocol.api()248 ScriptedProtocol.script = [{ _ in .init(headers: ["Content-Type": "text/event-stream"], chunks: []) }]249 let c = RunController(api: api)250 c.start(ChatRequest(query: "Q"))251 #expect(await wait({ c.run.isFinished }))252 #expect(c.run.error != nil && c.run.jobId == nil)253 #expect(ScriptedProtocol.requests.count == 1)254 }255256 @Test func jobGoneFromServerMemoryEndsQuietly() async {257 let api = ScriptedProtocol.api()258 ScriptedProtocol.script = [{ _ in .init(status: 404, chunks: [Data(#"{"error":"Cette analyse n'est plus en mémoire."}"#.utf8)]) }]259 let c = RunController(api: api)260 c.attach(jobId: "old")261 #expect(await wait({ c.run.isFinished }))262 #expect(c.run.error == nil)263 }264}265266@MainActor267@Suite("Graphiques")268struct ChartTests {269 private func bars(_ n: Int) -> [Bar] {270 (0..<n).map { i in271 let base = 100 + 10 * sin(Double(i) / 9) + Double(i) * 0.05272 return Bar(date: MarketDate.parse("2026-01-02")!.addingTimeInterval(Double(i) * 86_400), open: base, high: base + 1.5, low: base - 1.2, close: base + (i % 2 == 0 ? 0.8 : -0.6), volume: 1_000_000 + Double(i) * 1000)273 }274 }275276 private func averageLuminance(_ png: Data) -> Double? {277 guard let cg = UIImage(data: png)?.cgImage else { return nil }278 var px = [UInt8](repeating: 0, count: 4 * 16 * 16)279 guard let ctx = CGContext(data: &px, width: 16, height: 16, bitsPerComponent: 8, bytesPerRow: 64, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }280 ctx.draw(cg, in: CGRect(x: 0, y: 0, width: 16, height: 16))281 var sum = 0.0282 for i in stride(from: 0, to: px.count, by: 4) { sum += 0.2126 * Double(px[i]) + 0.7152 * Double(px[i + 1]) + 0.0722 * Double(px[i + 2]) }283 return sum / Double(16 * 16) / 255284 }285286 @Test func snapshotRendersInBothAppearances() throws {287 let cfg = ChartConfiguration(kind: .candles, overlays: [.sma20, .bollinger], panels: [.volume, .rsi, .macd])288 let dark = try #require(ChartSnapshot.png(bars: bars(300), configuration: cfg, intraday: false, title: "TEST", subtitle: "300 observations", colorScheme: .dark))289 let light = try #require(ChartSnapshot.png(bars: bars(300), configuration: cfg, intraday: false, title: "TEST", subtitle: "300 observations", colorScheme: .light))290 let img = try #require(UIImage(data: dark))291 #expect(img.cgImage?.width == 1200 && img.cgImage?.height == 750)292 let ld = try #require(averageLuminance(dark)), ll = try #require(averageLuminance(light))293 #expect(ld < 0.35, "dark snapshot should have a dark background, luminance \(ld)")294 #expect(ll > 0.65, "light snapshot should have a light background, luminance \(ll)")295 }296297 @Test func snapshotOfNothingIsNil() {298 #expect(ChartSnapshot.png(bars: [], configuration: ChartConfiguration(), intraday: false, title: "", subtitle: "") == nil)299 }300301 @Test func largeSeriesRendersEveryKind() throws {302 let many = bars(12_000)303 for kind in ChartKind.allCases {304 let png = ChartSnapshot.png(bars: many, configuration: ChartConfiguration(kind: kind, overlays: Set(ChartOverlay.allCases), panels: Set(ChartPanel.allCases)), intraday: false, title: kind.label, subtitle: "")305 #expect(png != nil)306 }307 }308}309310/// Runs against a development copy of the backend when the test runner provides one (`TEST_RUNNER_VQUANT_BASE_URL`311/// and `TEST_RUNNER_VQUANT_TEST_TOKEN`, set by Scripts/test-live.sh). Never the production server, never a trade.312@Suite("Backend réel (copie de test)", .enabled(if: ProcessInfo.processInfo.environment["VQUANT_TEST_TOKEN"] != nil), .serialized)313struct LiveBackendTests {314 private var api: VQuantAPI {315 let env = ProcessInfo.processInfo.environment316 return VQuantAPI(client: APIClient(baseURL: URL(string: env["VQUANT_BASE_URL"] ?? "http://127.0.0.1:5056")!, tokens: MemoryTokenStore(env["VQUANT_TEST_TOKEN"]), clientTag: "vquant-ios/1.0.0 (1)"))317 }318319 @Test func sessionAndAccount() async throws {320 let s = try await api.session()321 #expect(!s.user.id.isEmpty && s.device.platform == "ios")322 #expect(try await api.me().id == s.user.id)323 let d = try await api.devices()324 #expect(d.sessions.contains { $0.current == true } && !d.passkeys.isEmpty)325 }326327 @Test func revokedOrUnknownTokenIsRefused() async {328 let bad = VQuantAPI(client: APIClient(baseURL: api.client.baseURL, tokens: MemoryTokenStore("vqn_" + String(repeating: "x", count: 43))))329 let fired = LockedFlag()330 bad.client.onUnauthorized { fired.set() }331 do { _ = try await bad.me(); Issue.record("expected 401") } catch { #expect((error as? APIError)?.kind == .unauthorized) }332 #expect(fired.value)333 }334335 @Test func sensitiveOperationsRequireFreshPasskeyVerification() async throws {336 // A test token is minted without a passkey ceremony older than five minutes → the server must demand re-authentication.337 let d = try await api.devices()338 guard !d.reauthFresh else { return } // freshly minted token: nothing to assert yet339 do { try await api.revokePasskey(ref: "000000000000000000000000"); Issue.record("expected a refusal") }340 catch { #expect((error as? APIError)?.kind == .reauthRequired) }341 }342343 @Test func marketData() async throws {344 let idx = try await api.indices()345 #expect(idx.count >= 8 && idx.allSatisfy { $0.price > 0 })346 let q = try await api.quote("AAPL")347 #expect(q.symbol == "AAPL" && q.price > 0 && q.timestamp != nil)348 let daily = try await api.bars("AAPL", range: .quarter)349 #expect(daily.count > 40)350 #expect(zip(daily, daily.dropFirst()).allSatisfy { $0.date < $1.date })351 #expect(daily.allSatisfy { $0.high >= $0.low && $0.high >= max($0.open, $0.close) - 1e-9 })352 let intraday = try await api.bars("AAPL", range: .day)353 #expect(Set(intraday.map { MarketDate.day($0.date) }).count <= 1)354 #expect(try await api.search("microsoft").contains { $0.symbol == "MSFT" })355 #expect(try await api.fundamentals(.income, symbol: "AAPL").first?["revenue"]?.doubleValue ?? 0 > 0)356 #expect(try await api.marketHours().contains { $0.exchange == "NASDAQ" })357 }358359 @Test func unknownSymbolIsAnErrorNotAZero() async {360 do { _ = try await api.quote("ZZZZNOTREAL"); Issue.record("expected not found") } catch { #expect((error as? APIError)?.kind == .notFound) }361 }362363 @Test func quantJobLifecycle() async throws {364 let tools = try await api.quantTools()365 #expect(tools.tools.contains { $0.id == "risk_metrics" })366 var job = try await api.startQuantJob(tool: "risk_metrics", params: ["symbol": .string("MSFT")])367 #expect(job.status == .running)368 #expect(job.params["benchmark_symbol"]?.stringValue == "SPY") // the server wrote its default out369 for _ in 0..<60 where job.status == .running { try await Task.sleep(for: .seconds(1)); job = try await api.quantJob(job.id) }370 #expect(job.status == .done)371 #expect(job.code?.isEmpty == false)372 let sections = QuantResult.sections(try #require(job.result))373 #expect(sections.contains { $0.title == "risk_adjusted_metrics" })374 #expect(try await api.quantJobs().jobs.contains { $0.id == job.id })375 try await api.deleteQuantJob(job.id)376 do { _ = try await api.quantJob(job.id); Issue.record("expected 404") } catch { #expect((error as? APIError)?.kind == .notFound) }377 }378379 @Test func quantValidationErrorsComeFromTheServer() async {380 do { _ = try await api.startQuantJob(tool: "garch", params: ["symbol": .string("AAPL"), "p": .number(99)]); Issue.record("expected 400") }381 catch { let e = error as? APIError; #expect(e?.kind == .badRequest); #expect(e?.message.contains("between") == true) }382 }383384 @Test func workspaceAndConversations() async throws {385 let w = try await api.workspace()386 #expect(!w.user.id.isEmpty)387 let list = try await api.conversations()388 if let first = list.first {389 let c = try await api.conversation(first.sessionId)390 #expect(c.sessionId == first.sessionId)391 }392 #expect(try await api.generations().running >= 0)393 }394395 /// 1.0 wrote a position through `/api/workspace/portfolio/:symbol`. On backend 6 that route writes `portfolio/main`396 /// (the agent's portfolio), which tests must not touch: 2.0 no longer calls it, and the position round trip is397 /// made on the test portfolio through the object store (`NextLiveTests`, UI test `testPortfolioPositionLifecycle`).398 /// What remains here is the read route, still used for the memory and the watches.399 @Test func workspaceStillAnswersOnBackendSix() async throws {400 let w = try await api.workspace()401 #expect(w.positions.allSatisfy { !$0.symbol.isEmpty })402 }403}404405final class LockedFlag: @unchecked Sendable {406 private let lock = NSLock(); private var v = false407 func set() { lock.withLock { v = true } }408 var value: Bool { lock.withLock { v } }409}410