HTTPSCallableTests.swift 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. // Copyright 2021 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 Combine
  16. import FirebaseAppCheckInterop
  17. import FirebaseAuthInterop
  18. import FirebaseCore
  19. @testable import FirebaseFunctions
  20. import FirebaseFunctionsCombineSwift
  21. import FirebaseMessagingInterop
  22. import GTMSessionFetcherCore
  23. import XCTest
  24. // hardcoded in HTTPSCallable.swift
  25. private let timeoutInterval: TimeInterval = 70.0
  26. private let expectationTimeout: TimeInterval = 2
  27. class MockFunctions: Functions {
  28. let mockCallFunction: () throws -> HTTPSCallableResult
  29. var verifyParameters: ((_ url: URL, _ data: Any?, _ timeout: TimeInterval) throws -> Void)?
  30. override func callFunction(at url: URL,
  31. withObject data: Any?,
  32. options: HTTPSCallableOptions?,
  33. timeout: TimeInterval,
  34. completion: @escaping (
  35. (Result<HTTPSCallableResult, any Error>) -> Void
  36. )) {
  37. do {
  38. try verifyParameters?(url, data, timeout)
  39. let result = try mockCallFunction()
  40. completion(.success(result))
  41. } catch {
  42. completion(.failure(error))
  43. }
  44. }
  45. init(mockCallFunction: @escaping () throws -> HTTPSCallableResult) {
  46. self.mockCallFunction = mockCallFunction
  47. super.init(
  48. projectID: "dummy-project",
  49. region: "test-region",
  50. customDomain: nil,
  51. auth: nil,
  52. messaging: nil,
  53. appCheck: nil,
  54. fetcherService: GTMSessionFetcherService()
  55. )
  56. }
  57. }
  58. public class HTTPSCallableResultFake: HTTPSCallableResult {
  59. let fakeData: String
  60. init(data: String) {
  61. fakeData = data
  62. super.init(data: data)
  63. }
  64. }
  65. @available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 6.0, *)
  66. class HTTPSCallableTests: XCTestCase {
  67. func testCallWithoutParametersSuccess() {
  68. // given
  69. var cancellables = Set<AnyCancellable>()
  70. let httpsFunctionWasCalledExpectation = expectation(description: "HTTPS Function was called")
  71. let functionWasCalledExpectation = expectation(description: "Function was called")
  72. let expectedResult = "mockResult w/o parameters"
  73. let functions = MockFunctions {
  74. httpsFunctionWasCalledExpectation.fulfill()
  75. return HTTPSCallableResultFake(data: expectedResult)
  76. }
  77. let dummyFunction = functions.httpsCallable("dummyFunction")
  78. // when
  79. dummyFunction.call()
  80. .sink { completion in
  81. switch completion {
  82. case .finished:
  83. print("Finished")
  84. case let .failure(error):
  85. XCTFail("💥 Something went wrong: \(error)")
  86. }
  87. } receiveValue: { functionResult in
  88. guard let result = functionResult.data as? String else {
  89. XCTFail("Expected String data")
  90. return
  91. }
  92. XCTAssertEqual(result, expectedResult)
  93. functionWasCalledExpectation.fulfill()
  94. }
  95. .store(in: &cancellables)
  96. // then
  97. wait(
  98. for: [functionWasCalledExpectation, httpsFunctionWasCalledExpectation],
  99. timeout: expectationTimeout
  100. )
  101. }
  102. func testCallWithParametersSuccess() {
  103. // given
  104. var cancellables = Set<AnyCancellable>()
  105. let httpsFunctionWasCalledExpectation = expectation(description: "HTTPS Function was called")
  106. let functionWasCalledExpectation = expectation(description: "Function was called")
  107. let inputParameter = "input parameter"
  108. let expectedResult = "mockResult w/ parameters: \(inputParameter)"
  109. let functions = MockFunctions {
  110. httpsFunctionWasCalledExpectation.fulfill()
  111. return HTTPSCallableResultFake(data: expectedResult)
  112. }
  113. functions.verifyParameters = { url, data, timeout in
  114. XCTAssertEqual(
  115. url.absoluteString,
  116. "https://test-region-dummy-project.cloudfunctions.net/dummyFunction"
  117. )
  118. XCTAssertEqual(data as? String, inputParameter)
  119. XCTAssertEqual(timeout as TimeInterval, timeoutInterval)
  120. }
  121. let dummyFunction = functions.httpsCallable("dummyFunction")
  122. // when
  123. dummyFunction.call(inputParameter)
  124. .sink { completion in
  125. switch completion {
  126. case .finished:
  127. print("Finished")
  128. case let .failure(error):
  129. XCTFail("💥 Something went wrong: \(error)")
  130. }
  131. } receiveValue: { functionResult in
  132. guard let result = functionResult.data as? String else {
  133. XCTFail("Expected String data")
  134. return
  135. }
  136. XCTAssertEqual(result, expectedResult)
  137. functionWasCalledExpectation.fulfill()
  138. }
  139. .store(in: &cancellables)
  140. // then
  141. wait(
  142. for: [httpsFunctionWasCalledExpectation, functionWasCalledExpectation],
  143. timeout: expectationTimeout
  144. )
  145. }
  146. func testCallWithParametersFailure() {
  147. // given
  148. var cancellables = Set<AnyCancellable>()
  149. let httpsFunctionWasCalledExpectation = expectation(description: "HTTPS Function was called")
  150. let functionCallFailedExpectation = expectation(description: "Function call failed")
  151. let inputParameter = "input parameter"
  152. let functions = MockFunctions {
  153. httpsFunctionWasCalledExpectation.fulfill()
  154. throw NSError(domain: FunctionsErrorDomain,
  155. code: FunctionsErrorCode.internal.rawValue,
  156. userInfo: [NSLocalizedDescriptionKey: "Response is missing data field."])
  157. }
  158. functions.verifyParameters = { url, data, timeout in
  159. XCTAssertEqual(
  160. url.absoluteString,
  161. "https://test-region-dummy-project.cloudfunctions.net/dummyFunction"
  162. )
  163. XCTAssertEqual(data as? String, inputParameter)
  164. XCTAssertEqual(timeout as TimeInterval, timeoutInterval)
  165. }
  166. let dummyFunction = functions.httpsCallable("dummyFunction")
  167. // when
  168. dummyFunction.call(inputParameter)
  169. .sink { completion in
  170. if case let .failure(error as NSError) = completion {
  171. // Verify user mismatch error.
  172. XCTAssertEqual(error.code, FunctionsErrorCode.internal.rawValue)
  173. functionCallFailedExpectation.fulfill()
  174. }
  175. } receiveValue: { functionResult in
  176. XCTFail("💥 result unexpected")
  177. }
  178. .store(in: &cancellables)
  179. // then
  180. wait(
  181. for: [functionCallFailedExpectation, httpsFunctionWasCalledExpectation],
  182. timeout: expectationTimeout
  183. )
  184. }
  185. }