1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import Foundation
import XCTest
@testable import OldFella
final class RefreshRaceURLProtocol: URLProtocol {
static var handler: ((URLRequest) throws -> (Int, Data))?
private static let lock = NSLock()
private static var requests: [URLRequest] = []
static var recordedRequests: [URLRequest] {
lock.lock()
defer { lock.unlock() }
return requests
}
static func clearRequests() {
lock.lock()
requests = []
lock.unlock()
}
override static func canInit(with request: URLRequest) -> Bool { true }
override static func canonicalRequest(for request: URLRequest) -> URLRequest { request }
override func startLoading() {
Self.lock.lock()
Self.requests.append(request)
let handler = Self.handler
Self.lock.unlock()
guard let handler, let url = request.url else {
client?.urlProtocol(self, didFailWithError: ServiceError.invalidResponse)
return
}
let request = self.request
DispatchQueue.global().async {
let result: (Int, Data)
do {
result = try handler(request)
} catch {
self.client?.urlProtocol(self, didFailWithError: error)
return
}
guard
let response = HTTPURLResponse(
url: url, statusCode: result.0, httpVersion: "HTTP/1.1",
headerFields: ["Content-Type": "application/json"])
else {
self.client?.urlProtocol(self, didFailWithError: ServiceError.invalidResponse)
return
}
self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
self.client?.urlProtocol(self, didLoad: result.1)
self.client?.urlProtocolDidFinishLoading(self)
}
}
override func stopLoading() {}
}