-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMockURLProtocol.swift
73 lines (57 loc) · 2.21 KB
/
MockURLProtocol.swift
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
import Foundation
final class MockURLProtocol: URLProtocol {
enum ResponseType {
case error(Error)
case success(HTTPURLResponse)
}
static var responseType: ResponseType!
private lazy var session: URLSession = {
let configuration: URLSessionConfiguration = URLSessionConfiguration.ephemeral
return URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
}()
private(set) var activeTask: URLSessionTask?
override class func canInit(with request: URLRequest) -> Bool {
return true
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool {
return false
}
override func startLoading() {
activeTask = session.dataTask(with: request.urlRequest!)
activeTask?.cancel()
}
override func stopLoading() {
activeTask?.cancel()
}
}
// MARK: - URLSessionDataDelegate
extension MockURLProtocol: URLSessionDataDelegate {
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
client?.urlProtocol(self, didLoad: data)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
switch MockURLProtocol.responseType {
case .error(let error)?:
client?.urlProtocol(self, didFailWithError: error)
case .success(let response)?:
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
default:
break
}
client?.urlProtocolDidFinishLoading(self)
}
}
extension MockURLProtocol {
enum MockError: Error {
case none
}
static func responseWithFailure() {
MockURLProtocol.responseType = MockURLProtocol.ResponseType.error(MockError.none)
}
static func responseWithStatusCode(code: Int) {
MockURLProtocol.responseType = MockURLProtocol.ResponseType.success(HTTPURLResponse(url: URL(string: "http://any.com")!, statusCode: code, httpVersion: nil, headerFields: nil)!)
}
}