Files
Sprachmittler/Packages/SprachmittlerKit/Tests/SprachmittlerOllamaTests/Support/StubURLProtocol.swift
T
schihei 26b493e7e5 feat(m1): Ollama client, catalog, streaming chat and CLI (T1.1-T1.6)
Add endpoint policy and redirect-safe ephemeral HTTP client, error mapping, catalog cache and version checks, streaming chat with phase timeouts/cancellation, provisional Hy-MT3 prompt/language/request factory, warm-up policy, and sprachmittler-cli models/show/translate. Recapture the 7B fixtures; defer the 1.8B VERIFY items; document ADR-016. Also fix the signature checker's pipefail SIGPIPE issue.
2026-11-26 13:04:22 +01:00

91 lines
2.7 KiB
Swift

import Foundation
/// A serialized `URLProtocol` stub for contract tests. Test suites using it must be `.serialized`.
final class StubURLProtocol: URLProtocol, @unchecked Sendable {
struct Stub: Sendable {
var status = 200
var headers: [String: String] = ["Content-Type": "application/json"]
var chunks: [Data] = []
var error: URLError?
var hangAfterChunks = false
}
struct Snapshot: Sendable {
let count: Int
let stopped: Bool
let lastRequest: URLRequest?
}
private static let lock = NSLock()
private nonisolated(unsafe) static var stub: Stub?
private nonisolated(unsafe) static var requestCount = 0
private nonisolated(unsafe) static var wasStopped = false
private nonisolated(unsafe) static var lastRequestValue: URLRequest?
static func reset(_ stub: Stub? = nil) {
lock.lock()
self.stub = stub
requestCount = 0
wasStopped = false
lastRequestValue = nil
lock.unlock()
}
static func snapshot() -> Snapshot {
lock.lock()
defer { lock.unlock() }
return Snapshot(count: requestCount, stopped: wasStopped, lastRequest: lastRequestValue)
}
private static func beginRequest(_ request: URLRequest) -> Stub? {
lock.lock()
defer { lock.unlock() }
requestCount += 1
lastRequestValue = request
return stub
}
override static func canInit(with request: URLRequest) -> Bool {
true
}
override static func canonicalRequest(for request: URLRequest) -> URLRequest {
request
}
override func startLoading() {
guard let stub = Self.beginRequest(request) else {
client?.urlProtocol(self, didFailWithError: URLError(.unknown))
return
}
if let error = stub.error {
client?.urlProtocol(self, didFailWithError: error)
return
}
guard let url = request.url,
let response = HTTPURLResponse(
url: url,
statusCode: stub.status,
httpVersion: "HTTP/1.1",
headerFields: stub.headers
)
else {
client?.urlProtocol(self, didFailWithError: URLError(.badURL))
return
}
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
for chunk in stub.chunks {
client?.urlProtocol(self, didLoad: chunk)
}
if !stub.hangAfterChunks {
client?.urlProtocolDidFinishLoading(self)
}
}
override func stopLoading() {
Self.lock.lock()
Self.wasStopped = true
Self.lock.unlock()
}
}