MockURLProtocol.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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, *)
  17. class MockURLProtocol: URLProtocol {
  18. static var requestHandler: ((URLRequest) throws -> (
  19. URLResponse,
  20. AsyncLineSequence<URL.AsyncBytes>?
  21. ))?
  22. override class func canInit(with request: URLRequest) -> Bool { return true }
  23. override class func canonicalRequest(for request: URLRequest) -> URLRequest { return request }
  24. override func startLoading() {
  25. guard let requestHandler = MockURLProtocol.requestHandler else {
  26. fatalError("`requestHandler` is nil.")
  27. }
  28. guard let client = client else {
  29. fatalError("`client` is nil.")
  30. }
  31. Task {
  32. let (response, stream) = try requestHandler(self.request)
  33. client.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
  34. if let stream = stream {
  35. do {
  36. for try await line in stream {
  37. guard let data = line.data(using: .utf8) else {
  38. fatalError("Failed to convert \"\(line)\" to UTF8 data.")
  39. }
  40. client.urlProtocol(self, didLoad: data)
  41. // Add a newline character since AsyncLineSequence strips them when reading line by
  42. // line;
  43. // without the following, the whole file is delivered as a single line.
  44. client.urlProtocol(self, didLoad: "\n".data(using: .utf8)!)
  45. }
  46. } catch {
  47. client.urlProtocol(self, didFailWithError: error)
  48. XCTFail("Unexpected failure reading lines from stream: \(error.localizedDescription)")
  49. }
  50. }
  51. client.urlProtocolDidFinishLoading(self)
  52. }
  53. }
  54. override func stopLoading() {}
  55. }