HTTPSCallableTests.swift 7.1 KB

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