URLSessionPartialMock.swift 2.2 KB

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