import Foundation import XCTest @testable import OldFella final class StubURLProtocol: URLProtocol { static var handler: ((URLRequest) throws -> (Int, Data))? static var errorHandler: ((URLRequest) -> Error?)? private static let lock = NSLock() private static var requests: [URLRequest] = [] private static var bodies: [URL: Data] = [:] static func recordedBody(for url: URL) -> Data? { lock.lock() defer { lock.unlock() } return bodies[url] } static var recordedRequests: [URLRequest] { lock.lock() defer { lock.unlock() } return requests } static func clearRequests() { lock.lock() requests = [] bodies = [:] lock.unlock() } override static func canInit(with request: URLRequest) -> Bool { true } override static func canonicalRequest(for request: URLRequest) -> URLRequest { request } override func startLoading() { Self.lock.lock() Self.requests.append(request) if let url = request.url, let body = request.httpBody ?? Self.readBody(request.httpBodyStream) { Self.bodies[url] = body } Self.lock.unlock() if let error = Self.errorHandler?(request) { client?.urlProtocol(self, didFailWithError: error) return } guard let handler = Self.handler, let url = request.url else { client?.urlProtocol(self, didFailWithError: ServiceError.invalidResponse) return } let result: (Int, Data) do { result = try handler(request) } catch { client?.urlProtocol(self, didFailWithError: error) return } guard let response = HTTPURLResponse( url: url, statusCode: result.0, httpVersion: "HTTP/1.1", headerFields: ["Content-Type": "application/json"]) else { client?.urlProtocol(self, didFailWithError: ServiceError.invalidResponse) return } client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) client?.urlProtocol(self, didLoad: result.1) client?.urlProtocolDidFinishLoading(self) } override func stopLoading() {} private static func readBody(_ stream: InputStream?) -> Data? { guard let stream else { return nil } stream.open() defer { stream.close() } var data = Data() let bufferSize = 4096 let buffer = UnsafeMutablePointer.allocate(capacity: bufferSize) defer { buffer.deallocate() } while stream.hasBytesAvailable { let count = stream.read(buffer, maxLength: bufferSize) if count <= 0 { break } data.append(buffer, count: count) } return data.isEmpty ? nil : data } }