HTTPSCallableTests.swift 7.0 KB

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