Repository Public License
1import Foundation2import Testing3@testable import ProviderKit45/// Serves canned responses inside the process, so the production `URLSessionTransport` can be exercised without a6/// network. The behaviour is chosen by the first path component of the URL.7final class StubURLProtocol: URLProtocol, @unchecked Sendable {8 static let stopped = Locked<[String: Int]>([:])9 static let received = Locked<[String: URLRequest]>([:])1011 static let events = "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hel\"}}]}\n\ndata: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"lo\"}}]}\n\n"12 static let ending = "data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":4,\"completion_tokens\":2}}\n\ndata: [DONE]\n\n"1314 override class func canInit(with request: URLRequest) -> Bool { request.url?.host == "stub.invalid" }15 override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }1617 private var scenario: String { request.url?.pathComponents.dropFirst().first ?? "" }1819 override func startLoading() {20 let scenario = scenario21 Self.received.mutate { $0[scenario] = request }22 func head(_ status: Int, _ headers: [String: String]) {23 let response = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: headers)!24 client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)25 }26 switch scenario.prefix(while: { $0 != "-" }) {27 case "stream":28 head(200, ["Content-Type": "text/event-stream"])29 client?.urlProtocol(self, didLoad: Data(Self.events.utf8))30 client?.urlProtocol(self, didLoad: Data(Self.ending.utf8))31 client?.urlProtocolDidFinishLoading(self)32 case "hang":33 head(200, ["Content-Type": "text/event-stream"])34 client?.urlProtocol(self, didLoad: Data(Self.events.utf8)) // and then nothing: only cancellation ends it35 case "unauthorized":36 head(401, ["Content-Type": "application/json"])37 client?.urlProtocol(self, didLoad: Data(#"{"error":{"message":"Incorrect API key provided","type":"invalid_request_error"}}"#.utf8))38 client?.urlProtocolDidFinishLoading(self)39 case "models":40 head(200, ["Content-Type": "application/json"])41 client?.urlProtocol(self, didLoad: Data(#"{"data":[{"id":"local-model"}]}"#.utf8))42 client?.urlProtocolDidFinishLoading(self)43 default:44 client?.urlProtocol(self, didFailWithError: URLError(.cannotConnectToHost))45 }46 }4748 override func stopLoading() {49 let scenario = scenario50 Self.stopped.mutate { $0[scenario, default: 0] += 1 }51 }52}5354/// The real `URLSession` path: `URLSession.bytes`, chunk delivery, cancellation. Still no network.55@Suite struct URLSessionTransportTests {56 private func provider(_ scenario: String) -> CompatibleProvider {57 let configuration = URLSessionTransport.defaultConfiguration()58 configuration.protocolClasses = [StubURLProtocol.self]59 let environment = ProviderEnvironment(transport: URLSessionTransport(configuration: configuration), retry: .none)60 return CompatibleProvider(endpoint: .init(baseURL: "https://stub.invalid/\(scenario)/v1"), apiKey: { testKey }, environment: environment)61 }6263 @Test func defaultConfigurationKeepsNoCookiesAndNoCache() {64 let configuration = URLSessionTransport.defaultConfiguration()65 #expect(configuration.httpCookieStorage == nil)66 #expect(configuration.urlCache == nil)67 #expect(!configuration.httpShouldSetCookies)68 #expect(configuration.timeoutIntervalForResource == URLSessionTransport.totalTimeout)69 }7071 @Test func streamsAResponseThroughURLSession() async throws {72 let response = try await provider("stream-a").complete(sampleRequest())73 #expect(response.text == "Hello")74 #expect(response.finishReason == .endOfTurn)75 #expect(response.usage == ProviderUsage(inputTokens: 4, outputTokens: 2))76 let request = try #require(StubURLProtocol.received.get()["stream-a"])77 #expect(request.url?.path == "/stream-a/v1/chat/completions")78 #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer \(testKey)")79 #expect(request.value(forHTTPHeaderField: "User-Agent") == "ORIXNavigator")80 }8182 @Test func mapsAnHTTPErrorThroughURLSession() async {83 let (events, error) = await collect(provider("unauthorized-a").stream(sampleRequest()))84 #expect(events.isEmpty)85 #expect(error == .invalidKey("Incorrect API key provided"))86 }8788 @Test func listsModelsThroughURLSession() async throws {89 #expect(try await provider("models-a").listModels().map(\.id) == ["local-model"])90 }9192 @Test func connectionFailureIsANetworkError() async {93 let (_, error) = await collect(provider("down-a").stream(sampleRequest()))94 #expect(error == .network("The server could not be reached."))95 }9697 @Test func cancellingTheConsumerStopsTheURLSessionTask() async {98 let provider = provider("hang-a")99 let received = Locked("")100 let consumer = Task {101 do { for try await event in provider.stream(sampleRequest()) { if case .textDelta(let delta) = event { received.mutate { $0 += delta } } } } catch {}102 }103 #expect(await eventually { received.get() == "Hello" })104 #expect(StubURLProtocol.stopped.get()["hang-a"] == nil)105 consumer.cancel()106 // `stopLoading` is URLSession telling the protocol that the task was cancelled.107 #expect(await eventually { StubURLProtocol.stopped.get()["hang-a"] == 1 })108 await consumer.value109 }110}111