MockURLProtocol.swift 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2023 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. import XCTest
  16. @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
  17. class MockURLProtocol: URLProtocol, @unchecked Sendable {
  18. #if compiler(>=6)
  19. nonisolated(unsafe) static var requestHandler: ((URLRequest) throws -> (
  20. URLResponse,
  21. AsyncLineSequence<URL.AsyncBytes>?
  22. ))?
  23. #else
  24. static var requestHandler: ((URLRequest) throws -> (
  25. URLResponse,
  26. AsyncLineSequence<URL.AsyncBytes>?
  27. ))?
  28. #endif
  29. override class func canInit(with request: URLRequest) -> Bool {
  30. #if os(watchOS)
  31. print("MockURLProtocol cannot be used on watchOS.")
  32. return false
  33. #else
  34. return true
  35. #endif // os(watchOS)
  36. }
  37. override class func canonicalRequest(for request: URLRequest) -> URLRequest { return request }
  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. Task {
  46. let (response, stream) = try requestHandler(self.request)
  47. client.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
  48. if let stream = stream {
  49. do {
  50. for try await line in stream {
  51. guard let data = line.data(using: .utf8) else {
  52. fatalError("Failed to convert \"\(line)\" to UTF8 data.")
  53. }
  54. client.urlProtocol(self, didLoad: data)
  55. // Add a newline character since AsyncLineSequence strips them when reading line by
  56. // line;
  57. // without the following, the whole file is delivered as a single line.
  58. client.urlProtocol(self, didLoad: "\n".data(using: .utf8)!)
  59. }
  60. } catch {
  61. client.urlProtocol(self, didFailWithError: error)
  62. XCTFail("Unexpected failure reading lines from stream: \(error.localizedDescription)")
  63. }
  64. }
  65. client.urlProtocolDidFinishLoading(self)
  66. }
  67. }
  68. override func stopLoading() {}
  69. }