Implemented the MockURLProtocol class.
This commit is contained in:
parent
777a50367c
commit
3a87c57371
65
Libraries/Sources/APIService/Classes/MockURLProtocol.swift
Normal file
65
Libraries/Sources/APIService/Classes/MockURLProtocol.swift
Normal file
@ -0,0 +1,65 @@
|
||||
//
|
||||
// MockURLProtocol.swift
|
||||
// APIService
|
||||
//
|
||||
// Created by Javier Cicchelli on 04/12/2022.
|
||||
// Copyright © 2022 Röck+Cöde. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class MockURLProtocol: URLProtocol {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
static var mockData: [URL: MockURLResponse] = [:]
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
override class func canInit(with task: URLSessionTask) -> Bool {
|
||||
true
|
||||
}
|
||||
|
||||
override class func canInit(with request: URLRequest) -> Bool {
|
||||
true
|
||||
}
|
||||
|
||||
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
|
||||
request
|
||||
}
|
||||
|
||||
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.rawValue,
|
||||
httpVersion: nil,
|
||||
headerFields: response.headers
|
||||
) {
|
||||
client?.urlProtocol(self, didReceive: httpResponse, cacheStoragePolicy: .allowedInMemoryOnly)
|
||||
}
|
||||
|
||||
client?.urlProtocolDidFinishLoading(self)
|
||||
}
|
||||
|
||||
override func stopLoading() {}
|
||||
}
|
||||
|
||||
// MARK: - Structs
|
||||
|
||||
struct MockURLResponse {
|
||||
let status: ResponseStatus
|
||||
let headers: [String: String]
|
||||
let data: Data?
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
//
|
||||
// ResponseStatus.swift
|
||||
// APIService
|
||||
//
|
||||
// Created by Javier Cicchelli on 04/12/2022.
|
||||
// Copyright © 2022 Röck+Cöde. All rights reserved.
|
||||
//
|
||||
|
||||
enum ResponseStatus: Int {
|
||||
case ok = 200
|
||||
case created = 201
|
||||
case noContent = 204
|
||||
case badRequest = 400
|
||||
case notFound = 404
|
||||
}
|
@ -8,7 +8,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
struct Item {
|
||||
public struct Item {
|
||||
let idParent: String?
|
||||
let id: String
|
||||
let name: String
|
||||
|
Loading…
x
Reference in New Issue
Block a user