Implemented the MockURLProtocol class in the Foundation library.

This commit is contained in:
Javier Cicchelli 2024-03-17 18:18:33 +01:00
parent 910fc0b612
commit ef6a30d8c0

View File

@ -0,0 +1,88 @@
//
// 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
) {
self.statusCode = statusCode
self.object = object
}
// MARK: Computed
var data: Data? {
get throws {
try JSONEncoder().encode(object)
}
}
}
}