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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import Foundation
import XCTest
@testable import OldFella
final class StubURLProtocol: URLProtocol {
static var handler: ((URLRequest) throws -> (Int, Data))?
static var errorHandler: ((URLRequest) -> Error?)?
private static let lock = NSLock()
private static var requests: [URLRequest] = []
private static var bodies: [URL: Data] = [:]
static func recordedBody(for url: URL) -> Data? {
lock.lock()
defer { lock.unlock() }
return bodies[url]
}
static var recordedRequests: [URLRequest] {
lock.lock()
defer { lock.unlock() }
return requests
}
static func clearRequests() {
lock.lock()
requests = []
bodies = [:]
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)
if let url = request.url, let body = request.httpBody ?? Self.readBody(request.httpBodyStream) {
Self.bodies[url] = body
}
Self.lock.unlock()
if let error = Self.errorHandler?(request) {
client?.urlProtocol(self, didFailWithError: error)
return
}
guard let handler = Self.handler,
let url = request.url
else {
client?.urlProtocol(self, didFailWithError: ServiceError.invalidResponse)
return
}
let result: (Int, Data)
do {
result = try handler(request)
} catch {
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 {
client?.urlProtocol(self, didFailWithError: ServiceError.invalidResponse)
return
}
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
client?.urlProtocol(self, didLoad: result.1)
client?.urlProtocolDidFinishLoading(self)
}
override func stopLoading() {}
private static func readBody(_ stream: InputStream?) -> Data? {
guard let stream else { return nil }
stream.open()
defer { stream.close() }
var data = Data()
let bufferSize = 4096
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
defer { buffer.deallocate() }
while stream.hasBytesAvailable {
let count = stream.read(buffer, maxLength: bufferSize)
if count <= 0 { break }
data.append(buffer, count: count)
}
return data.isEmpty ? nil : data
}
}