-
Notifications
You must be signed in to change notification settings - Fork 1
/
MockSpider.swift
69 lines (57 loc) · 1.97 KB
/
MockSpider.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
//
// File.swift
//
//
// Created by Denys Telezhkin on 05.01.2021.
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
import Swarm
class MockSpider : Spider {
enum Response {
case response(Data?, URLResponse?, Error?)
case infiniteLoading
}
var mockResponse: Response?
init() {}
@discardableResult func stubResponse(_ data: Data? = nil, _ response: URLResponse? = nil, _ error: Error? = nil) -> Self {
mockResponse = .response(data, response, error)
return self
}
@discardableResult func stubSuccess(data: Data = .init(), statusCode: Int = 200) -> Self {
mockResponse = .response(data, HTTPURLResponse.withStatus(statusCode), nil)
return self
}
@discardableResult func stubFailure(error: Error, statusCode: Int) -> Self {
mockResponse = .response(nil, HTTPURLResponse.withStatus(statusCode), error)
return self
}
@discardableResult func stubInfiniteLoading() -> Self {
mockResponse = .infiniteLoading
return self
}
var conditionalSetup : ((MockSpider) -> ())?
func conditionallyStub(_ closure: @escaping (MockSpider) -> ()) {
conditionalSetup = closure
}
var requestCount = 0
func request(url: ScrappableURL, completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
requestCount += 1
if let conditionalSetup = conditionalSetup {
conditionalSetup(self)
}
switch mockResponse {
case .response(let data, let response, let error):
completion(data, response, error)
case .infiniteLoading: ()
case .none: ()
}
}
}
private extension HTTPURLResponse {
static func withStatus(_ statusCode: Int) -> HTTPURLResponse {
return HTTPURLResponse(url: URL(fileURLWithPath: ""), statusCode: statusCode, httpVersion: "HTTP/1.1", headerFields: nil)!
}
}