Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Tests/CoreTests/Support/MockTransport.swift3// Description: Scripted HTTP transport for tests: records requests, serves JSON / SSE / failures, can cut a stream mid-way.4import Foundation5@testable import SPChatCore67final class MockTransport: HTTPTransport, @unchecked Sendable {8 enum Reply {9 case json(Int, String, headers: [String: String] = [:])10 case sse([String], closes: Bool = true, hang: Bool = false, headers: [String: String] = [:]) // frames already formatted; closes=false → error mid-stream11 case fail(URLError.Code)12 case data(Int, Data, headers: [String: String])13 }14 struct Recorded { let method: String; let path: String; let query: String?; let headers: [String: String]; let body: Data? }1516 private let lock = NSLock()17 private var handlers: [(matches: (URLRequest) -> Bool, replies: [Reply])] = []18 private(set) var recorded: [Recorded] = []19 var requests: [Recorded] { lock.withLock { recorded } }2021 /// Replies are consumed in order; the last one repeats.22 func on(_ method: String, _ path: String, _ replies: Reply...) {23 lock.withLock { handlers.append(({ $0.httpMethod == method && $0.url?.path == path }, replies)) }24 }2526 private func next(for r: URLRequest, body: Data?) throws -> Reply {27 try lock.withLock {28 recorded.append(Recorded(method: r.httpMethod ?? "GET", path: r.url?.path ?? "", query: r.url?.query, headers: r.allHTTPHeaderFields ?? [:], body: body ?? r.httpBody))29 guard let i = handlers.firstIndex(where: { $0.matches(r) }) else { throw URLError(.unsupportedURL) }30 let reply = handlers[i].replies[0]31 if handlers[i].replies.count > 1 { handlers[i].replies.removeFirst() }32 return reply33 }34 }3536 func send(_ request: URLRequest) async throws -> (Data, HTTPResponse) {37 switch try next(for: request, body: nil) {38 case .json(let status, let body, let headers): return (Data(body.utf8), HTTPResponse(status: status, headers: ["Content-Type": "application/json"].merging(headers) { $1 }))39 case .data(let status, let d, let headers): return (d, HTTPResponse(status: status, headers: headers))40 case .fail(let code): throw URLError(code)41 case .sse: throw URLError(.badServerResponse)42 }43 }4445 func upload(_ request: URLRequest, body: Data, progress: @escaping @Sendable (Double) -> Void) async throws -> (Data, HTTPResponse) {46 progress(0.5)47 switch try next(for: request, body: body) {48 case .json(let status, let b, let headers): return (Data(b.utf8), HTTPResponse(status: status, headers: ["Content-Type": "application/json"].merging(headers) { $1 }))49 case .fail(let code): throw URLError(code)50 default: throw URLError(.badServerResponse)51 }52 }5354 func stream(_ request: URLRequest) async throws -> (HTTPResponse, AsyncThrowingStream<Data, Error>) {55 switch try next(for: request, body: nil) {56 case .fail(let code): throw URLError(code)57 case .json(let status, let body, let headers):58 return (HTTPResponse(status: status, headers: ["Content-Type": "application/json"].merging(headers) { $1 }), AsyncThrowingStream { c in c.yield(Data(body.utf8)); c.finish() })59 case .data(let status, let d, let headers): return (HTTPResponse(status: status, headers: headers), AsyncThrowingStream { c in c.yield(d); c.finish() })60 case .sse(let frames, let closes, let hang, let headers):61 let stream = AsyncThrowingStream<Data, Error> { c in62 let task = Task {63 for f in frames { c.yield(Data(f.utf8)); await Task.yield() }64 if hang { try? await Task.sleep(for: .seconds(30)) }65 if closes { c.finish() } else { c.finish(throwing: URLError(.networkConnectionLost)) }66 }67 c.onTermination = { _ in task.cancel() }68 }69 return (HTTPResponse(status: 200, headers: ["Content-Type": "text/event-stream; charset=utf-8"].merging(headers) { $1 }), stream)70 }71 }72}7374func frame(_ event: String, _ json: String, id: Int? = nil) -> String { (id.map { "id: \($0)\n" } ?? "") + "event: \(event)\ndata: \(json)\n\n" }7576func makeClient(_ transport: MockTransport, secrets: SecretStore = InMemorySecretStore(), session: Bool = true) -> APIClient {77 let api = APIClient(server: .production, transport: transport, secrets: secrets)78 if session { api.cookies.ingest(setCookie: "__Host-csa_session=\(String(repeating: "a", count: 43)); Path=/; HttpOnly; Secure; SameSite=lax; Max-Age=2592000") }79 return api80}8182/// A complete, well-formed run as the server emits it.83func happyRun(runId: String = "run_1", conversationId: String = "conv_1", created: Bool = true, text: [String] = ["Bon", "jour"], startIndex: Int = 0) -> [String] {84 var i = startIndex85 func f(_ e: String, _ j: String) -> String { defer { i += 1 }; return frame(e, j, id: i) }86 var frames = ["retry: 2000\n\n", f("run", #"{"runId":"\#(runId)"}"#), f("conversation", #"{"id":"\#(conversationId)","userMessageId":"msg_u1","created":\#(created)}"#),87 f("start", #"{"messageId":"msg_a1","model":"claude-haiku-5-5","provider":"anthropic","routing":{"mode":"manual","selected":"claude-haiku-5-5"},"applied":{"applied":{"tools":true},"ignored":[]}}"#)]88 for t in text { frames.append(f("text", #"{"delta":"\#(t)"}"#)) }89 frames += [f("usage", #"{"usage":{"input":12,"output":3,"cached":0},"costUsd":0.00012,"latencyMs":420,"ttftMs":180}"#), f("status", #"{"messageId":"msg_a1","status":"complete","error":null}"#),90 f("title", #"{"title":"Salutation"}"#), f("done", #"{"messageId":"msg_a1","status":"complete"}"#), f("end", "{}")]91 return frames92}93