URLSessionPartialMock.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. // Create a partial mock by subclassing the URLSessionDataTask.
  16. class URLSessionDataTaskMock: URLSessionDataTask {
  17. private let closure: () -> Void
  18. init(closure: @escaping () -> Void) {
  19. self.closure = closure
  20. }
  21. override func resume() {
  22. closure()
  23. }
  24. }
  25. class URLSessionMock: URLSession {
  26. typealias CompletionHandler = (Data?, URLResponse?, Error?) -> Void
  27. private let fakeConsole: FakeConsole
  28. init(with fakeConsole: FakeConsole) {
  29. self.fakeConsole = fakeConsole
  30. }
  31. // Properties to control what gets returned to the URLSession callback.
  32. // error could also be added here.
  33. var data: Data?
  34. var response: URLResponse?
  35. var etag = ""
  36. override func dataTask(with request: URLRequest,
  37. completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void)
  38. -> URLSessionDataTask {
  39. let consoleValues = fakeConsole.get()
  40. if etag == "" || consoleValues["state"] as! String == RCNFetchResponseKeyStateUpdate {
  41. // Time string in microseconds to insure a different string from previous change.
  42. etag = String(NSDate().timeIntervalSince1970)
  43. }
  44. let jsonData = try! JSONSerialization.data(withJSONObject: consoleValues)
  45. let response = HTTPURLResponse(url: URL(fileURLWithPath: "fakeURL"),
  46. statusCode: 200,
  47. httpVersion: nil,
  48. headerFields: ["etag": etag])
  49. return URLSessionDataTaskMock {
  50. completionHandler(jsonData, response, nil)
  51. }
  52. }
  53. }