MockURLProtocol.swift 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2020 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. class MockURLProtocol: URLProtocol {
  16. nonisolated(unsafe) static var requestHandler: ((URLRequest) throws -> (
  17. Data,
  18. HTTPURLResponse
  19. ))?
  20. override class func canInit(with request: URLRequest) -> Bool {
  21. #if os(watchOS)
  22. print("MockURLProtocol cannot be used on watchOS.")
  23. return false
  24. #else
  25. return true
  26. #endif // os(watchOS)
  27. }
  28. override class func canonicalRequest(for request: URLRequest) -> URLRequest {
  29. return request
  30. }
  31. override func startLoading() {
  32. guard let requestHandler = MockURLProtocol.requestHandler else {
  33. fatalError("`requestHandler` is nil.")
  34. }
  35. guard let client = client else {
  36. fatalError("`client` is nil.")
  37. }
  38. do {
  39. let (data, respopnse) = try requestHandler(request)
  40. client.urlProtocol(self, didReceive: respopnse, cacheStoragePolicy: .notAllowed)
  41. client.urlProtocol(self, didLoad: data)
  42. client.urlProtocolDidFinishLoading(self)
  43. } catch {
  44. client.urlProtocol(self, didFailWithError: error)
  45. }
  46. }
  47. override func stopLoading() {}
  48. }