import Alamofire
import Foundation
import XCTest
class ProxyURLProtocol: URLProtocol {
enum PropertyKeys {
static let handledByForwarderURLProtocol = "HandledByProxyURLProtocol"
}
lazy var session: URLSession = {
let configuration: URLSessionConfiguration = {
let configuration = URLSessionConfiguration.ephemeral
configuration.headers = HTTPHeaders.default
return configuration
}()
return URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
}()
weak var activeTask: URLSessionTask?
override class func canInit(with task: URLSessionTask) -> Bool {
if let request = task.currentRequest,
URLProtocol.property(forKey: PropertyKeys.handledByForwarderURLProtocol, in: request) != nil {
return false
}
return true
}
override class func canInit(with request: URLRequest) -> Bool {
if URLProtocol.property(forKey: PropertyKeys.handledByForwarderURLProtocol, in: request) != nil {
return false
}
return true
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
if let headers = request.allHTTPHeaderFields {
do {
return try URLEncoding.default.encode(request, with: headers)
} catch {
return request
}
}
return request
}
override class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool {
false
}
override func startLoading() {
let urlRequest = (request.urlRequest! as NSURLRequest).mutableCopy() as! NSMutableURLRequest
URLProtocol.setProperty(true, forKey: PropertyKeys.handledByForwarderURLProtocol, in: urlRequest)
activeTask = session.dataTask(with: urlRequest as URLRequest)
activeTask?.resume()
}
override func stopLoading() {
activeTask?.cancel()
}
}
extension ProxyURLProtocol: URLSessionDataDelegate {
func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse) async -> URLSession.ResponseDisposition {
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
return .allow
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
client?.urlProtocol(self, didLoad: data)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: (any Error)?) {
client?.urlProtocolDidFinishLoading(self)
}
}
class URLProtocolTestCase: BaseTestCase {
var manager: Session!
override func setUp() {
super.setUp()
manager = {
let configuration: URLSessionConfiguration = {
let configuration = URLSessionConfiguration.default
configuration.protocolClasses = [ProxyURLProtocol.self]
configuration.headers["Session-Configuration-Header"] = "foo"
return configuration
}()
return Session(configuration: configuration)
}()
}
@MainActor
func testThatURLProtocolReceivesRequestHeadersAndSessionConfigurationHeaders() {
let endpoint = Endpoint.responseHeaders.modifying(\.headers, to: ["Request-Header": "foobar"])
let expectation = expectation(description: "GET request should succeed")
var response: DataResponse<Data?, AFError>?
manager.request(endpoint)
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout)
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
XCTAssertEqual(response?.response?.headers["Request-Header"], "foobar")
XCTAssertEqual(response?.response?.headers["Session-Configuration-Header"], "foo")
}
}