URLSessionPartialMock.swift 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. // 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. enum TestCase {
  27. case success
  28. case unauthenticatedFailure
  29. case unknownFailure
  30. }
  31. var testCase: TestCase
  32. // Properties to control what gets returned to the URLSession callback.
  33. var data: Data?
  34. var response: URLResponse?
  35. var error: Error?
  36. var responseData: Data?
  37. required init(testCase: TestCase, responseData: Data? = nil) {
  38. self.testCase = testCase
  39. self.responseData = responseData
  40. }
  41. override func dataTask(with request: URLRequest,
  42. completionHandler: @escaping @Sendable (Data?, URLResponse?, Error?)
  43. -> Void) -> URLSessionDataTask {
  44. createResponse(request: request)
  45. return URLSessionDataTaskMock {
  46. completionHandler(self.data, self.response, self.error)
  47. }
  48. }
  49. private func createResponse(request: URLRequest) {
  50. let fakeErrorDomain = "test.failure.domain"
  51. switch testCase {
  52. case .success:
  53. data = responseData
  54. response = HTTPURLResponse(url: request.url!,
  55. statusCode: 200,
  56. httpVersion: nil,
  57. headerFields: nil)
  58. case .unauthenticatedFailure:
  59. data = nil
  60. response = HTTPURLResponse(url: request.url!,
  61. statusCode: 401,
  62. httpVersion: nil,
  63. headerFields: nil)
  64. error = nil
  65. case .unknownFailure:
  66. data = nil
  67. response = HTTPURLResponse(url: request.url!,
  68. statusCode: 500,
  69. httpVersion: nil,
  70. headerFields: nil)
  71. error = NSError(domain: fakeErrorDomain, code: 1)
  72. }
  73. }
  74. }