MockURLProtocol.swift 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. #if compiler(>=6)
  17. nonisolated(unsafe) static var requestHandler: ((URLRequest) throws -> (
  18. Data,
  19. HTTPURLResponse
  20. ))?
  21. #else
  22. static var requestHandler: ((URLRequest) throws -> (
  23. Data,
  24. HTTPURLResponse
  25. ))?
  26. #endif
  27. override class func canInit(with request: URLRequest) -> Bool {
  28. #if os(watchOS)
  29. print("MockURLProtocol cannot be used on watchOS.")
  30. return false
  31. #else
  32. return true
  33. #endif // os(watchOS)
  34. }
  35. override class func canonicalRequest(for request: URLRequest) -> URLRequest {
  36. return request
  37. }
  38. override func startLoading() {
  39. guard let requestHandler = MockURLProtocol.requestHandler else {
  40. fatalError("`requestHandler` is nil.")
  41. }
  42. guard let client = client else {
  43. fatalError("`client` is nil.")
  44. }
  45. do {
  46. let (data, respopnse) = try requestHandler(request)
  47. client.urlProtocol(self, didReceive: respopnse, cacheStoragePolicy: .notAllowed)
  48. client.urlProtocol(self, didLoad: data)
  49. client.urlProtocolDidFinishLoading(self)
  50. } catch {
  51. client.urlProtocol(self, didFailWithError: error)
  52. }
  53. }
  54. override func stopLoading() {}
  55. }