AsyncSequenceTests.swift 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. // Copyright 2025 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 FirebaseCore
  15. @testable import FirebaseRemoteConfig
  16. import XCTest
  17. #if SWIFT_PACKAGE
  18. import RemoteConfigFakeConsoleObjC
  19. #endif
  20. // MARK: - Mock Objects for Testing
  21. /// A mock listener registration that allows tests to verify that its `remove()` method was called.
  22. class MockListenerRegistration: ConfigUpdateListenerRegistration, @unchecked Sendable {
  23. var wasRemoveCalled = false
  24. override func remove() {
  25. wasRemoveCalled = true
  26. }
  27. }
  28. /// A mock for the RCNConfigRealtime component that allows tests to control the config update
  29. /// listener.
  30. class MockRealtime: RCNConfigRealtime, @unchecked Sendable {
  31. /// The listener closure captured from the `configUpdates` async stream.
  32. var listener: ((RemoteConfigUpdate?, Error?) -> Void)?
  33. let mockRegistration = MockListenerRegistration()
  34. var listenerAttachedExpectation: XCTestExpectation?
  35. override func addConfigUpdateListener(_ listener: @escaping (RemoteConfigUpdate?, Error?)
  36. -> Void) -> ConfigUpdateListenerRegistration {
  37. self.listener = listener
  38. listenerAttachedExpectation?.fulfill()
  39. return mockRegistration
  40. }
  41. /// Simulates the backend sending a successful configuration update.
  42. func sendUpdate(keys: [String]) {
  43. let update = RemoteConfigUpdate(updatedKeys: Set(keys))
  44. listener?(update, nil)
  45. }
  46. /// Simulates the backend sending an error.
  47. func sendError(_ error: Error) {
  48. listener?(nil, error)
  49. }
  50. /// Simulates the listener completing without an update or error.
  51. func sendCompletion() {
  52. listener?(nil, nil)
  53. }
  54. }
  55. // MARK: - AsyncSequenceTests
  56. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  57. class AsyncSequenceTests: XCTestCase {
  58. var app: FirebaseApp!
  59. var config: RemoteConfig!
  60. var mockRealtime: MockRealtime!
  61. struct TestError: Error, Equatable {}
  62. override func setUpWithError() throws {
  63. try super.setUpWithError()
  64. // Perform one-time setup of the FirebaseApp for testing.
  65. if FirebaseApp.app() == nil {
  66. let options = FirebaseOptions(googleAppID: "1:123:ios:123abc",
  67. gcmSenderID: "correct_gcm_sender_id")
  68. options.apiKey = "A23456789012345678901234567890123456789"
  69. options.projectID = "Fake_Project"
  70. FirebaseApp.configure(options: options)
  71. }
  72. app = FirebaseApp.app()!
  73. config = RemoteConfig.remoteConfig(app: app)
  74. // Install the mock realtime service.
  75. mockRealtime = MockRealtime()
  76. config.configRealtime = mockRealtime
  77. }
  78. override func tearDownWithError() throws {
  79. app = nil
  80. config = nil
  81. mockRealtime = nil
  82. try super.tearDownWithError()
  83. }
  84. func testSequenceYieldsUpdate_whenUpdateIsSent() async throws {
  85. let expectation = self.expectation(description: "Sequence should yield an update.")
  86. let keysToUpdate = ["foo", "bar"]
  87. let listenerAttachedExpectation = self.expectation(description: "Listener should be attached.")
  88. mockRealtime.listenerAttachedExpectation = listenerAttachedExpectation
  89. let listeningTask = Task {
  90. for try await update in config.configUpdates {
  91. XCTAssertEqual(update.updatedKeys, Set(keysToUpdate))
  92. expectation.fulfill()
  93. break // End the loop after receiving the expected update.
  94. }
  95. }
  96. // Wait for the listener to be attached before sending the update.
  97. await fulfillment(of: [listenerAttachedExpectation], timeout: 1.0)
  98. mockRealtime.sendUpdate(keys: keysToUpdate)
  99. await fulfillment(of: [expectation], timeout: 1.0)
  100. listeningTask.cancel()
  101. }
  102. func testSequenceFinishes_whenErrorIsSent() async throws {
  103. let expectation = self.expectation(description: "Sequence should throw an error.")
  104. let testError = TestError()
  105. let listenerAttachedExpectation = self.expectation(description: "Listener should be attached.")
  106. mockRealtime.listenerAttachedExpectation = listenerAttachedExpectation
  107. let listeningTask = Task {
  108. do {
  109. for try await _ in config.configUpdates {
  110. XCTFail("Stream should not have yielded any updates.")
  111. }
  112. } catch {
  113. XCTAssertEqual(error as? TestError, testError)
  114. expectation.fulfill()
  115. }
  116. }
  117. // Wait for the listener to be attached before sending the error.
  118. await fulfillment(of: [listenerAttachedExpectation], timeout: 1.0)
  119. mockRealtime.sendError(testError)
  120. await fulfillment(of: [expectation], timeout: 1.0)
  121. listeningTask.cancel()
  122. }
  123. func testSequenceCancellation_callsRemoveOnListener() async throws {
  124. let listenerAttachedExpectation = expectation(description: "Listener should be attached.")
  125. mockRealtime.listenerAttachedExpectation = listenerAttachedExpectation
  126. let listeningTask = Task {
  127. for try await _ in config.configUpdates {
  128. // We will cancel the task, so it should not reach here.
  129. }
  130. }
  131. // Wait for the listener to be attached.
  132. await fulfillment(of: [listenerAttachedExpectation], timeout: 1.0)
  133. // Verify the listener has not been removed yet.
  134. XCTAssertFalse(mockRealtime.mockRegistration.wasRemoveCalled)
  135. // Cancel the task, which should trigger the stream's onTermination handler.
  136. listeningTask.cancel()
  137. // Give the cancellation a moment to propagate.
  138. try await Task.sleep(nanoseconds: 100_000_000) // 0.1 seconds
  139. // Verify the listener was removed.
  140. XCTAssertTrue(mockRealtime.mockRegistration.wasRemoveCalled)
  141. }
  142. func testSequenceFinishesGracefully_whenListenerSendsNil() async throws {
  143. let expectation = self.expectation(description: "Sequence should finish without error.")
  144. let listenerAttachedExpectation = self.expectation(description: "Listener should be attached.")
  145. mockRealtime.listenerAttachedExpectation = listenerAttachedExpectation
  146. let listeningTask = Task {
  147. var updateCount = 0
  148. do {
  149. for try await _ in config.configUpdates {
  150. updateCount += 1
  151. }
  152. // The loop finished without throwing, which is the success condition.
  153. XCTAssertEqual(updateCount, 0, "No updates should have been received.")
  154. expectation.fulfill()
  155. } catch {
  156. XCTFail("Stream should not have thrown an error, but threw \(error).")
  157. }
  158. }
  159. await fulfillment(of: [listenerAttachedExpectation], timeout: 1.0)
  160. mockRealtime.sendCompletion()
  161. await fulfillment(of: [expectation], timeout: 1.0)
  162. listeningTask.cancel()
  163. }
  164. func testSequenceYieldsMultipleUpdates_whenMultipleUpdatesAreSent() async throws {
  165. let expectation = self.expectation(description: "Sequence should receive two updates.")
  166. expectation.expectedFulfillmentCount = 2
  167. let updatesToSend = [
  168. Set(["key1", "key2"]),
  169. Set(["key3"]),
  170. ]
  171. var receivedUpdates: [Set<String>] = []
  172. let listenerAttachedExpectation = self.expectation(description: "Listener should be attached.")
  173. mockRealtime.listenerAttachedExpectation = listenerAttachedExpectation
  174. let listeningTask = Task {
  175. for try await update in config.configUpdates {
  176. receivedUpdates.append(update.updatedKeys)
  177. expectation.fulfill()
  178. if receivedUpdates.count == updatesToSend.count {
  179. break
  180. }
  181. }
  182. return receivedUpdates
  183. }
  184. await fulfillment(of: [listenerAttachedExpectation], timeout: 1.0)
  185. mockRealtime.sendUpdate(keys: Array(updatesToSend[0]))
  186. mockRealtime.sendUpdate(keys: Array(updatesToSend[1]))
  187. await fulfillment(of: [expectation], timeout: 2.0)
  188. let finalUpdates = try await listeningTask.value
  189. XCTAssertEqual(finalUpdates, updatesToSend)
  190. listeningTask.cancel()
  191. }
  192. }