SPB Git

Repository Public

NextTestSupport.swift 10.1 KB 214 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Mail9// File             : Packages/SPMailCore/Tests/SPMailCoreTests/NextTestSupport.swift10// Description      : Test double of the SP Mail Next server: a URLProtocol that11//                    answers from a per-test script (keyed by host, so suites12//                    can run in parallel) and records every request exactly as13//                    it left the client.14// Module           : SPMailCoreTests15// Repository       : https://git.spboucher.ai/sp-mail-apple16// Created          : 2026-11-2017// Last Modified    : 2026-11-2018//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation92import Testing93@testable import SPMailCore9495struct RecordedRequest: Sendable {96    var method: String97    var path: String98    /// Percent-encoded query, exactly as sent ("" when there is none).99    var query: String100    var headers: [String: String]101    var body: Data102    var json: JSONValue { (try? JSONValue.parse(body)) ?? .null }103    var line: String { query.isEmpty ? "\(method) \(path)" : "\(method) \(path)?\(query)" }104    func header(_ name: String) -> String? { headers.first { $0.key.lowercased() == name.lowercased() }?.value }105}106107struct StubReply: Sendable {108    var status = 200109    var headers = ["Content-Type": "application/json"]110    var body = Data()111    /// A transport failure instead of an answer.112    var failure: URLError.Code?113    static func json(_ text: String, status: Int = 200, headers: [String: String] = [:]) -> StubReply {114        StubReply(status: status, headers: ["Content-Type": "application/json"].merging(headers) { _, b in b }, body: Data(text.utf8))115    }116    static func value(_ v: JSONValue, status: Int = 200) -> StubReply { StubReply(status: status, body: (try? v.data()) ?? Data()) }117    static func error(_ status: Int, _ code: String, message: String = "", headers: [String: String] = [:]) -> StubReply {118        .json("{\"error\":\"\(code)\",\"message\":\"\(message)\"}", status: status, headers: headers)119    }120    static let offline = StubReply(failure: .notConnectedToInternet)121    static let ok = StubReply.json("{\"ok\":true}")122}123124/// One fake server. Replies are consumed in order; when the script is empty `fallback` answers (default: 500 `unscripted`).125final class FakeServer: @unchecked Sendable {126    typealias Handler = @Sendable (RecordedRequest) -> StubReply?127    private let lock = NSLock()128    private var script: [StubReply] = []129    private var handler: Handler?130    private var log: [RecordedRequest] = []131    let host = "t\(UUID().uuidString.lowercased().prefix(12)).test"132133    init(_ replies: StubReply...) { script = replies; NextStub.register(self) }134    deinit { NextStub.unregister(host) }135136    var baseURL: URL { URL(string: "https://\(host)")! }137    func client(token: String? = "test-token") -> APIClient { APIClient(baseURL: baseURL, token: token, userAgent: "SPMailCoreTests", protocolClasses: [NextStub.self]) }138    var api: NextAPI { NextAPI(client()) }139140    func enqueue(_ replies: StubReply...) { lock.withLock { script.append(contentsOf: replies) } }141    /// Answers by route; return nil to fall through to the script.142    func route(_ h: @escaping Handler) { lock.withLock { handler = h } }143    var requests: [RecordedRequest] { lock.withLock { log } }144    var lines: [String] { requests.map(\.line) }145    var last: RecordedRequest { lock.withLock { log.last ?? RecordedRequest(method: "", path: "", query: "", headers: [:], body: Data()) } }146    func reset() { lock.withLock { log = [] } }147148    fileprivate func answer(_ r: RecordedRequest) -> StubReply {149        lock.withLock {150            log.append(r)151            if let h = handler, let reply = h(r) { return reply }152            return script.isEmpty ? .error(500, "unscripted", message: r.line) : script.removeFirst()153        }154    }155}156157final class NextStub: URLProtocol, @unchecked Sendable {158    private static let lock = NSLock()159    nonisolated(unsafe) private static var servers: [String: () -> FakeServer?] = [:]160    static func register(_ s: FakeServer) { lock.withLock { servers[s.host] = { [weak s] in s } } }161    static func unregister(_ host: String) { lock.withLock { servers[host] = nil } }162163    override class func canInit(with request: URLRequest) -> Bool { true }164    override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }165    override func startLoading() {166        var body = request.httpBody ?? Data()167        if let s = request.httpBodyStream {168            s.open()169            var buf = [UInt8](repeating: 0, count: 16_384)170            while s.hasBytesAvailable { let n = s.read(&buf, maxLength: buf.count); if n <= 0 { break }; body.append(buf, count: n) }171            s.close()172        }173        let comps = request.url.flatMap { URLComponents(url: $0, resolvingAgainstBaseURL: false) }174        let recorded = RecordedRequest(method: request.httpMethod ?? "GET", path: comps?.percentEncodedPath ?? "", query: comps?.percentEncodedQuery ?? "", headers: request.allHTTPHeaderFields ?? [:], body: body)175        let server = Self.lock.withLock { Self.servers[request.url?.host ?? ""] }?()176        let reply = server?.answer(recorded) ?? .error(500, "no_server")177        let me = self178        DispatchQueue.global().async {179            guard let client = me.client, let url = me.request.url else { return }180            if let code = reply.failure { client.urlProtocol(me, didFailWithError: URLError(code)); return }181            guard let http = HTTPURLResponse(url: url, statusCode: reply.status, httpVersion: "HTTP/1.1", headerFields: reply.headers) else { return }182            client.urlProtocol(me, didReceive: http, cacheStoragePolicy: .notAllowed)183            if !reply.body.isEmpty { client.urlProtocol(me, didLoad: reply.body) }184            client.urlProtocolDidFinishLoading(me)185        }186    }187    override func stopLoading() {}188}189190/// Runs one call against a server that gives one answer; returns the result and the request that was sent.191func exchange<T: Sendable>(_ reply: StubReply, _ call: @Sendable (NextAPI) async throws -> T) async throws -> (T, RecordedRequest) {192    let server = FakeServer(reply)193    let value = try await call(server.api)194    #expect(server.requests.count == 1, "expected exactly one request, got \(server.lines)")195    return (value, server.last)196}197198/// The error a call throws against one scripted answer.199func failure<T: Sendable>(_ reply: StubReply, _ call: @Sendable (NextAPI) async throws -> T) async -> Error? {200    let server = FakeServer(reply)201    do { _ = try await call(server.api); return nil } catch { return error }202}203204/// A mutable clock for the store tests.205final class TestClock: @unchecked Sendable {206    private let lock = NSLock()207    private var t: Date208    init(_ t: Date = Date(timeIntervalSince1970: 1_800_000_000)) { self.t = t }209    var now: Date { lock.withLock { t } }210    func advance(_ s: TimeInterval) { lock.withLock { t = t.addingTimeInterval(s) } }211}212213let uuidA = "11111111-1111-4111-8111-111111111111", uuidB = "22222222-2222-4222-8222-222222222222", uuidC = "33333333-3333-4333-8333-333333333333"214
Files main
Menu

Theme