Repository Public
1import Foundation2import SwiftUI3import Testing4import VQuantKit5@testable import VQuantUI67@Suite struct SVGPathTests {8 @Test func basicCommandsAbsoluteAndRelative() {9 let p = VQSVGPath.path("M10 10 H 20 V 20 h-10 z")10 #expect(p.boundingRect == CGRect(x: 10, y: 10, width: 10, height: 10))11 #expect(VQSVGPath.path("m10,10 l10,0 0,10 -10,0z").boundingRect == CGRect(x: 10, y: 10, width: 10, height: 10)) // implicit repeats12 #expect(VQSVGPath.path("M0 0L1.5.5-2-3").boundingRect == CGRect(x: -2, y: -3, width: 3.5, height: 3.5)) // compact numbers13 #expect(VQSVGPath.path("M0 0 Q 5 10 10 0 T 20 0").boundingRect.width == 20)14 #expect(VQSVGPath.path("M0 0 C 0 10 10 10 10 0 S 20 -10 20 0").boundingRect.maxX == 20)15 #expect(VQSVGPath.path("").isEmpty && VQSVGPath.path("garbage").isEmpty)16 }1718 @Test func arcsBecomeCurvesOnTheCircle() {19 // a full circle of radius 5 centred on (5,5) as two arcs, with glued flags ("0 01")20 let p = VQSVGPath.path("M0 5a5 5 0 0110 0a5 5 0 01-10 0z")21 let r = p.boundingRect22 #expect(abs(r.minX) < 0.01 && abs(r.minY) < 0.01 && abs(r.width - 10) < 0.02 && abs(r.height - 10) < 0.02)23 #expect(p.contains(CGPoint(x: 5, y: 5)) && !p.contains(CGPoint(x: 0.3, y: 0.3)))24 // radii too small are scaled up (SVG F.6.6)25 #expect(abs(VQSVGPath.path("M0 0 A 1 1 0 0 1 10 0").boundingRect.width - 10) < 0.02)26 }2728 @Test(arguments: VQProviderMark.allCases)29 func providerMarksFillTheirViewBox(_ mark: VQProviderMark) {30 let r = mark.path.boundingRect31 #expect(!mark.path.isEmpty)32 #expect(r.minX >= -0.01 && r.minY >= -0.01 && r.maxX <= 24.01 && r.maxY <= 24.01, "\(mark) leaves the 24 × 24 box: \(r)")33 #expect(r.width > 17 && r.height > 15, "\(mark) is too small: \(r)")34 }35}3637@Suite struct MarkdownTests {38 @Test func blocksAndFormulas() {39 let blocks = VQMarkdown.blocks("# Title\n\n**Returns.** $r_t = \\ln(P_t/P_{t-1})$ from closes;\nsecond line.\n\n- one\n- two $\\sigma$\n\n1. first\n2. second\n\n```\ncode $x$\n```")40 #expect(blocks.count == 5)41 #expect(blocks[0] == .heading(level: 1, text: "Title"))42 #expect(blocks[2] == .bullets(["one", "two $\\sigma$"]) && blocks[3] == .numbered(["first", "second"]) && blocks[4] == .code("code $x$"))43 let seg = VQMarkdown.segments("Vol is $\\sigma_t\\sqrt{A}$ with $A$ = 252, costs $5.")44 #expect(seg.map(\.isMath) == [false, true, false, true, false])45 #expect(seg.last?.text == " = 252, costs $5.") // an unpaired $ is money46 }4748 @Test func latexIsMadeReadable() {49 #expect(VQMarkdown.readableMath(#"\sigma_t^2 = \omega + \sum_i \alpha_i\varepsilon_{t-i}^2"#) == "σ_t^2 = ω + ∑_i α_iε_{t-i}^2")50 #expect(VQMarkdown.readableMath(#"\sigma_t\sqrt{A}"#) == "σ_t√(A)")51 #expect(VQMarkdown.readableMath(#"\frac{a}{b} \le \infty, x \in S, \left(\ln 0.5\right)"#) == "(a)/(b) ≤ ∞, x ∈ S, (ln 0.5)")52 #expect(VQMarkdown.readableMath(#"\mathbf{1}(\varepsilon_{t-i}<0)"#) == "1(ε_{t-i}<0)")53 let a = VQMarkdown.attributed("**bold** and $\\beta$")54 #expect(String(a.characters).contains("bold and") && String(a.characters).contains("β"))55 }56}5758@Suite struct ChartDataTests {59 private func series(_ n: Int) -> [VQChartPoint] { (0..<n).map { VQChartPoint(x: .number(Double($0)), y: sin(Double($0) / 37) * 10 + ($0 == 4321 ? 500 : 0) - ($0 == 7777 ? 400 : 0), index: $0) } }6061 @Test func downsamplingKeepsExtremesAndEnds() {62 let points = series(20_000)63 let reduced = VQLabChartData.downsample(points, limit: 600)64 #expect(reduced.count <= 600 && reduced.count > 300)65 #expect(reduced.first == points.first && reduced.last == points.last)66 #expect(reduced.map(\.y).max() == points.map(\.y).max() && reduced.map(\.y).min() == points.map(\.y).min()) // the spikes survive67 #expect(zip(reduced, reduced.dropFirst()).allSatisfy { $0.index < $1.index })68 #expect(VQLabChartData.downsample(series(500), limit: 600).count == 500) // short series untouched69 let categories = (0..<1000).map { VQChartPoint(x: .category("c\($0)"), y: 1, index: $0) }70 #expect(VQLabChartData.downsample(categories, limit: 100).count == 1000) // categories are never dropped71 }7273 @Test func holesSplitLinesAndAxesAreRead() {74 let s = VQLabResult.Chart.Series(json: ["name": "s", "kind": "observed", "x": ["2026-01-01", "2026-01-02", "2026-01-03", "2026-01-04", "bad"], "y": [1, .null, 3, 4, 5]])75 let pts = VQLabChartData.points(s, axis: .time)76 #expect(pts.map(\.index) == [0, 2, 3])77 #expect(VQLabChartData.segments(pts).map(\.count) == [1, 2])78 let chart = VQLabResult.Chart(json: ["type": "line", "x": ["type": "time"], "y": [:], "series": [["name": "s", "x": ["AAPL 2024-02-01"], "y": [1]]]])79 #expect(VQLabChartData.effectiveAxis(chart) == .category) // not dates: categories80 #expect(VQLabChartData.minimumSpacing([3, 1, 2.5, 1, 7]) == 0.5)81 let ascending = series(100)82 #expect(VQLabChartData.nearestIndex(ascending, to: 41.4) == 41 && VQLabChartData.nearestIndex(ascending, to: -5) == 0 && VQLabChartData.nearestIndex(ascending, to: 1e9) == 99)83 }8485 @Test func colourScalesAndTables() {86 let m = VQLabResult.Chart.Matrix(json: ["x": ["a", "b"], "y": ["r1", "r2"], "z": [[-1, 0.5], [.null, 1]]])87 let scale = try! #require(VQLabChartData.colorScale(m))88 #expect(scale.diverging && scale.position(0) == 0.5 && scale.band(-1, steps: 7) == 0 && scale.band(1, steps: 7) == 6 && scale.band(0, steps: 7) == 3)89 #expect(scale.levels(steps: 7).first == -1 && scale.levels(steps: 7).last == 1)90 let sequential = VQLabChartData.ColorScale(minimum: 0.14, maximum: 0.82, diverging: false)91 #expect(sequential.band(0.14, steps: 7) == 0 && sequential.band(0.82, steps: 7) == 6)92 let chart = VQLabResult.Chart(json: ["title": "t", "type": "heatmap", "x": ["label": "X", "type": "category"], "y": ["label": "Y"], "matrix": ["x": ["a", "b"], "y": ["r1"], "z": [[1, .null]]]])93 #expect(VQExport.csv(chart: chart) == "Y,a,b\nr1,1,\n")94 let line = VQLabResult.Chart(json: ["type": "line", "x": ["label": "Date", "type": "time"], "y": ["label": "v"], "series": [["name": "A, B", "x": ["2026-01-01"], "y": [1.5]]]])95 #expect(VQExport.csv(chart: line) == "Date,\"A, B\"\n2026-01-01,1.5\n")96 #expect(!VQLabChartData.summary(of: line, language: .en).isEmpty)97 }9899 @Test func axisDecimalsAndLogTicks() {100 #expect(LabAxis.decimals(forSpan: 30) == 0 && LabAxis.decimals(forSpan: 1) == 1 && LabAxis.decimals(forSpan: 0.12) == 2 && LabAxis.decimals(forSpan: 5000) == 0)101 #expect(LabAxis.logTicks(100...320) == [100, 150, 200, 300])102 #expect(LabAxis.logTicks(1...5.4) == [1, 2, 5])103 #expect(LabAxis.logTicks(0.5...2000).contains(100))104 }105}106107@Suite @MainActor struct RenderTests {108 private func fixture(_ name: String) throws -> VQLabResult {109 // the kit's test fixtures, read from the source tree110 let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("VQuantKitTests/Fixtures/job_\(name).json")111 return try #require(VQQuantJob(json: try VQJSON.parse(Data(contentsOf: url))["job"] ?? .null).labResult)112 }113114 @Test func aResultRendersToPNGInBothAppearances() throws {115 let result = try fixture("options_price")116 for scheme in [ColorScheme.light, .dark] {117 let data = try #require(VQExport.png(LabResultView(result), width: 900, colorScheme: scheme, scale: 1))118 #expect(data.prefix(4) == Data([0x89, 0x50, 0x4E, 0x47]) && data.count > 50_000)119 }120 }121122 @Test func aChartExportsToPNGAndVectorPDF() throws {123 let chart = try #require(try fixture("time_series").charts.first { $0.type == .fan })124 let png = try #require(VQExport.png(chart: chart))125 #expect(png.count > 20_000)126 let pdf = try #require(VQExport.pdf(chart: chart))127 #expect(String(decoding: pdf.prefix(5), as: UTF8.self) == "%PDF-")128 }129130 @Test func darkAndLightRendersDiffer() throws {131 let view = VQMetricTile(label: "VaR", value: 0.02, unit: .percent, kind: .calculated)132 let light = try #require(VQExport.png(view, width: 240, colorScheme: .light, scale: 1))133 let dark = try #require(VQExport.png(view, width: 240, colorScheme: .dark, scale: 1))134 #expect(light != dark)135 }136137 @Test func themeFollowsThePreference() {138 var p = VQPreference()139 p.upDownColors = .known(.cvd); p.numberFormat = "en-CA"; p.reduceMotion = true140 let theme = VQTheme(preference: p, language: .en)141 #expect(theme.upDown == .cvd && theme.numberLocale == .enCA && theme.reduceMotion)142 #expect(VQTheme(preference: VQPreference()).upDown == .classic)143 }144}145146@Suite @MainActor struct ResearchViewTests {147 private func json(_ name: String) throws -> VQJSON {148 let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("VQuantKitTests/Fixtures/research/\(name)")149 return try VQJSON.parse(Data(contentsOf: url))150 }151152 @Test func everyResearchViewRendersFromTheRecordedStudy() throws {153 let detail = VQResearchSessionDetail(json: try json("session.json"))154 let live = VQResearchReducer.replay(try json("stream_study.json").arrayValue ?? [])155 let state = live.merged(over: VQResearchState(detail: detail, conversation: try json("conversation.json")).filtered(generationId: live.generationId ?? ""))156 #expect(state.counts.executions == 56 && state.counts.failed == 4 && state.figures.count == 14)157 let store = VQResearchSessionStore(state: state, detail: detail, sandbox: VQSandboxStatus(json: try json("sandbox.json")))158 var preload = ResearchPreload()159 let code = VQResearchFilePreview(json: try json("file_code.json"))160 preload.texts[code.path] = code.text161 func png<V: View>(_ v: V, width: CGFloat = 700) -> Int { VQExport.png(v.researchPreload(preload), width: width, scale: 1)?.count ?? 0 }162 #expect(png(ResearchActivityView(store: store)) > 60_000)163 for section in ResearchActivityView.Section.allCases {164 #expect(png(ResearchActivityView(store: store, initial: section, selectedFile: code.path), width: 390) > 20_000, "section \(section)")165 #expect(!ResearchActivityView.title(section, .fr).isEmpty)166 }167 #expect(png(ResearchExecutionList(state.executions, expanded: Set(state.executions.prefix(3).map(\.key)))) > 40_000)168 #expect(png(ResearchExperimentsTable(state.experiments)) > 40_000 && png(ResearchRunsList(state.runs)) > 10_000 && png(ResearchFiguresGrid(state.figures)) > 10_000)169 #expect(png(ResearchFilePreview(path: code.path)) > 10_000 && png(ResearchEnvironmentPanel(sandbox: nil)) > 500 && png(ResearchQualityGateView([])) > 500)170 let approval = VQResearchApproval(json: ["id": "a", "action": "send_data", "reason": "r", "status": "pending", "createdAt": 1_795_300_000_000])171 let pending = png(ResearchApprovalCard(approval, now: Date(timeIntervalSince1970: 1_795_300_060), onApprove: {}, onRefuse: {}))172 let expired = png(ResearchApprovalCard(approval, now: Date(timeIntervalSince1970: 1_795_302_000), onApprove: {}, onRefuse: {}))173 #expect(pending > 5_000 && expired > 5_000)174 // an empty study is an honest empty state, not a crash175 #expect(png(ResearchActivityView(store: VQResearchSessionStore())) > 2_000)176 }177178 @Test func pythonColouringCoversTheWholeSource() {179 let src = "def f(x):\n return \"é\" + str(x) # ünïcode\n"180 let a = ResearchCodeView.attributed(src)181 #expect(String(a.characters) == src)182 let colours = Set(a.runs.compactMap { $0.foregroundColor })183 #expect(colours.count >= 4) // keyword, definition, string, comment, plain184 #expect(String(ResearchCodeView.attributed(String(repeating: "x = 1\n", count: 20_000)).characters).count == 120_000) // large input: plain, instant185 #expect(VQImageData.cgImage(Data("not an image".utf8)) == nil)186 }187}188189/// VQuantKit 0.3: the renderer rules of CONTRACT §4.2 and the research additions of §9.6.190@Suite @MainActor struct V03ViewTests {191 private func fixture(_ name: String) throws -> VQJSON {192 try VQJSON.parse(Data(contentsOf: URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("VQuantKitTests/Fixtures/\(name)")))193 }194195 @Test func bandsFollowTheLineFlagAndOldResultsDrawAsBefore() throws {196 func marks(_ file: String, _ chartType: VQLabResult.Chart.ChartType) throws -> [LabMark] {197 let r = try #require(VQQuantJob(json: try fixture(file)["job"] ?? .null).labResult)198 return LabChartModel(try #require(r.charts.first { $0.type == chartType }), maxPoints: 600).series.map(\.mark)199 }200 // new: three bands without a centre line, the median as a band with its line201 #expect(try marks("job_time_series.json", .fan) == [.line, .band, .band, .band, .bandLine])202 // the same chart recorded before `line` existed203 #expect(try marks("lab_v0/job_time_series.json", .fan) == [.line, .band, .band, .band, .line])204 // error bars stay bars205 let event = try #require(VQQuantJob(json: try fixture("job_event_study.json")["job"] ?? .null).labResult)206 #expect(LabChartModel(try #require(event.charts.first { $0.id == "aar" }), maxPoints: 600).series.map(\.mark) == [.bar])207 }208209 @Test func candlesRenderAndFallBackToALine() throws {210 let chart = VQLabResult.Chart(json: ["id": "c", "title": "AAPL", "type": "candles", "x": ["label": "Date", "type": "time"], "y": ["label": "Price", "unit": "currency", "currency": "CAD"],211 "series": [["name": "AAPL", "kind": "observed", "x": ["2026-11-18", "2026-11-19", "2026-11-20"], "open": [350, 352, 349], "high": [355, 353, 354.3], "low": [348, 346, 340.6], "close": [352, 349.2, 342.6], "y": [352, 349.2, 342.6]]]])212 let model = LabChartModel(chart, maxPoints: 600)213 #expect(model.series.map(\.mark) == [.candles] && model.yRange == 340.6...355 && model.candles[0] != nil) // the range covers highs and lows214 #expect(LabAxis.yTitle(chart, language: .fr) == "Price (CAD)" && LabAxis.xTitle(chart) == "Date")215 #expect((VQExport.png(chart: chart)?.count ?? 0) > 10_000)216 // without the four arrays a candles chart is a line of `y`217 let plain = VQLabResult.Chart(json: ["id": "c", "title": "AAPL", "type": "candles", "x": ["label": "Date", "type": "time"], "y": ["label": "Price"], "series": [["name": "AAPL", "x": ["2026-11-18", "2026-11-19"], "y": [352, 349.2]]]])218 #expect(LabChartModel(plain, maxPoints: 600).series.map(\.mark) == [.line])219 }220221 @Test func newAndOldLabResultsRender() throws {222 for file in ["job_portfolio_lab.json", "lab_v0/job_portfolio_lab.json", "job_backtest.json", "lab_v0/job_backtest.json"] {223 let r = try #require(VQQuantJob(json: try fixture(file)["job"] ?? .null).labResult)224 #expect((VQExport.png(LabResultView(r), width: 900, scale: 1)?.count ?? 0) > 100_000, "\(file)")225 }226 let chain = try #require(VQQuantJob(json: try fixture("job_options_chain.json")["job"] ?? .null).labResult)227 let surface = try #require(chain.charts.first { $0.type == .surface })228 #expect(surface.cellAxis.label == "Implied volatility" && LabAxis.xText(0.25, chart: VQLabResult.Chart(json: ["x": ["type": "number", "unit": "percent"], "y": [:]]), span: 0.5, locale: .frCA) == "25\u{00A0}%")229 }230231 @Test func approvalCardStatesFromTheRecordedSequences() throws {232 let streams = try fixture("research/approval_stream.json")233 var images: [Data] = []234 for name in ["approved", "denied"] {235 let events = streams[name]!.list("events")236 var mid = VQResearchState()237 for e in events { VQResearchReducer.reduce(&mid, e); if e.str("type") == "approval_request" { break } }238 let pending = try #require(mid.pendingApprovals.first), resolved = try #require(VQResearchReducer.replay(events).approvals.first)239 let asked = try #require(pending.createdAt)240 for (a, now) in [(pending, asked.addingTimeInterval(5)), (pending, asked.addingTimeInterval(14 * 60)), (pending, asked.addingTimeInterval(16 * 60)), (resolved, asked.addingTimeInterval(60))] {241 images.append(try #require(VQExport.png(ResearchApprovalCard(a, now: now, onApprove: {}, onRefuse: {}), width: 600, scale: 1)))242 }243 #expect(!resolved.isAnswerable(now: asked.addingTimeInterval(5)) && pending.isAnswerable(now: asked.addingTimeInterval(5)) && !pending.isAnswerable(now: asked.addingTimeInterval(16 * 60)))244 }245 #expect(Set(images).count == images.count) // waiting, urgent, expired, approved and denied all look different246 }247248 @Test func aReopenedStudyShowsItsPlanAndQuietVerdicts() throws {249 let detail = VQResearchSessionDetail(json: try fixture("research/session_v03_439f8b56.json"))250 let state = VQResearchState(detail: detail)251 let store = VQResearchSessionStore(state: state, detail: detail)252 #expect(store.budgetApplied?.maxMinutes == 5 && store.generations.count == 1 && state.figures.first?.lintStatus == .fixed)253 #expect((VQExport.png(ResearchActivityView(store: store), width: 700, scale: 1)?.count ?? 0) > 30_000)254 #expect((VQExport.png(ResearchFiguresGrid(state.figures), width: 700, scale: 1)?.count ?? 0) > 5_000)255 // multi-line strings keep their colour line by line in an export256 let lines = ResearchCodeView.attributedLines("x = '''a\nb'''\ny = 1")257 #expect(lines.count == 3 && String(lines[1].characters) == "b'''" && lines[1].runs.first?.foregroundColor == lines[0].runs.last?.foregroundColor)258 }259}260261/// VQuantKit 0.4: one language per hierarchy, taken from the String Catalog, with an override an app can set.262@Suite @MainActor struct LanguageTests {263 @Test func theOverrideWinsOverTheThemeAndNilReturnsToIt() {264 var env = EnvironmentValues()265 env.vqTheme = VQTheme(upDown: .cvd, language: .fr)266 #expect(env.vqTheme.language == .fr)267 env.vqLanguage = .en268 #expect(env.vqTheme.language == .en && env.vqTheme.upDown == .cvd) // only the language is forced269 env.vqTheme = VQTheme(language: .fr)270 #expect(env.vqTheme.language == .en)271 env.vqLanguage = nil272 #expect(env.vqTheme.language == .fr)273 }274275 @Test func sectionTitlesAndBadgesComeFromTheCatalog() {276 #expect(ResearchActivityView.Section.allCases.map { ResearchActivityView.title($0, .en) } == ["Activity", "Code", "Experiments", "Figures", "Runs", "Files", "Environment"])277 #expect(ResearchActivityView.Section.allCases.map { ResearchActivityView.title($0, .fr) } == ["Activité", "Code", "Expériences", "Figures", "Exécutions", "Fichiers", "Environnement"])278 #expect(VQProviderMark.local.displayName(.fr) == "Modèle local" && VQProviderMark.local.displayName(.en) == "Local model")279 #expect(VQProviderMark.openai.displayName(.fr) == "OpenAI")280 }281282 @Test func aViewRendersInTheForcedLanguage() throws {283 let approval = VQResearchApproval(json: ["id": "a", "action": "raise_budget", "reason": "More time.", "detail": ["maxMinutes": 90], "status": "pending", "createdAt": 0])284 let now = Date(timeIntervalSince1970: 60)285 func card() -> some View { ResearchApprovalCard(approval, now: now, onApprove: {}, onRefuse: {}) }286 let fr = try #require(VQExport.png(card(), width: 520, colorScheme: .light, theme: VQTheme(language: .fr)))287 let en = try #require(VQExport.png(card(), width: 520, colorScheme: .light, theme: VQTheme(language: .en)))288 let forced = try #require(VQExport.png(card().vqLanguage(.en), width: 520, colorScheme: .light, theme: VQTheme(language: .fr)))289 let byLocale = try #require(VQExport.png(card().vqLanguage(locale: Locale(identifier: "fr_CA")), width: 520, colorScheme: .light, theme: VQTheme(language: .en)))290 #expect(fr != en && forced != fr && byLocale != en)291 // what a component reads inside each hierarchy292 final class Seen: @unchecked Sendable { var languages: [VQLanguage] = [] }293 struct Probe: View {294 let seen: Seen295 @Environment(\.vqTheme) private var theme296 var body: some View { seen.languages.append(theme.language); return Text(theme.language.rawValue) }297 }298 let seen = Seen()299 _ = VQExport.png(Probe(seen: seen), width: 100, colorScheme: .light, theme: VQTheme(language: .fr))300 _ = VQExport.png(Probe(seen: seen).vqLanguage(.en), width: 100, colorScheme: .light, theme: VQTheme(language: .fr))301 _ = VQExport.png(Probe(seen: seen).vqLanguage(locale: Locale(identifier: "fr_CA")), width: 100, colorScheme: .light, theme: VQTheme(language: .en))302 _ = VQExport.png(Probe(seen: seen).vqLanguage(nil).vqLanguage(.en), width: 100, colorScheme: .light, theme: VQTheme(language: .fr))303 var distinct: [VQLanguage] = []304 for l in seen.languages where distinct.last != l { distinct.append(l) }305 #expect(distinct == [.fr, .en, .fr]) // French theme; forced English; forced French by locale; an inner nil returns to the theme (French)306 }307}308