91 lines
2.1 KiB
Swift
91 lines
2.1 KiB
Swift
|
//
|
||
|
// MockURLProtocol.swift
|
||
|
// ReviewsFoundationKit
|
||
|
//
|
||
|
// Created by Javier Cicchelli on 17/03/2024.
|
||
|
// Copyright © 2024 Röck+Cöde VoF. All rights reserved.
|
||
|
//
|
||
|
|
||
|
import Foundation
|
||
|
|
||
|
public class MockURLProtocol: URLProtocol {
|
||
|
|
||
|
// MARK: Properties
|
||
|
public static var response: Response?
|
||
|
|
||
|
// 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.response
|
||
|
else {
|
||
|
client?.urlProtocolDidFinishLoading(self)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
if let data = try? response.data {
|
||
|
client?.urlProtocol(self, didLoad: data)
|
||
|
}
|
||
|
|
||
|
if let httpResponse = HTTPURLResponse(
|
||
|
url: url,
|
||
|
statusCode: response.statusCode,
|
||
|
httpVersion: nil,
|
||
|
headerFields: nil
|
||
|
) {
|
||
|
client?.urlProtocol(
|
||
|
self,
|
||
|
didReceive: httpResponse,
|
||
|
cacheStoragePolicy: .allowedInMemoryOnly
|
||
|
)
|
||
|
}
|
||
|
|
||
|
client?.urlProtocolDidFinishLoading(self)
|
||
|
}
|
||
|
|
||
|
public override func stopLoading() {}
|
||
|
|
||
|
}
|
||
|
|
||
|
// MARK: - Structs
|
||
|
|
||
|
extension MockURLProtocol {
|
||
|
public struct Response {
|
||
|
|
||
|
// MARK: Constants
|
||
|
public let statusCode: Int
|
||
|
public let object: (any Encodable)?
|
||
|
|
||
|
// MARK: Initialisers
|
||
|
public init(
|
||
|
statusCode: Int,
|
||
|
object: (any Codable)? = nil
|
||
|
) {
|
||
|
self.statusCode = statusCode
|
||
|
self.object = object
|
||
|
}
|
||
|
|
||
|
// MARK: Computed
|
||
|
var data: Data? {
|
||
|
get throws {
|
||
|
guard let object else { return nil }
|
||
|
|
||
|
return try JSONEncoder.default.encode(object)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
}
|
||
|
}
|