SPB Git

Repository Public

MockTransport.swift 4.0 KB 74 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/CoreTests/Support/MockTransport.swift3// Description: TEST ONLY — scripted HTTP transport: records requests, serves bodies, event streams and failures, can cut a stream mid-way.4import Foundation5@testable import VQuantCore67final class MockTransport: HTTPTransport, @unchecked Sendable {8    enum Reply {9        case json(Int, String, headers: [String: String] = [:])10        /// lines of an event stream; `cut` ends it with a network error instead of a clean close11        case sse([String], cut: Bool = false)12        case fail(URLError.Code)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: [(method: String, path: String, replies: [Reply])] = []18    private 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...) { lock.withLock { handlers.append((method, path, replies)) } }2324    private func next(_ r: URLRequest) throws -> Reply {25        try lock.withLock {26            recorded.append(Recorded(method: r.httpMethod ?? "GET", path: r.url?.path ?? "", query: r.url?.query, headers: r.allHTTPHeaderFields ?? [:], body: r.httpBody))27            guard let i = handlers.firstIndex(where: { $0.method == r.httpMethod && $0.path == r.url?.path }) else { throw URLError(.unsupportedURL) }28            let reply = handlers[i].replies[0]29            if handlers[i].replies.count > 1 { handlers[i].replies.removeFirst() }30            return reply31        }32    }33    private func response(_ r: URLRequest, _ status: Int, _ headers: [String: String]) -> HTTPURLResponse { HTTPURLResponse(url: r.url!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: headers)! }3435    func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) {36        switch try next(request) {37        case .json(let s, let body, let h): return (Data(body.utf8), response(request, s, h))38        case .fail(let code): throw URLError(code)39        case .sse: throw URLError(.badServerResponse)40        }41    }4243    func lines(for request: URLRequest) async throws -> (AsyncThrowingStream<String, Error>, HTTPURLResponse) {44        switch try next(request) {45        case .fail(let code): throw URLError(code)46        case .json(let s, let body, let h): return (AsyncThrowingStream { c in c.yield(body); c.finish() }, response(request, s, h))47        case .sse(let lines, let cut):48            let stream = AsyncThrowingStream<String, Error> { c in49                let task = Task {50                    for l in lines { c.yield(l); await Task.yield() }51                    if cut { c.finish(throwing: URLError(.networkConnectionLost)) } else { c.finish() }52                }53                c.onTermination = { _ in task.cancel() }54            }55            return (stream, response(request, 200, ["Content-Type": "text/event-stream"]))56        }57    }58}5960let testIdentity = ClientIdentity(version: "2.0.0", build: "1", deviceName: "Test Mac")6162func makeAPI(_ t: MockTransport, token: String? = "vqn_" + String(repeating: "a", count: 43)) -> (VQuantAPI, MemoryTokenStore) {63    let store = MemoryTokenStore(token)64    return (VQuantAPI(client: APIClient(baseURL: URL(string: "https://vquant.test")!, identity: testIdentity, tokens: store, transport: t)), store)65}6667/// Event lines as the server writes them: `id: n` then `data: {json}` (blank separator lines are dropped by line readers).68func events(from start: Int = 0, _ jsons: [String]) -> [String] { jsons.enumerated().flatMap { ["id: \(start + $0.offset)", "data: \($0.element)"] } }6970func fixture(_ name: String) throws -> Data {71    guard let url = Bundle.module.url(forResource: name, withExtension: "json", subdirectory: "Fixtures") else { throw CocoaError(.fileNoSuchFile) }72    return try Data(contentsOf: url)73}74
Files main
Menu

Theme