Implemented the MockURLProtocol protocol for mocking URL responses.
This commit is contained in:
parent
35c2340a9b
commit
c1a2acb248
@ -0,0 +1,62 @@
|
|||||||
|
//
|
||||||
|
// MockURLProtocol.swift
|
||||||
|
// APICore
|
||||||
|
//
|
||||||
|
// Created by Javier Cicchelli on 10/04/2023.
|
||||||
|
// Copyright © 2023 Röck+Cöde. All rights reserved.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
public class MockURLProtocol: URLProtocol {
|
||||||
|
|
||||||
|
// MARK: Properties
|
||||||
|
|
||||||
|
public static var mockData: [URL: MockURLResponse] = [:]
|
||||||
|
|
||||||
|
// MARK: Functions
|
||||||
|
|
||||||
|
public override class func canInit(with task: URLSessionTask) -> Bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
public override class func canInit(with request: URLRequest) -> Bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
public override class func canonicalRequest(for request: URLRequest) -> URLRequest {
|
||||||
|
request
|
||||||
|
}
|
||||||
|
|
||||||
|
public override func startLoading() {
|
||||||
|
guard
|
||||||
|
let url = request.url,
|
||||||
|
let response = Self.mockData[url]
|
||||||
|
else {
|
||||||
|
client?.urlProtocolDidFinishLoading(self)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if let data = response.data {
|
||||||
|
client?.urlProtocol(self, didLoad: data)
|
||||||
|
}
|
||||||
|
|
||||||
|
if let httpResponse = HTTPURLResponse(
|
||||||
|
url: url,
|
||||||
|
statusCode: response.status,
|
||||||
|
httpVersion: nil,
|
||||||
|
headerFields: response.headers
|
||||||
|
) {
|
||||||
|
client?.urlProtocol(
|
||||||
|
self,
|
||||||
|
didReceive: httpResponse,
|
||||||
|
cacheStoragePolicy: .allowedInMemoryOnly
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
client?.urlProtocolDidFinishLoading(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
public override func stopLoading() {}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,31 @@
|
|||||||
|
//
|
||||||
|
// MockURLResponse.swift
|
||||||
|
// APICore
|
||||||
|
//
|
||||||
|
// Created by Javier Cicchelli on 10/04/2023.
|
||||||
|
// Copyright © 2023 Röck+Cöde. All rights reserved.
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
public struct MockURLResponse {
|
||||||
|
|
||||||
|
// MARK: Properties
|
||||||
|
|
||||||
|
public let status: Int
|
||||||
|
public let headers: [String: String]
|
||||||
|
public let data: Data?
|
||||||
|
|
||||||
|
// MARK: Initialisers
|
||||||
|
|
||||||
|
public init(
|
||||||
|
status: Int,
|
||||||
|
headers: [String : String],
|
||||||
|
data: Data? = nil
|
||||||
|
) {
|
||||||
|
self.status = status
|
||||||
|
self.headers = headers
|
||||||
|
self.data = data
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user