MockURLProtocol.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. nonisolated(unsafe) static var requestHandler: ((URLRequest) throws -> (
  19. URLResponse,
  20. AsyncLineSequence<URL.AsyncBytes>?
  21. ))?
  22. override class func canInit(with request: URLRequest) -> Bool {
  23. #if os(watchOS)
  24. print("MockURLProtocol cannot be used on watchOS.")
  25. return false
  26. #else
  27. return true
  28. #endif // os(watchOS)
  29. }
  30. override class func canonicalRequest(for request: URLRequest) -> URLRequest { return request }
  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. Task {
  39. let (response, stream) = try requestHandler(self.request)
  40. client.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
  41. if let stream = stream {
  42. do {
  43. for try await line in stream {
  44. guard let data = line.data(using: .utf8) else {
  45. fatalError("Failed to convert \"\(line)\" to UTF8 data.")
  46. }
  47. client.urlProtocol(self, didLoad: data)
  48. // Add a newline character since AsyncLineSequence strips them when reading line by
  49. // line;
  50. // without the following, the whole file is delivered as a single line.
  51. client.urlProtocol(self, didLoad: "\n".data(using: .utf8)!)
  52. }
  53. } catch {
  54. client.urlProtocol(self, didFailWithError: error)
  55. XCTFail("Unexpected failure reading lines from stream: \(error.localizedDescription)")
  56. }
  57. }
  58. client.urlProtocolDidFinishLoading(self)
  59. }
  60. }
  61. override func stopLoading() {}
  62. }