From ef6a30d8c067e81f4a7a72ce46d66275b120ca70 Mon Sep 17 00:00:00 2001 From: Javier Cicchelli Date: Sun, 17 Mar 2024 18:18:33 +0100 Subject: [PATCH] Implemented the MockURLProtocol class in the Foundation library. --- .../Kit/Sources/Classes/MockURLProtocol.swift | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 Libraries/Foundation/Kit/Sources/Classes/MockURLProtocol.swift diff --git a/Libraries/Foundation/Kit/Sources/Classes/MockURLProtocol.swift b/Libraries/Foundation/Kit/Sources/Classes/MockURLProtocol.swift new file mode 100644 index 0000000..805cc8d --- /dev/null +++ b/Libraries/Foundation/Kit/Sources/Classes/MockURLProtocol.swift @@ -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) + } + } + + } +}