Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/CoreTests/StudioIntegrationTests.swift3// Description: Portfolios and Research Studio routes against the REAL VQuant Next test backend (5058, never production): project bundle, exports (md, zip, tex, pdf), note versions, batched quotes. Enabled by VQ_IT_URL + VQ_IT_TOKEN (a development session of Scripts/dev-session.sh). Objects are prefixed mac-test- and deleted.4import Foundation5import Testing6@testable import VQuantCore78private enum SIT {9 static let env = ProcessInfo.processInfo.environment10 static var enabled: Bool { env["VQ_IT_URL"] != nil && (env["VQ_IT_TOKEN"] ?? "").hasPrefix("vqn_") }11 static let client: APIClient = {12 let url = URL(string: env["VQ_IT_URL"] ?? "http://localhost:5058")!13 precondition(["localhost", "127.0.0.1"].contains(url.host ?? "") && url.port == 5058, "integration tests only run against the 5058 test backend")14 return APIClient(baseURL: url, identity: ClientIdentity(version: "2.0.0", build: "it", deviceName: "Mac d’essai (studio)"), tokens: MemoryTokenStore(env["VQ_IT_TOKEN"]), transport: URLSessionTransport())15 }()16 static let run = String(UUID().uuidString.prefix(8)).lowercased()1718 static func put(_ kind: String, _ id: String, _ data: JSONValue, baseRev: Int) async throws -> JSONValue {19 try await client.json(.put, "/api/v2/objects/\(kind)/\(id)", body: ["data": data, "baseRev": .number(Double(baseRev))])20 }21 static func delete(_ kind: String, _ id: String) async {22 guard let o = try? await client.json(.get, "/api/v2/objects/\(kind)/\(id)"), let rev = o["object"]?["rev"]?.doubleValue else { return }23 _ = try? await client.data(.delete, "/api/v2/objects/\(kind)/\(id)", query: ["baseRev": String(Int(rev))])24 }25}2627@Suite(.serialized, .enabled(if: SIT.enabled, "set VQ_IT_URL and VQ_IT_TOKEN (eval \"$(Scripts/dev-session.sh)\")"))28struct StudioIntegrationTests {29 @Test func quotesInBatchesOfSixty() async throws {30 // 70 symbols: more than one request may carry31 let real = ["AAPL", "MSFT", "NVDA", "SPY", "TLT", "GLD", "SHOP.TO", "RY.TO"]32 let symbols = real + (0..<62).map { "ZZQX\($0)" }33 await #expect(throws: APIError.self) { _ = try await SIT.client.json(.get, "/api/v2/data/quotes", query: ["symbols": symbols.joined(separator: ",")]) }34 let batches = Batching.chunks(symbols, size: 60)35 #expect(batches.map(\.count) == [60, 10])36 var quoted: [String: JSONValue] = [:]; var missing = Set<String>()37 for b in batches {38 let r = try await SIT.client.json(.get, "/api/v2/data/quotes", query: ["symbols": b.joined(separator: ",")])39 for q in r["quotes"]?.arrayValue ?? [] { if let s = q["symbol"]?.stringValue { quoted[s] = q } }40 for m in r["missing"]?.arrayValue ?? [] { if let s = m.stringValue { missing.insert(s) } }41 #expect(r["freshness"]?["kind"]?.stringValue != nil)42 }43 #expect(Set(real).isSubset(of: Set(quoted.keys)), "real symbols are quoted: \(quoted.keys.sorted())")44 #expect(missing.count == 62 && missing.allSatisfy { $0.hasPrefix("ZZQX") })45 #expect(quoted["AAPL"]?["currency"]?.stringValue == "USD" && quoted["SHOP.TO"]?["currency"]?.stringValue == "CAD")46 #expect((quoted["AAPL"]?["price"]?.doubleValue ?? 0) > 0 && quoted["AAPL"]?["providerTimestamp"]?.doubleValue != nil)47 // the valuation of a two-currency portfolio groups, never adds48 let hq = quoted.mapValues { HoldingQuote(price: $0["price"]?.doubleValue, change: $0["change"]?.doubleValue, changePct: $0["changePct"]?.doubleValue, currency: $0["currency"]?.stringValue) }49 let v = HoldingsValuation(holdings: [HoldingInput(symbol: "AAPL", quantity: 2), HoldingInput(symbol: "SHOP.TO", quantity: 3), HoldingInput(symbol: "ZZQX1", quantity: 1)], quotes: hq)50 #expect(v.groups.map(\.currency) == ["USD", "CAD"] && v.unpriced == ["ZZQX1"])51 }5253 @Test func noteVersionsListPreviewRestore() async throws {54 let id = "mac-test-it-note-\(SIT.run)"55 let r1 = try await SIT.put("note", id, ["title": "mac-test note", "body": "first", "futureKey": ["kept": true]], baseRev: 0)56 #expect(r1["object"]?["rev"]?.doubleValue == 1)57 _ = try await SIT.put("note", id, ["title": "mac-test note", "body": "second"], baseRev: 1)58 _ = try await SIT.put("note", id, ["title": "mac-test note", "body": "third"], baseRev: 2)59 let list = try await SIT.client.json(.get, "/api/v2/objects/note/\(id)/versions")60 let revs = (list["versions"]?.arrayValue ?? []).compactMap { $0["rev"]?.doubleValue }61 #expect(revs == [2, 1], "replaced revisions, newest first: \(revs)")62 let old = try await SIT.client.json(.get, "/api/v2/objects/note/\(id)/versions/1")63 #expect(old["object"]?["data"]?["body"]?.stringValue == "first" && old["object"]?["data"]?["futureKey"]?["kept"] == .bool(true))64 // restore = the old data saved as a new revision65 let restored = try await SIT.put("note", id, old["object"]!["data"]!, baseRev: 3)66 #expect(restored["object"]?["rev"]?.doubleValue == 4 && restored["object"]?["data"]?["body"]?.stringValue == "first")67 let after = try await SIT.client.json(.get, "/api/v2/objects/note/\(id)/versions")68 #expect((after["versions"]?.arrayValue ?? []).compactMap { $0["rev"]?.doubleValue } == [3, 2, 1])69 await SIT.delete("note", id)70 await #expect(throws: APIError.self) { _ = try await SIT.client.json(.get, "/api/v2/objects/note/\(id)/versions") }71 }7273 @Test func projectBundleAndExports() async throws {74 let pid = "mac-test-it-project-\(SIT.run)", nid = "mac-test-it-pnote-\(SIT.run)", fid = "mac-test-it-pf-\(SIT.run)"75 _ = try await SIT.put("note", nid, ["title": "mac-test bundle note", "body": "# Finding\n\nVolatility **clusters**.", "projectId": .string(pid)], baseRev: 0)76 _ = try await SIT.put("portfolio", fid, ["name": "mac-test bundle portfolio", "baseCurrency": "USD", "positions": [["symbol": "AAPL", "quantity": 2]]], baseRev: 0)77 _ = try await SIT.put("project", pid, ["title": "mac-test export project", "question": "Does it export?", "hypotheses": [["id": "h1", "text": "Yes", "status": "open"]],78 "items": [["id": "a", "type": "note", "ref": .string(nid)], ["id": "b", "type": "portfolio", "ref": .string(fid), "title": "My holdings"],79 ["id": "c", "type": "dataset", "ref": "nothing.parquet"], ["id": "d", "type": "conversation", "ref": "00000000-0000-0000-0000-000000000000"]]], baseRev: 0)80 // bundle: resolved titles for what exists, null for what does not or has no store81 let bundle = try await SIT.client.json(.get, "/api/v2/projects/\(pid)/bundle")82 #expect(bundle["project"]?["id"]?.stringValue == pid)83 let items = bundle["items"]?.arrayValue ?? []84 #expect(items.compactMap { $0["id"]?.stringValue } == ["a", "b", "c", "d"], "order kept")85 #expect(items[0]["resolved"]?["title"]?.stringValue == "mac-test bundle note")86 #expect(items[1]["resolved"]?["title"]?.stringValue == "mac-test bundle portfolio" && items[1]["title"]?.stringValue == "My holdings")87 #expect(items[2]["resolved"] == .null || items[2]["resolved"] == nil)88 #expect(items[3]["resolved"] == .null || items[3]["resolved"] == nil)8990 // md: every item; the file is the document91 let md = try await SIT.client.json(.post, "/api/v2/projects/\(pid)/export", body: ["format": "md"])92 #expect(md["format"]?.stringValue == "md" && (md["bytes"]?.doubleValue ?? 0) > 100 && md["url"]?.stringValue?.hasPrefix("/api/download/") == true)93 let mdText = String(decoding: try await SIT.client.data(.get, md["url"]!.stringValue!), as: UTF8.self)94 #expect(mdText.contains("mac-test export project") && mdText.contains("Does it export?") && mdText.contains("Volatility **clusters**") && mdText.contains("Appendix"))95 // include: only the chosen items are in the document96 let only = try await SIT.client.json(.post, "/api/v2/projects/\(pid)/export", body: ["format": "md", "include": ["b"]])97 let onlyText = String(decoding: try await SIT.client.data(.get, only["url"]!.stringValue!), as: UTF8.self)98 #expect(!onlyText.contains("Volatility **clusters**") && onlyText.contains("AAPL"))99 // zip and tex are not compiled by the server100 let zip = try await SIT.client.json(.post, "/api/v2/projects/\(pid)/export", body: ["format": "zip"])101 #expect(zip["compiled"] == .bool(false))102 let zipData = try await SIT.client.data(.get, zip["url"]!.stringValue!)103 #expect(zipData.prefix(2) == Data([0x50, 0x4B]) && zipData.count == Int(zip["bytes"]?.doubleValue ?? -1))104 let tex = try await SIT.client.json(.post, "/api/v2/projects/\(pid)/export", body: ["format": "tex"])105 #expect(tex["compiled"] == .bool(false))106 #expect(String(decoding: try await SIT.client.data(.get, tex["url"]!.stringValue!), as: UTF8.self).contains("\\begin{document}"))107 // pdf: a PDF, or 502 with a plain sentence when the renderer is unavailable108 do {109 let pdf = try await SIT.client.json(.post, "/api/v2/projects/\(pid)/export", body: ["format": "pdf"])110 #expect(try await SIT.client.data(.get, pdf["url"]!.stringValue!).prefix(4) == Data("%PDF".utf8))111 } catch let e as APIError { #expect(e.status == 502 && !e.message.isEmpty, "a refusal is a sentence: \(e)") }112 // an unknown format is a validation error113 await #expect(throws: APIError.self) { _ = try await SIT.client.json(.post, "/api/v2/projects/\(pid)/export", body: ["format": "docx"]) }114115 await SIT.delete("project", pid); await SIT.delete("note", nid); await SIT.delete("portfolio", fid)116 await #expect(throws: APIError.self) { _ = try await SIT.client.json(.get, "/api/v2/projects/\(pid)/bundle") }117 }118119 @Test func projectMemoryScope() async throws {120 let scope = "project:mac-test-it-mem-\(SIT.run)"121 let m = try await SIT.client.json(.post, "/api/workspace/memories", body: ["content": .string("mac-test memory \(SIT.run)"), "category": "instruction", "scope": .string(scope), "kind": "project", "pinned": true])122 let mem: JSONValue = m["memory"] ?? m123 let id = try #require(mem["id"]?.stringValue)124 #expect(mem["scope"]?.stringValue == scope && mem["pinned"] == JSONValue.bool(true) && mem["source"]?.stringValue == "user")125 let patched = try await SIT.client.json(.patch, "/api/workspace/memories/\(id)", body: ["pinned": false, "expiresAt": .number(Date().addingTimeInterval(86_400 * 30).timeIntervalSince1970 * 1000)])126 let pm: JSONValue = patched["memory"] ?? patched127 #expect(pm["pinned"] == JSONValue.bool(false) && pm["expiresAt"]?.doubleValue != nil)128 let all = try await SIT.client.json(.get, "/api/v2/memory")129 let group = (all["groups"]?.arrayValue ?? []).first { $0["scope"]?.stringValue == scope }130 #expect(group?["memories"]?.arrayValue?.count == 1)131 #expect(all["groups"]?.arrayValue?.first?["scope"]?.stringValue == "user")132 _ = try await SIT.client.data(.delete, "/api/workspace/memories/\(id)")133 let after = try await SIT.client.json(.get, "/api/v2/memory")134 #expect((after["groups"]?.arrayValue ?? []).first { $0["scope"]?.stringValue == scope }?["memories"]?.arrayValue?.isEmpty ?? true)135 }136}137