migration
This commit is contained in:
46
PediFoodsTests/URLProtocolStub.swift
Normal file
46
PediFoodsTests/URLProtocolStub.swift
Normal file
@@ -0,0 +1,46 @@
|
||||
import Foundation
|
||||
|
||||
/// Intercepts every request made through a `URLSession` configured with it,
|
||||
/// so network-dependent code (`ApiClient`, `ApiService`,
|
||||
/// `FeatureControlService`, ...) can be unit tested without touching a real
|
||||
/// server. Register a handler per test, then build a session via
|
||||
/// `URLProtocolStub.makeSession()`.
|
||||
final class URLProtocolStub: URLProtocol {
|
||||
/// `nonisolated(unsafe)`: `URLProtocol` subclasses are instantiated and
|
||||
/// driven by URLSession's own internal (non-Sendable-checked) machinery,
|
||||
/// off the calling actor. Tests only ever set this once, synchronously,
|
||||
/// before starting the request that reads it.
|
||||
nonisolated(unsafe) static var handler: ((URLRequest) throws -> (HTTPURLResponse, Data))?
|
||||
|
||||
static func makeSession() -> URLSession {
|
||||
let config = URLSessionConfiguration.ephemeral
|
||||
config.protocolClasses = [URLProtocolStub.self]
|
||||
return URLSession(configuration: config)
|
||||
}
|
||||
|
||||
override class func canInit(with request: URLRequest) -> Bool { true }
|
||||
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
|
||||
|
||||
override func startLoading() {
|
||||
guard let handler = URLProtocolStub.handler else {
|
||||
client?.urlProtocol(self, didFailWithError: URLError(.badServerResponse))
|
||||
return
|
||||
}
|
||||
do {
|
||||
let (response, data) = try handler(request)
|
||||
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
|
||||
client?.urlProtocol(self, didLoad: data)
|
||||
client?.urlProtocolDidFinishLoading(self)
|
||||
} catch {
|
||||
client?.urlProtocol(self, didFailWithError: error)
|
||||
}
|
||||
}
|
||||
|
||||
override func stopLoading() {}
|
||||
}
|
||||
|
||||
extension HTTPURLResponse {
|
||||
static func stub(url: URL = URL(string: "https://example.com")!, statusCode: Int) -> HTTPURLResponse {
|
||||
HTTPURLResponse(url: url, statusCode: statusCode, httpVersion: nil, headerFields: nil)!
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user