Repository Public
1// SP Notes Core2// File: Tests/SPNotesAPITests/TestSupport.swift3// Description: Test plumbing: a URLProtocol stub that records requests and plays scripted answers, and helpers to4// build a client on top of it.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import XCTest10@testable import SPNotesAPI1112/// A scripted answer.13struct StubReply: Sendable {14 var status = 20015 var headers: [String: String] = ["Content-Type": "application/json"]16 var body = Data()17 var error: URLError.Code?1819 static func json(_ text: String, status: Int = 200, headers: [String: String] = [:]) -> StubReply {20 StubReply(status: status, headers: ["Content-Type": "application/json"].merging(headers) { $1 }, body: Data(text.utf8))21 }2223 static func failure(_ code: URLError.Code) -> StubReply { StubReply(error: code) }24}2526/// A request as the stub saw it.27struct RecordedRequest: Sendable {28 var method: String29 var url: URL30 var headers: [String: String]31 var body: Data3233 var path: String { url.path }34 var query: String? { url.query }35 func header(_ name: String) -> String? { headers.first { $0.key.lowercased() == name.lowercased() }?.value }36 var bodyText: String { String(decoding: body, as: UTF8.self) }37}3839/// Global script of the stub (tests of one process run one after the other).40final class StubServer: @unchecked Sendable {41 static let shared = StubServer()42 private let lock = NSLock()43 private var handler: (@Sendable (RecordedRequest) -> StubReply)?44 private var recorded: [RecordedRequest] = []4546 func reset(_ handler: @escaping @Sendable (RecordedRequest) -> StubReply) {47 lock.withLock { self.handler = handler; recorded = [] }48 }4950 func handle(_ request: RecordedRequest) -> StubReply {51 let h: (@Sendable (RecordedRequest) -> StubReply)? = lock.withLock { recorded.append(request); return handler }52 return h?(request) ?? StubReply(status: 500)53 }5455 var requests: [RecordedRequest] { lock.withLock { recorded } }56 var last: RecordedRequest? { requests.last }57}5859final class StubURLProtocol: URLProtocol, @unchecked Sendable {60 override class func canInit(with request: URLRequest) -> Bool { true }61 override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }6263 override func startLoading() {64 var body = request.httpBody ?? Data()65 if body.isEmpty, let stream = request.httpBodyStream {66 stream.open()67 var buffer = [UInt8](repeating: 0, count: 64 * 1024)68 while stream.hasBytesAvailable {69 let n = stream.read(&buffer, maxLength: buffer.count)70 if n <= 0 { break }71 body.append(buffer, count: n)72 }73 stream.close()74 }75 let recorded = RecordedRequest(method: request.httpMethod ?? "GET", url: request.url!, headers: request.allHTTPHeaderFields ?? [:], body: body)76 let reply = StubServer.shared.handle(recorded)77 if let code = reply.error {78 client?.urlProtocol(self, didFailWithError: URLError(code))79 return80 }81 let response = HTTPURLResponse(url: request.url!, statusCode: reply.status, httpVersion: "HTTP/1.1", headerFields: reply.headers)!82 client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)83 if !reply.body.isEmpty { client?.urlProtocol(self, didLoad: reply.body) }84 client?.urlProtocolDidFinishLoading(self)85 }8687 override func stopLoading() {}88}8990enum TestEnv {91 static let baseURL = URL(string: "https://notes.test")!92 static let token = "tok_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"9394 static func configuration() -> APIConfiguration {95 APIConfiguration(baseURL: baseURL, userAgent: APIConfiguration.userAgent(appVersion: "1.2.3", device: .iPhone, osVersion: "iOS 18.1"))96 }9798 /// A client whose requests all go to `StubServer.shared`.99 static func client(token: String? = TestEnv.token) -> (HTTPClient, InMemoryTokenStore) {100 let store = InMemoryTokenStore(token: token)101 let session = URLSessionConfiguration.ephemeral102 session.protocolClasses = [StubURLProtocol.self]103 return (HTTPClient(configuration: configuration(), tokenStore: store, sessionConfiguration: session), store)104 }105106 static func api(token: String? = TestEnv.token) -> (NotesAPI, HTTPClient, InMemoryTokenStore) {107 let (client, store) = client(token: token)108 return (NotesAPI(client: client), client, store)109 }110}111112/// Runs an async throwing expression and returns the `APIError` it throws.113func captureAPIError<T>(_ body: () async throws -> T, file: StaticString = #filePath, line: UInt = #line) async -> APIError? {114 do {115 _ = try await body()116 XCTFail("expected an error", file: file, line: line)117 return nil118 } catch let error as APIError {119 return error120 } catch {121 XCTFail("unexpected error type: \(error)", file: file, line: line)122 return nil123 }124}125126/// Parses JSON text for order-insensitive comparisons.127func jsonObject(_ data: Data) -> NSObject? {128 (try? JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed])) as? NSObject129}130