Repository Public
1// SP Wallet Core2// File: Tests/SPWalletCoreTests/Support/MockTransport.swift3// Description: Scripted HTTP transport for endpoint tests: records every request and answers from a queue or a handler.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8@testable import SPWalletCore910final class MockTransport: HTTPTransport, @unchecked Sendable {11 struct Recorded: Sendable {12 let method: String, path: String, query: [String: String], headers: [String: String], body: JSONValue?13 }14 private let lock = NSLock()15 private var queue: [(Int, Data, [String: String])] = []16 private var _requests: [Recorded] = []17 var handler: (@Sendable (Recorded) -> (Int, Data, [String: String])?)?1819 var requests: [Recorded] { lock.withLock { _requests } }20 var last: Recorded? { requests.last }2122 func enqueue(status: Int = 200, json: String, headers: [String: String] = [:]) { lock.withLock { queue.append((status, Data(json.utf8), headers)) } }23 func enqueue(status: Int = 200, data: Data, headers: [String: String] = [:]) { lock.withLock { queue.append((status, data, headers)) } }2425 func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {26 let c = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)!27 let rec = Recorded(method: request.httpMethod ?? "GET", path: c.path,28 query: Dictionary((c.queryItems ?? []).map { ($0.name, $0.value ?? "") }, uniquingKeysWith: { a, _ in a }),29 headers: request.allHTTPHeaderFields ?? [:],30 body: request.httpBody.flatMap { try? JSONDecoder().decode(JSONValue.self, from: $0) })31 let answer: (Int, Data, [String: String]) = lock.withLock {32 _requests.append(rec)33 if let h = handler?(rec) { return h }34 return queue.isEmpty ? (500, Data(#"{"error":"mock_empty","message":"no scripted answer"}"#.utf8), [:]) : queue.removeFirst()35 }36 return (answer.1, HTTPURLResponse(url: request.url!, statusCode: answer.0, httpVersion: "HTTP/1.1", headerFields: answer.2)!)37 }3839 /** A client on a throwaway origin with an in-memory session token. */40 static func client(token: String? = "test-session-token") -> (APIClient, MockTransport, InMemoryTokenStore) {41 let t = MockTransport(), store = InMemoryTokenStore(token)42 let cfg = APIConfiguration(origin: URL(string: "https://wallet.example.test")!, rpId: "wallet.example.test", userAgent: "SPWalletCoreTests")43 return (APIClient(configuration: cfg, tokens: store, transport: t), t, store)44 }45}4647enum TestResources {48 static func data(_ name: String, in dir: String) throws -> Data {49 let url = Bundle.module.resourceURL!.appendingPathComponent(dir).appendingPathComponent(name)50 return try Data(contentsOf: url)51 }52 static func json(_ name: String, in dir: String = "Fixtures") throws -> JSONValue { try JSONDecoder().decode(JSONValue.self, from: try data(name, in: dir)) }53}54