From df31badb8336be36f8a5d6011a9b261fb9b17512 Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Thu, 12 Oct 2023 22:29:37 -0400 Subject: [PATCH] fix: unit tests fulfillment --- ...SAPICategoryPlugin+ReachabilityTests.swift | 2 +- .../Operation/AWSGraphQLOperationTests.swift | 2 +- ...phQLSubscriptionOperationCancelTests.swift | 2 +- ...hQLSubscriptionTaskRunnerCancelTests.swift | 8 +- .../Operation/AWSRESTOperationTests.swift | 4 +- .../GraphQLSubscribeCombineTests.swift | 101 ++++------- .../Operation/GraphQLSubscribeTaskTests.swift | 159 +++++++----------- .../Operation/GraphQLSubscribeTests.swift | 12 +- .../NetworkReachabilityNotifierTests.swift | 4 +- .../VerifyPasswordSRPTests.swift | 5 +- .../ConfigurationTests/EscapeHatchTests.swift | 2 +- .../AmplifyAuthCognitoPluginTests.swift | 4 +- .../AWSDataStorePluginBaseBehaviorTests.swift | 6 +- ...ataStorePluginSubscribeBehaviorTests.swift | 2 +- .../Core/ListTests.swift | 1 - .../SQLiteStorageEngineAdapterJsonTests.swift | 18 +- .../SQLiteStorageEngineAdapterTests.swift | 38 ++--- .../Core/StateMachineTests.swift | 16 +- .../StorageAdapterMutationSyncTests.swift | 2 +- ...utationSyncMetadataMigrationTestBase.swift | 8 +- ...SyncMetadataMigrationValidationTests.swift | 4 +- .../Storage/CascadeDeleteOperationTests.swift | 8 +- .../Storage/StorageEnginePublisherTests.swift | 14 +- .../Storage/StorageEngineTestsBase.swift | 8 +- .../Storage/StorageEngineTestsDelete.swift | 2 +- .../Storage/StorageEngineTestsHasMany.swift | 6 +- .../Storage/StorageEngineTestsHasOne.swift | 4 +- .../StorageEngineTestsManyToMany.swift | 4 +- .../StorageEngineTestsSQLiteIndex.swift | 4 +- .../ObserveQueryTaskRunnerTests.swift | 73 ++++---- .../InitialSyncOperationTests.swift | 6 +- .../InitialSyncOrchestratorTests.swift | 22 ++- .../InitialSync/ReadyEventEmitterTests.swift | 2 +- .../LocalSubscriptionWithJSONModelTests.swift | 22 +-- .../MutationEventClearStateTests.swift | 11 +- ...ationIngesterConflictResolutionTests.swift | 11 +- .../OutgoingMutationQueueNetworkTests.swift | 11 +- .../OutgoingMutationQueueTests.swift | 28 ++- ...tationQueueTestsWithMockStateMachine.swift | 16 +- ...MutationErrorFromCloudOperationTests.swift | 82 ++++----- .../RemoteSyncAPIInvocationTests.swift | 13 +- .../Sync/RemoteSyncEngineTests.swift | 96 +++++++---- ...ncomingEventReconciliationQueueTests.swift | 10 +- .../ModelReconciliationDeleteTests.swift | 11 +- ...odelReconciliationQueueBehaviorTests.swift | 52 +++++- .../ReconcileAndSaveQueueTests.swift | 12 +- .../MutationEventExtensionsTests.swift | 24 +-- .../Support/MutationEventQueryTests.swift | 10 +- .../TestSupport/BaseDataStoreTests.swift | 2 +- .../TestSupport/SyncEngineTestBase.swift | 4 +- .../AWSDataStorePrimaryKeyBaseTest.swift | 28 ++- .../DataStoreConsecutiveUpdatesTests.swift | 38 ++--- .../DataStoreCustomPrimaryKeyTests.swift | 10 +- .../DataStoreEndToEndTests.swift | 2 +- .../DataStoreStressBaseTest.swift | 2 +- ...SLocationGeoPluginConfigurationTests.swift | 4 +- .../Mocks/MockAnalyticsClient.swift | 20 +-- .../AWSCloudWatchLoggingMonitorTests.swift | 2 +- .../LoggingNetworkMonitorTests.swift | 2 +- ...SS3StorageDownloadFileOperationTests.swift | 4 +- .../AWSS3StorageGetDataOperationTests.swift | 43 ++--- .../AWSS3StorageRemoveOperationTests.swift | 8 +- ...WSS3StorageUploadFileOperationTests2.swift | 2 +- .../Support/Internal/FileSystemTests.swift | 2 +- .../StorageMultipartUploadSessionTests.swift | 10 +- .../API/APICategoryClientGraphQLTests.swift | 11 +- .../API/APICategoryConfigurationTests.swift | 19 ++- .../API/RetryableGraphQLOperationTests.swift | 6 +- .../Auth/AuthCategoryConfigurationTests.swift | 2 +- .../DataStoreCategoryClientAPITests.swift | 10 +- .../DataStoreCategoryConfigurationTests.swift | 26 +-- .../ArrayLiteralListProviderTests.swift | 4 +- .../DataStore/Model/ListTests.swift | 10 +- .../Hub/AmplifyOperationHubTests.swift | 2 +- .../DefaultHubPluginConcurrencyTests.swift | 2 +- .../DefaultHubPluginCustomChannelTests.swift | 6 +- .../DefaultHubPluginTests.swift | 8 +- ...hNotificationsCategoryClientAPITests.swift | 8 +- ...lifyConfigurationInitializationTests.swift | 2 +- AmplifyTests/CoreTests/AmplifyTaskTests.swift | 2 +- AmplifyTests/CoreTests/ChildTaskTests.swift | 4 +- .../CoreTests/ConfigurationTests.swift | 2 +- 82 files changed, 679 insertions(+), 590 deletions(-) diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+ReachabilityTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+ReachabilityTests.swift index 02bb53ac30..5f5f38ff2f 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+ReachabilityTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/AWSAPICategoryPlugin+ReachabilityTests.swift @@ -114,7 +114,7 @@ class AWSAPICategoryPluginReachabilityTests: XCTestCase { concurrentPerformCompleted.fulfill() } - await fulfillment(of: [concurrentPerformCompleted], timeout: 1) + wait(for: [concurrentPerformCompleted], timeout: 1) XCTAssertEqual(apiPlugin.reachabilityMap.count, 2) } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLOperationTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLOperationTests.swift index 3fff3057c9..93af2539b2 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLOperationTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLOperationTests.swift @@ -32,7 +32,7 @@ class AWSGraphQLOperationTests: AWSAPICategoryPluginTestBase { } receiveValue: { _ in } defer { sink.cancel() } - await fulfillment(of: [receivedCompletion], timeout: 1) + wait(for: [receivedCompletion], timeout: 1) let task = operation.mapper.task(for: operation) XCTAssertNil(task) } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLSubscriptionOperationCancelTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLSubscriptionOperationCancelTests.swift index 10541326c5..b54fe33c70 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLSubscriptionOperationCancelTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLSubscriptionOperationCancelTests.swift @@ -231,7 +231,7 @@ class AWSGraphQLSubscriptionOperationCancelTests: XCTestCase { completionListener: nil ) await fulfillment( - of: [receivedValue], + of: [receivedValue, connectionCreation], timeout: 5 ) diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLSubscriptionTaskRunnerCancelTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLSubscriptionTaskRunnerCancelTests.swift index e566ef7012..583886dff3 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLSubscriptionTaskRunnerCancelTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSGraphQLSubscriptionTaskRunnerCancelTests.swift @@ -112,9 +112,9 @@ class AWSGraphQLSubscriptionTaskRunnerCancelTests: XCTestCase { receivedFailure.fulfill() } } - await fulfillment(of: [receivedValueConnecting]) + await fulfillment(of: [receivedValueConnecting], timeout: 1) subscriptionEvents.cancel() - await fulfillment(of: [receivedValueDisconnected, receivedCompletion, receivedFailure]) + await fulfillment(of: [receivedValueDisconnected, receivedCompletion, receivedFailure], timeout: 1) } func testFailureOnConnection() async { @@ -171,8 +171,12 @@ class AWSGraphQLSubscriptionTaskRunnerCancelTests: XCTestCase { responseType: JSONValue.self) let receivedValue = expectation(description: "Received value for connecting") + receivedValue.expectedFulfillmentCount = 1 + receivedValue.assertForOverFulfill = false + let receivedFailure = expectation(description: "Received failure") receivedFailure.isInverted = true + let receivedCompletion = expectation(description: "Received completion") let subscriptionEvents = apiPlugin.subscribe(request: request) diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSRESTOperationTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSRESTOperationTests.swift index 6276160960..c65f1257ac 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSRESTOperationTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSRESTOperationTests.swift @@ -93,7 +93,7 @@ class AWSRESTOperationTests: OperationTestBase { callbackInvoked.fulfill() } - await fulfillment(of: [callbackInvoked], timeout: 1.0) + wait(for: [callbackInvoked], timeout: 1.0) } func testRESTOperation_withCustomHeader_shouldOverrideDefaultAmplifyHeaders() throws { @@ -118,7 +118,7 @@ class AWSRESTOperationTests: OperationTestBase { } callbackInvoked.fulfill() } - await fulfillment(of: [callbackInvoked, validated], timeout: 1.0) + wait(for: [callbackInvoked, validated], timeout: 1.0) } } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeCombineTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeCombineTests.swift index 19fa27b57f..8fbc7bcbbc 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeCombineTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeCombineTests.swift @@ -19,18 +19,18 @@ class GraphQLSubscribeCombineTests: OperationTestBase { var sink: AnyCancellable? // Setup expectations - var onSubscribeInvoked: AsyncExpectation! - var receivedCompletionSuccess: AsyncExpectation! - var receivedCompletionFailure: AsyncExpectation! - + var onSubscribeInvoked: XCTestExpectation! + var receivedCompletionSuccess: XCTestExpectation! + var receivedCompletionFailure: XCTestExpectation! + // Subscription state expectations - var receivedStateValueConnecting: AsyncExpectation! - var receivedStateValueConnected: AsyncExpectation! - var receivedStateValueDisconnected: AsyncExpectation! + var receivedStateValueConnecting: XCTestExpectation! + var receivedStateValueConnected: XCTestExpectation! + var receivedStateValueDisconnected: XCTestExpectation! // Subscription item expectations - var receivedDataValueSuccess: AsyncExpectation! - var receivedDataValueError: AsyncExpectation! + var receivedDataValueSuccess: XCTestExpectation! + var receivedDataValueError: XCTestExpectation! // Handles to the subscription item and event handler used to make mock calls into the // subscription system @@ -68,14 +68,8 @@ class GraphQLSubscribeCombineTests: OperationTestBase { } func testHappyPath() async throws { - await receivedCompletionSuccess.setShouldTrigger(true) - await receivedCompletionFailure.setShouldTrigger(false) - await receivedStateValueConnecting.setShouldTrigger(true) - await receivedStateValueConnected.setShouldTrigger(true) - await receivedStateValueDisconnected.setShouldTrigger(true) - - await receivedDataValueSuccess.setShouldTrigger(true) - await receivedDataValueError.setShouldTrigger(false) + receivedCompletionFailure.isInverted = true + receivedDataValueError.isInverted = true let testJSON: JSONValue = ["foo": true] let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)! @@ -92,14 +86,9 @@ class GraphQLSubscribeCombineTests: OperationTestBase { } func testConnectionWithNoData() async throws { - await receivedCompletionSuccess.setShouldTrigger(true) - await receivedCompletionFailure.setShouldTrigger(false) - await receivedStateValueConnecting.setShouldTrigger(true) - await receivedStateValueConnected.setShouldTrigger(true) - await receivedStateValueDisconnected.setShouldTrigger(true) - - await receivedDataValueSuccess.setShouldTrigger(false) - await receivedDataValueError.setShouldTrigger(false) + receivedCompletionFailure.isInverted = true + receivedDataValueSuccess.isInverted = true + receivedDataValueError.isInverted = true try await subscribe() await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) @@ -112,14 +101,11 @@ class GraphQLSubscribeCombineTests: OperationTestBase { } func testConnectionError() async throws { - await receivedCompletionSuccess.setShouldTrigger(false) - await receivedCompletionFailure.setShouldTrigger(true) - await receivedStateValueConnecting.setShouldTrigger(true) - await receivedStateValueConnected.setShouldTrigger(false) - await receivedStateValueDisconnected.setShouldTrigger(false) - - await receivedDataValueSuccess.setShouldTrigger(false) - await receivedDataValueError.setShouldTrigger(false) + receivedCompletionSuccess.isInverted = true + receivedStateValueConnected.isInverted = true + receivedStateValueDisconnected.isInverted = true + receivedDataValueSuccess.isInverted = true + receivedDataValueError.isInverted = true try await subscribe() await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) @@ -132,14 +118,8 @@ class GraphQLSubscribeCombineTests: OperationTestBase { func testDecodingError() async throws { let testData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)! - await receivedCompletionSuccess.setShouldTrigger(true) - await receivedCompletionFailure.setShouldTrigger(false) - await receivedStateValueConnecting.setShouldTrigger(true) - await receivedStateValueConnected.setShouldTrigger(true) - await receivedStateValueDisconnected.setShouldTrigger(true) - - await receivedDataValueSuccess.setShouldTrigger(false) - await receivedDataValueError.setShouldTrigger(true) + receivedCompletionFailure.isInverted = true + receivedDataValueSuccess.isInverted = true try await subscribe() await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) @@ -155,15 +135,9 @@ class GraphQLSubscribeCombineTests: OperationTestBase { func testMultipleSuccessValues() async throws { let testJSON: JSONValue = ["foo": true] let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)! - await receivedCompletionSuccess.setShouldTrigger(true) - await receivedCompletionFailure.setShouldTrigger(false) - await receivedStateValueConnecting.setShouldTrigger(true) - await receivedStateValueConnected.setShouldTrigger(true) - await receivedStateValueDisconnected.setShouldTrigger(true) - - await receivedDataValueSuccess.setShouldTrigger(true) - await receivedDataValueSuccess.setExpectedFulfillmentCount(2) - await receivedDataValueError.setShouldTrigger(false) + receivedCompletionFailure.isInverted = true + receivedDataValueError.isInverted = true + receivedDataValueSuccess.expectedFulfillmentCount = 2 try await subscribe(expecting: testJSON) await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) @@ -180,15 +154,8 @@ class GraphQLSubscribeCombineTests: OperationTestBase { func testMixedSuccessAndErrorValues() async throws { let successfulTestData = #"{"data": {"foo": true}}"# .data(using: .utf8)! let invalidTestData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)! - await receivedCompletionSuccess.setShouldTrigger(true) - await receivedCompletionFailure.setShouldTrigger(false) - await receivedStateValueConnecting.setShouldTrigger(true) - await receivedStateValueConnected.setShouldTrigger(true) - await receivedStateValueDisconnected.setShouldTrigger(true) - - await receivedDataValueSuccess.setShouldTrigger(true) - await receivedDataValueSuccess.setExpectedFulfillmentCount(2) - await receivedDataValueError.setShouldTrigger(true) + receivedCompletionFailure.isInverted = true + receivedDataValueSuccess.expectedFulfillmentCount = 2 try await subscribe() await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) @@ -219,7 +186,7 @@ class GraphQLSubscribeCombineTests: OperationTestBase { self.subscriptionItem = item self.subscriptionEventHandler = eventHandler - Task { await self.onSubscribeInvoked.fulfill() } + self.onSubscribeInvoked.fulfill() return item } @@ -247,20 +214,20 @@ class GraphQLSubscribeCombineTests: OperationTestBase { sink = Amplify.Publisher.create(subscription).sink { completion in switch completion { case .failure: - Task { await self.receivedCompletionFailure.fulfill() } + self.receivedCompletionFailure.fulfill() case .finished: - Task { await self.receivedCompletionSuccess.fulfill() } + self.receivedCompletionSuccess.fulfill() } } receiveValue: { subscriptionEvent in switch subscriptionEvent { case .connection(let connectionState): switch connectionState { case .connecting: - Task { await self.receivedStateValueConnecting.fulfill() } + self.receivedStateValueConnecting.fulfill() case .connected: - Task { await self.receivedStateValueConnected.fulfill() } + self.receivedStateValueConnected.fulfill() case .disconnected: - Task { await self.receivedStateValueDisconnected.fulfill() } + self.receivedStateValueDisconnected.fulfill() } case .data(let result): switch result { @@ -268,9 +235,9 @@ class GraphQLSubscribeCombineTests: OperationTestBase { if let expectedValue = expectedValue { XCTAssertEqual(actualValue, expectedValue) } - Task { await self.receivedDataValueSuccess.fulfill() } + self.receivedDataValueSuccess.fulfill() case .failure: - Task { await self.receivedDataValueError.fulfill() } + self.receivedDataValueError.fulfill() } } } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTaskTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTaskTests.swift index f4c95cf003..9b03c7a748 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTaskTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTaskTests.swift @@ -17,18 +17,18 @@ import AppSyncRealTimeClient class GraphQLSubscribeTasksTests: OperationTestBase { // Setup expectations - var onSubscribeInvoked: AsyncExpectation! - var receivedCompletionSuccess: AsyncExpectation! - var receivedCompletionFailure: AsyncExpectation! - + var onSubscribeInvoked: XCTestExpectation! + var receivedCompletionSuccess: XCTestExpectation! + var receivedCompletionFailure: XCTestExpectation! + // Subscription state expectations - var receivedStateValueConnecting: AsyncExpectation! - var receivedStateValueConnected: AsyncExpectation! - var receivedStateValueDisconnected: AsyncExpectation! + var receivedStateValueConnecting: XCTestExpectation! + var receivedStateValueConnected: XCTestExpectation! + var receivedStateValueDisconnected: XCTestExpectation! // Subscription item expectations - var receivedDataValueSuccess: AsyncExpectation! - var receivedDataValueError: AsyncExpectation! + var receivedDataValueSuccess: XCTestExpectation! + var receivedDataValueError: XCTestExpectation! // Handles to the subscription item and event handler used to make mock calls into the // subscription system @@ -57,24 +57,23 @@ class GraphQLSubscribeTasksTests: OperationTestBase { } func waitForSubscriptionExpectations() async { - await fulfillment(of: [receivedCompletionSuccess, - receivedCompletionFailure, - receivedStateValueConnecting, - receivedStateValueConnected, - receivedStateValueDisconnected, - receivedDataValueSuccess, - receivedDataValueError], timeout: 0.05) + await fulfillment( + of: [ + receivedCompletionSuccess, + receivedCompletionFailure, + receivedStateValueConnecting, + receivedStateValueConnected, + receivedStateValueDisconnected, + receivedDataValueSuccess, + receivedDataValueError + ], + timeout: 0.05 + ) } func testHappyPath() async throws { - await receivedCompletionSuccess.setShouldTrigger(true) - await receivedCompletionFailure.setShouldTrigger(false) - await receivedStateValueConnecting.setShouldTrigger(true) - await receivedStateValueConnected.setShouldTrigger(true) - await receivedStateValueDisconnected.setShouldTrigger(true) - - await receivedDataValueSuccess.setShouldTrigger(true) - await receivedDataValueError.setShouldTrigger(false) + receivedCompletionFailure.isInverted = true + receivedDataValueError.isInverted = true let testJSON: JSONValue = ["foo": true] let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)! @@ -91,15 +90,10 @@ class GraphQLSubscribeTasksTests: OperationTestBase { } func testConnectionWithNoData() async throws { - await receivedCompletionSuccess.setShouldTrigger(true) - await receivedCompletionFailure.setShouldTrigger(false) - await receivedStateValueConnecting.setShouldTrigger(true) - await receivedStateValueConnected.setShouldTrigger(true) - await receivedStateValueDisconnected.setShouldTrigger(true) - - await receivedDataValueSuccess.setShouldTrigger(false) - await receivedDataValueError.setShouldTrigger(false) - + receivedCompletionFailure.isInverted = true + receivedDataValueSuccess.isInverted = true + receivedDataValueError.isInverted = true + try await subscribe() await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) @@ -111,14 +105,11 @@ class GraphQLSubscribeTasksTests: OperationTestBase { } func testConnectionErrorWithLimitExceeded() async throws { - await receivedCompletionSuccess.setShouldTrigger(false) - await receivedCompletionFailure.setShouldTrigger(true) - await receivedStateValueConnecting.setShouldTrigger(true) - await receivedStateValueConnected.setShouldTrigger(false) - await receivedStateValueDisconnected.setShouldTrigger(false) - - await receivedDataValueSuccess.setShouldTrigger(false) - await receivedDataValueError.setShouldTrigger(false) + receivedCompletionSuccess.isInverted = true + receivedStateValueConnected.isInverted = true + receivedStateValueDisconnected.isInverted = true + receivedDataValueSuccess.isInverted = true + receivedDataValueError.isInverted = true try await subscribe() await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) @@ -130,14 +121,11 @@ class GraphQLSubscribeTasksTests: OperationTestBase { } func testConnectionErrorWithSubscriptionError() async throws { - await receivedCompletionSuccess.setShouldTrigger(false) - await receivedCompletionFailure.setShouldTrigger(true) - await receivedStateValueConnecting.setShouldTrigger(true) - await receivedStateValueConnected.setShouldTrigger(false) - await receivedStateValueDisconnected.setShouldTrigger(false) - - await receivedDataValueSuccess.setShouldTrigger(false) - await receivedDataValueError.setShouldTrigger(false) + receivedCompletionSuccess.isInverted = true + receivedStateValueConnected.isInverted = true + receivedStateValueDisconnected.isInverted = true + receivedDataValueSuccess.isInverted = true + receivedDataValueError.isInverted = true try await subscribe() await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) @@ -149,14 +137,11 @@ class GraphQLSubscribeTasksTests: OperationTestBase { } func testConnectionErrorWithConnectionUnauthorizedError() async throws { - await receivedCompletionSuccess.setShouldTrigger(false) - await receivedCompletionFailure.setShouldTrigger(true) - await receivedStateValueConnecting.setShouldTrigger(true) - await receivedStateValueConnected.setShouldTrigger(false) - await receivedStateValueDisconnected.setShouldTrigger(false) - - await receivedDataValueSuccess.setShouldTrigger(false) - await receivedDataValueError.setShouldTrigger(false) + receivedCompletionSuccess.isInverted = true + receivedStateValueConnected.isInverted = true + receivedStateValueDisconnected.isInverted = true + receivedDataValueSuccess.isInverted = true + receivedDataValueError.isInverted = true try await subscribe() await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) @@ -168,14 +153,11 @@ class GraphQLSubscribeTasksTests: OperationTestBase { } func testConnectionErrorWithConnectionProviderConnectionError() async throws { - await receivedCompletionSuccess.setShouldTrigger(false) - await receivedCompletionFailure.setShouldTrigger(true) - await receivedStateValueConnecting.setShouldTrigger(true) - await receivedStateValueConnected.setShouldTrigger(false) - await receivedStateValueDisconnected.setShouldTrigger(false) - - await receivedDataValueSuccess.setShouldTrigger(false) - await receivedDataValueError.setShouldTrigger(false) + receivedCompletionSuccess.isInverted = true + receivedStateValueConnected.isInverted = true + receivedStateValueDisconnected.isInverted = true + receivedDataValueSuccess.isInverted = true + receivedDataValueError.isInverted = true try await subscribe() await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) @@ -188,14 +170,8 @@ class GraphQLSubscribeTasksTests: OperationTestBase { func testDecodingError() async throws { let testData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)! - await receivedCompletionSuccess.setShouldTrigger(true) - await receivedCompletionFailure.setShouldTrigger(false) - await receivedStateValueConnecting.setShouldTrigger(true) - await receivedStateValueConnected.setShouldTrigger(true) - await receivedStateValueDisconnected.setShouldTrigger(true) - - await receivedDataValueSuccess.setShouldTrigger(false) - await receivedDataValueError.setShouldTrigger(true) + receivedCompletionFailure.isInverted = true + receivedDataValueSuccess.isInverted = true try await subscribe() await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) @@ -211,15 +187,10 @@ class GraphQLSubscribeTasksTests: OperationTestBase { func testMultipleSuccessValues() async throws { let testJSON: JSONValue = ["foo": true] let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)! - await receivedCompletionSuccess.setShouldTrigger(true) - await receivedCompletionFailure.setShouldTrigger(false) - await receivedStateValueConnecting.setShouldTrigger(true) - await receivedStateValueConnected.setShouldTrigger(true) - await receivedStateValueDisconnected.setShouldTrigger(true) - await receivedDataValueSuccess.setShouldTrigger(true) - await receivedDataValueSuccess.setExpectedFulfillmentCount(2) - await receivedDataValueError.setShouldTrigger(false) + receivedCompletionFailure.isInverted = true + receivedDataValueError.isInverted = true + receivedDataValueSuccess.expectedFulfillmentCount = 2 try await subscribe(expecting: testJSON) await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) @@ -236,15 +207,9 @@ class GraphQLSubscribeTasksTests: OperationTestBase { func testMixedSuccessAndErrorValues() async throws { let successfulTestData = #"{"data": {"foo": true}}"# .data(using: .utf8)! let invalidTestData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)! - await receivedCompletionSuccess.setShouldTrigger(true) - await receivedCompletionFailure.setShouldTrigger(false) - await receivedStateValueConnecting.setShouldTrigger(true) - await receivedStateValueConnected.setShouldTrigger(true) - await receivedStateValueDisconnected.setShouldTrigger(true) - await receivedDataValueSuccess.setShouldTrigger(true) - await receivedDataValueSuccess.setExpectedFulfillmentCount(2) - await receivedDataValueError.setShouldTrigger(true) + receivedCompletionFailure.isInverted = true + receivedDataValueSuccess.expectedFulfillmentCount = 2 try await subscribe() await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) @@ -275,7 +240,7 @@ class GraphQLSubscribeTasksTests: OperationTestBase { self.subscriptionItem = item self.subscriptionEventHandler = eventHandler - Task { await self.onSubscribeInvoked.fulfill() } + self.onSubscribeInvoked.fulfill() return item } @@ -307,11 +272,11 @@ class GraphQLSubscribeTasksTests: OperationTestBase { case .connection(let connectionState): switch connectionState { case .connecting: - await self.receivedStateValueConnecting.fulfill() + self.receivedStateValueConnecting.fulfill() case .connected: - await self.receivedStateValueConnected.fulfill() + self.receivedStateValueConnected.fulfill() case .disconnected: - await self.receivedStateValueDisconnected.fulfill() + self.receivedStateValueDisconnected.fulfill() } case .data(let result): switch result { @@ -319,21 +284,21 @@ class GraphQLSubscribeTasksTests: OperationTestBase { if let expectedValue = expectedValue { XCTAssertEqual(actualValue, expectedValue) } - await self.receivedDataValueSuccess.fulfill() + self.receivedDataValueSuccess.fulfill() case .failure: - await self.receivedDataValueError.fulfill() + self.receivedDataValueError.fulfill() } } } - await self.receivedCompletionSuccess.fulfill() + self.receivedCompletionSuccess.fulfill() } catch { if let apiError = error as? APIError, let expectedError = expectedCompletionFailureError { XCTAssertEqual(apiError, expectedError) } - await self.receivedCompletionFailure.fulfill() + self.receivedCompletionFailure.fulfill() } } } diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTests.swift index 761ba434d5..5b5e70791e 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTests.swift @@ -73,7 +73,7 @@ class GraphQLSubscribeTests: OperationTestBase { receivedSubscriptionEventError.shouldTrigger = false subscribe(expecting: testJSON) - await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) + wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.connection(.connected), subscriptionItem) @@ -103,7 +103,7 @@ class GraphQLSubscribeTests: OperationTestBase { receivedSubscriptionEventError.shouldTrigger = false subscribe() - await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) + wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.connection(.connected), subscriptionItem) @@ -131,7 +131,7 @@ class GraphQLSubscribeTests: OperationTestBase { receivedSubscriptionEventError.shouldTrigger = false subscribe() - await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) + wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.failed("Error"), subscriptionItem) @@ -161,7 +161,7 @@ class GraphQLSubscribeTests: OperationTestBase { receivedSubscriptionEventError.shouldTrigger = true subscribe() - await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) + wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.connection(.connected), subscriptionItem) @@ -183,7 +183,7 @@ class GraphQLSubscribeTests: OperationTestBase { receivedSubscriptionEventError.shouldTrigger = false subscribe(expecting: testJSON) - await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) + wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.connection(.connected), subscriptionItem) @@ -206,7 +206,7 @@ class GraphQLSubscribeTests: OperationTestBase { receivedSubscriptionEventError.shouldTrigger = true subscribe() - await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) + wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.connection(.connected), subscriptionItem) diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Reachability/NetworkReachabilityNotifierTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Reachability/NetworkReachabilityNotifierTests.swift index 11605c1966..48f6886616 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Reachability/NetworkReachabilityNotifierTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Reachability/NetworkReachabilityNotifierTests.swift @@ -104,12 +104,12 @@ class NetworkReachabilityNotifierTests: XCTestCase { defaultValueExpect.fulfill() }) - await fulfillment(of: [defaultValueExpect], timeout: 1.0) + wait(for: [defaultValueExpect], timeout: 1.0) notifier = nil notification = Notification.init(name: .reachabilityChanged) NotificationCenter.default.post(notification) - await fulfillment(of: [completeExpect], timeout: 1.0) + wait(for: [completeExpect], timeout: 1.0) cancellable.cancel() } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyPasswordSRPTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyPasswordSRPTests.swift index 2a61b88576..e6a8e599bb 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyPasswordSRPTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyPasswordSRPTests.swift @@ -385,7 +385,8 @@ class VerifyPasswordSRPTests: XCTestCase { clientMetadata: [:]) let passwordVerifierCompletion = expectation( - description: "passwordVerifierCompletion") + description: "passwordVerifierCompletion" + ) let dispatcher = MockDispatcher { event in guard let event = event as? SignInEvent else { @@ -401,7 +402,7 @@ class VerifyPasswordSRPTests: XCTestCase { await action.execute(withDispatcher: dispatcher, environment: environment) await fulfillment( - of: [passwordVerifierError], + of: [passwordVerifierCompletion], timeout: 0.1 ) } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/EscapeHatchTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/EscapeHatchTests.swift index 407864dc9c..d385c628d8 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/EscapeHatchTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/EscapeHatchTests.swift @@ -61,7 +61,7 @@ class EscapeHatchTests: XCTestCase { case .userPoolAndIdentityPool: expectation.fulfill() } - await fulfillment(of: [expectation], timeout: 1) + wait(for: [expectation], timeout: 1) } /// Test escape hatch with valid config for only identity pool diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAuthCognitoPluginTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAuthCognitoPluginTests.swift index 22f68c66ed..064ccb693c 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAuthCognitoPluginTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAuthCognitoPluginTests.swift @@ -97,7 +97,7 @@ class AmplifyAuthCognitoPluginTests: XCTestCase { expectation.fulfill() } } - await fulfillment(of: [expectation], timeout: apiTimeout) + wait(for: [expectation], timeout: apiTimeout) case .confirmSignIn(let request, expectedOutput: let expectedOutput): validateAPI(expectedOutput: expectedOutput) { return try await plugin.confirmSignIn( @@ -127,6 +127,6 @@ class AmplifyAuthCognitoPluginTests: XCTestCase { expectation.fulfill() } } - await fulfillment(of: [expectation], timeout: apiTimeout) + wait(for: [expectation], timeout: apiTimeout) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/AWSDataStorePluginBaseBehaviorTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/AWSDataStorePluginBaseBehaviorTests.swift index 2f9eaf3c8e..19d92716ca 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/AWSDataStorePluginBaseBehaviorTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/AWSDataStorePluginBaseBehaviorTests.swift @@ -45,7 +45,7 @@ class AWSDataStorePluginBaseBehaviorTests: BaseDataStoreTests { dataStorePlugin.onReceiveValue(receiveValue: .modelSyncedEvent(modelSyncedEvent)) XCTAssertTrue(dispatchedModelSyncedEvent.get()) - await fulfillment(of: [modelSyncedReceivedFromHub], timeout: 1) + wait(for: [modelSyncedReceivedFromHub], timeout: 1) listener.cancel() } @@ -74,7 +74,7 @@ class AWSDataStorePluginBaseBehaviorTests: BaseDataStoreTests { } } - await fulfillment(of: [dataStoreStopSuccess], timeout: 1) + wait(for: [dataStoreStopSuccess], timeout: 1) XCTAssertFalse(dispatchedModelSyncedEvent.get()) } @@ -95,7 +95,7 @@ class AWSDataStorePluginBaseBehaviorTests: BaseDataStoreTests { dataStorePlugin.onReceiveValue(receiveValue: .syncQueriesReadyEvent) dataStorePlugin.onReceiveValue(receiveValue: .readyEvent) - await fulfillment(of: [syncQueriesReadyFromHub, readyReceivedFromHub], timeout: 1) + wait(for: [syncQueriesReadyFromHub, readyReceivedFromHub], timeout: 1) listener.cancel() } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/AWSDataStorePluginSubscribeBehaviorTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/AWSDataStorePluginSubscribeBehaviorTests.swift index b3a1b19347..61ebc3150f 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/AWSDataStorePluginSubscribeBehaviorTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/AWSDataStorePluginSubscribeBehaviorTests.swift @@ -33,7 +33,7 @@ class AWSDataStorePluginSubscribeBehaviorTests: BaseDataStoreTests { snapshotReceived.fulfill() } - await fulfillment(of: [snapshotReceived], timeout: 20) + wait(for: [snapshotReceived], timeout: 20) sink.cancel() } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/ListTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/ListTests.swift index 6dcd83dbd7..31bdb24e5c 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/ListTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/ListTests.swift @@ -49,7 +49,6 @@ class ListTests: BaseDataStoreTests { XCTFail("\(error)") } - await fulfillment(of: [expect], timeout: 1) } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterJsonTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterJsonTests.swift index 859e02de06..c1543d89d4 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterJsonTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterJsonTests.swift @@ -115,7 +115,7 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { expectation.fulfill() } } - await fulfillment(of: [expectation], timeout: 5) + wait(for: [expectation], timeout: 5) } /// - Given: a list a `Post` instance @@ -163,7 +163,7 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { } } - await fulfillment(of: [expectation], timeout: 5) + wait(for: [expectation], timeout: 5) } /// - Given: a list a `Post` instance @@ -224,7 +224,7 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { } } - await fulfillment(of: [expectation], timeout: 5) + wait(for: [expectation], timeout: 5) } /// - Given: a list a `Post` instance @@ -270,7 +270,7 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { } } - await fulfillment(of: [saveExpectation, deleteExpectation, queryExpectation], timeout: 2) + wait(for: [saveExpectation, deleteExpectation, queryExpectation], timeout: 2) } /// - Given: A Post instance @@ -330,7 +330,7 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { } } - await fulfillment(of: [expectation], timeout: 5) + wait(for: [expectation], timeout: 5) } /// - Given: A Post instance @@ -366,7 +366,7 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { } } - await fulfillment(of: [expectation], timeout: 5) + wait(for: [expectation], timeout: 5) } /// - Given: A Post instance @@ -418,7 +418,7 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { } } - await fulfillment(of: [expectation], timeout: 5) + wait(for: [expectation], timeout: 5) } func testInsertSinglePostThenDeleteItByPredicate() { @@ -461,7 +461,7 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { } } - await fulfillment(of: [saveExpectation, deleteExpectation, queryExpectation], timeout: 2) + wait(for: [saveExpectation, deleteExpectation, queryExpectation], timeout: 2) } func testInsertionOfManyItemsThenDeleteAllByPredicateConstant() { @@ -511,7 +511,7 @@ class SQLiteStorageEngineAdapterJsonTests: XCTestCase { } counter += 1 } - await fulfillment(of: [saveExpectation, deleteExpectation, queryExpectation], timeout: 5) + wait(for: [saveExpectation, deleteExpectation, queryExpectation], timeout: 5) } func checkIfPostIsDeleted(id: String) { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterTests.swift index 3bfa9a412d..16870f2ed4 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/SQLiteStorageEngineAdapterTests.swift @@ -54,7 +54,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } } - await fulfillment(of: [expectation], timeout: 5) + wait(for: [expectation], timeout: 5) } /// - Given: a list a `Post` instance @@ -93,7 +93,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } } - await fulfillment(of: [expectation], timeout: 5) + wait(for: [expectation], timeout: 5) } /// - Given: a list a `Post` instance @@ -134,7 +134,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } } - await fulfillment(of: [expectation], timeout: 5) + wait(for: [expectation], timeout: 5) } /// - Given: a list a `Post` instance @@ -184,7 +184,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } } - await fulfillment(of: [expectation], timeout: 5) + wait(for: [expectation], timeout: 5) } /// - Given: A Post instance @@ -234,7 +234,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } } - await fulfillment(of: [expectation], timeout: 5) + wait(for: [expectation], timeout: 5) } /// - Given: A Post instance @@ -283,7 +283,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } } - await fulfillment(of: [expectation], timeout: 5) + wait(for: [expectation], timeout: 5) } /// - Given: A Post instance @@ -311,7 +311,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } } - await fulfillment(of: [expectation], timeout: 5) + wait(for: [expectation], timeout: 5) } /// - Given: A Post instance @@ -348,7 +348,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } } - await fulfillment(of: [expectation], timeout: 5) + wait(for: [expectation], timeout: 5) } /// - Given: a list a `Post` instance @@ -384,7 +384,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } } - await fulfillment(of: [saveExpectation, deleteExpectation, queryExpectation], timeout: 2) + wait(for: [saveExpectation, deleteExpectation, queryExpectation], timeout: 2) } func testInsertPostAndThenDeleteByIdWithPredicate() { @@ -419,7 +419,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } } - await fulfillment(of: [saveExpectation, deleteExpectation, queryExpectation], timeout: 2) + wait(for: [saveExpectation, deleteExpectation, queryExpectation], timeout: 2) } func testInsertPostAndThenDeleteByIdWithPredicateThatDoesNotMatch() { @@ -454,7 +454,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } } - await fulfillment(of: [saveExpectation, deleteCompleteExpectation, queryExpectation], timeout: 2) + wait(for: [saveExpectation, deleteCompleteExpectation, queryExpectation], timeout: 2) } func testInsertSinglePostThenDeleteItByPredicate() { @@ -486,7 +486,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } } - await fulfillment(of: [saveExpectation, deleteExpectation, queryExpectation], timeout: 2) + wait(for: [saveExpectation, deleteExpectation, queryExpectation], timeout: 2) } func testInsertionOfManyItemsThenDeleteAllByPredicateConstant() { @@ -531,7 +531,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } counter += 1 } - await fulfillment(of: [saveExpectation, deleteExpectation, queryExpectation], timeout: 5) + wait(for: [saveExpectation, deleteExpectation, queryExpectation], timeout: 5) } func checkIfPostIsDeleted(id: String) { @@ -692,7 +692,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { case .failure(let error): XCTFail("\(error)") } } - await fulfillment(of: [querySuccess], timeout: 1) + wait(for: [querySuccess], timeout: 1) } func testQueryMutationSyncMetadataForModelIds() { @@ -716,7 +716,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } saveMetadata1.fulfill() } - await fulfillment(of: [saveMetadata1], timeout: 1) + wait(for: [saveMetadata1], timeout: 1) let saveMetadata2 = expectation(description: "save metadata2 success") storageAdapter.save(metadata2) { result in @@ -726,7 +726,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { } saveMetadata2.fulfill() } - await fulfillment(of: [saveMetadata2], timeout: 1) + wait(for: [saveMetadata2], timeout: 1) let querySuccess = expectation(description: "query for metadata success") var modelIds = [metadata1.modelId] @@ -740,7 +740,7 @@ class SQLiteStorageEngineAdapterTests: BaseDataStoreTests { XCTFail("\(error)") } - await fulfillment(of: [querySuccess], timeout: 1) + wait(for: [querySuccess], timeout: 1) } func testShouldIgnoreConstraintViolationError() { @@ -796,7 +796,7 @@ extension SQLiteStorageEngineAdapterTests { rowSaved.fulfill() } - await fulfillment(of: [transactionSaved, groupSaved, rowSaved], timeout: 1) + wait(for: [transactionSaved, groupSaved, rowSaved], timeout: 1) } func testQueryWithReservedWords() { @@ -829,6 +829,6 @@ extension SQLiteStorageEngineAdapterTests { } rowQueried.fulfill() } - await fulfillment(of: [transactionQueried, groupQueried, rowQueried], timeout: 1) + wait(for: [transactionQueried, groupQueried, rowQueried], timeout: 1) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StateMachineTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StateMachineTests.swift index c2118780b9..3f23198981 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StateMachineTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StateMachineTests.swift @@ -106,14 +106,16 @@ class StateMachineTests: XCTestCase { } } - await fulfillment(of: [ - receivedOneOnSubscribe, - receivedTwoAfterSubscribe, - receivedThreeAfterSubscribe, - receivedOneAfterSubscribe + wait( + for: [ + receivedOneOnSubscribe, + receivedTwoAfterSubscribe, + receivedThreeAfterSubscribe, + receivedOneAfterSubscribe ], - timeout: 1.0, - enforceOrder: true) + timeout: 1.0, + enforceOrder: true + ) listener.cancel() } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StorageAdapterMutationSyncTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StorageAdapterMutationSyncTests.swift index 8abfde868f..f33024288b 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StorageAdapterMutationSyncTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/StorageAdapterMutationSyncTests.swift @@ -49,7 +49,7 @@ class StorageAdapterMutationSyncTests: BaseDataStoreTests { XCTFail(error.localizedDescription) expect.fulfill() } - await fulfillment(of: [expect], timeout: 5) + wait(for: [expect], timeout: 5) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTestBase.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTestBase.swift index e8427be36d..e737a83d20 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/MutationSyncMetadataMigrationTestBase.swift @@ -53,7 +53,7 @@ class MutationSyncMetadataMigrationTestBase: XCTestCase { case .failure(let error): XCTFail("\(error.errorDescription)") } } - await fulfillment(of: [saveSuccess], timeout: 1) + wait(for: [saveSuccess], timeout: 1) } func saveMutationSyncMetadata(_ metadata: MutationSyncMetadata) { @@ -64,7 +64,7 @@ class MutationSyncMetadataMigrationTestBase: XCTestCase { case .failure(let error): XCTFail("\(error.errorDescription)") } } - await fulfillment(of: [saveMetadataSuccess], timeout: 1) + wait(for: [saveMetadataSuccess], timeout: 1) } func queryMutationSyncMetadata() -> [MutationSyncMetadata]? { @@ -78,7 +78,7 @@ class MutationSyncMetadataMigrationTestBase: XCTestCase { case .failure(let error): XCTFail("\(error.errorDescription)") } } - await fulfillment(of: [firstQueryModelSyncMetadata], timeout: 1) + wait(for: [firstQueryModelSyncMetadata], timeout: 1) return result } @@ -93,7 +93,7 @@ class MutationSyncMetadataMigrationTestBase: XCTestCase { case .failure(let error): XCTFail("\(error.errorDescription)") } } - await fulfillment(of: [queryModelSyncMetadata], timeout: 1) + wait(for: [queryModelSyncMetadata], timeout: 1) return result } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationValidationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationValidationTests.swift index e891d0eda3..d259ddf91d 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationValidationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Migration/SQLiteMutationSyncMetadataMigrationValidationTests.swift @@ -42,7 +42,7 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi XCTAssertEqual(message, "no such table: MutationSyncMetadata") shouldCatchFailure.fulfill() } - await fulfillment(of: [shouldCatchFailure], timeout: 1) + wait(for: [shouldCatchFailure], timeout: 1) } /// Set up MutationSyncMetadata records where the id is in the incorrect format. Check that it needs migration. @@ -90,7 +90,7 @@ class SQLiteMutationSyncMetadataMigrationValidationTests: MutationSyncMetadataMi XCTAssertEqual(message, "no such table: Dish") shouldCatchFailure.fulfill() } - await fulfillment(of: [shouldCatchFailure], timeout: 1) + wait(for: [shouldCatchFailure], timeout: 1) } func testSelectDuplicateIdAcrossModelsStatement() throws { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/CascadeDeleteOperationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/CascadeDeleteOperationTests.swift index 241c08eefb..dd3a7dd4ea 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/CascadeDeleteOperationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/CascadeDeleteOperationTests.swift @@ -362,7 +362,7 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.start() - await fulfillment(of: [receivedMutationEvent, expectedFailures, expectedSuccess], timeout: 1) + await fulfillment(of: [receivedMutationEvent, expectedFailures, expectedSuccess, completed], timeout: 1) guard case .success(let queriedRestaurants) = await queryModelSynchronous(modelType: Restaurant.self, predicate: predicate) else { XCTFail("Failed to query") @@ -423,7 +423,7 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } } operation.start() - await fulfillment(of: [receivedMutationEvent, expectedFailures, expectedSuccess], timeout: 1) + await fulfillment(of: [receivedMutationEvent, expectedFailures, expectedSuccess, completed], timeout: 1) guard case .success(let queriedModels) = await queryModelSynchronous(modelType: ModelCompositePk.self, predicate: predicate) else { XCTFail("Failed to query") @@ -730,7 +730,7 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.syncIfNeededAndFinish(result) - await fulfillment(of: [receivedMutationEvent, expectedFailures, expectedSuccess], timeout: 1) + await fulfillment(of: [receivedMutationEvent, expectedFailures, expectedSuccess, completed], timeout: 1) XCTAssertEqual(submittedEvents.count, 2) // The delete mutations should be synced in reverse order (children to parent) @@ -799,7 +799,7 @@ class CascadeDeleteOperationTests: StorageEngineTestsBase { } operation.syncIfNeededAndFinish(result) - await fulfillment(of: [receivedMutationEvent, expectedFailures, expectedSuccess], timeout: 1) + await fulfillment(of: [receivedMutationEvent, expectedFailures, expectedSuccess, completed], timeout: 1) XCTAssertEqual(submittedEvents.count, 3) // The delete mutations should be synced in reverse order (children to parent) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEnginePublisherTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEnginePublisherTests.swift index 8b9af5bdfe..3fabbb069d 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEnginePublisherTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEnginePublisherTests.swift @@ -84,11 +84,15 @@ class StorageEnginePublisherTests: StorageEngineTestsBase { storageEngine.onReceive(receiveValue: .syncStarted) storageEngine.onReceive(receiveValue: .cleanedUp) storageEngine.onReceive(receiveValue: .cleanedUpForTermination) - await fulfillment(of: [receivedMutationEvent, - receivedModelSyncedEvent, - receivedSyncQueriesReadyEvent, - receivedReadyEvent], - timeout: 1) + wait( + for: [ + receivedMutationEvent, + receivedModelSyncedEvent, + receivedSyncQueriesReadyEvent, + receivedReadyEvent + ], + timeout: 1 + ) sink.cancel() } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsBase.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsBase.swift index 97e0bde6da..bdd3ef26ac 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsBase.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsBase.swift @@ -47,7 +47,7 @@ class StorageEngineTestsBase: XCTestCase { result = sResult saveFinished.fulfill() } - await waitForExpectations(timeout: defaultTimeout) + await fulfillment(of: [saveFinished], timeout: defaultTimeout) guard let saveResult = result else { return .failure(causedBy: "Save operation timed out") } @@ -89,7 +89,7 @@ class StorageEngineTestsBase: XCTestCase { queryFinished.fulfill() } - await fulfillment(of: [queryFinished], timeout: defaultTimeout) + wait(for: [queryFinished], timeout: defaultTimeout) guard let queryResult = result else { return .failure(causedBy: "Query operation timed out") } @@ -105,7 +105,7 @@ class StorageEngineTestsBase: XCTestCase { queryFinished.fulfill() } - await waitForExpectations(timeout: defaultTimeout) + await fulfillment(of: [queryFinished], timeout: defaultTimeout) guard let queryResult = result else { return .failure(causedBy: "Query operation timed out") } @@ -174,7 +174,7 @@ class StorageEngineTestsBase: XCTestCase { deleteFinished.fulfill() }) - await fulfillment(of: [deleteFinished], timeout: timeout) + wait(for: [deleteFinished], timeout: timeout) guard let deleteResult = result else { return .failure(causedBy: "Delete operation timed out") } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsDelete.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsDelete.swift index 7c097de16b..810db0030f 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsDelete.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsDelete.swift @@ -169,6 +169,6 @@ class StorageEngineTestsDelete: StorageEngineTestsBase { XCTFail("Failed to delete projectA") return } - await fulfillment(of: [mutationEventOnProject], timeout: defaultTimeout) + wait(for: [mutationEventOnProject], timeout: defaultTimeout) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasMany.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasMany.swift index 3340bd32b5..daa980866b 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasMany.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasMany.swift @@ -111,7 +111,7 @@ class StorageEngineTestsHasMany: StorageEngineTestsBase { XCTFail("Failed to delete restaurant") return } - await fulfillment(of: [receivedMutationEvent], timeout: defaultTimeout) + wait(for: [receivedMutationEvent], timeout: defaultTimeout) } /* @@ -204,7 +204,7 @@ class StorageEngineTestsHasMany: StorageEngineTestsBase { XCTFail("Failed to delete restaurant") return } - await fulfillment(of: [receivedMutationEvent], timeout: 100) + wait(for: [receivedMutationEvent], timeout: 100) // let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime // print("Time elapsed time to delete: \(timeElapsed) s.") } @@ -245,7 +245,7 @@ class StorageEngineTestsHasMany: StorageEngineTestsBase { XCTFail("Deleting should have failed due to our mock") return } - await fulfillment(of: [receivedMutationEvent, expectedFailures, expectedSuccess], timeout: defaultTimeout) + wait(for: [receivedMutationEvent, expectedFailures, expectedSuccess], timeout: defaultTimeout) XCTAssertEqual(error.errorDescription, "mockError") } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasOne.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasOne.swift index 2467ac1a5d..6adf34fd54 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasOne.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsHasOne.swift @@ -56,7 +56,7 @@ class StorageEngineTestsHasOne: StorageEngineTestsBase { result = sResult saveFinished.fulfill() } - await fulfillment(of: [saveFinished], timeout: defaultTimeout) + wait(for: [saveFinished], timeout: defaultTimeout) guard result != nil else { XCTFail("Save operation timed out") @@ -110,6 +110,6 @@ class StorageEngineTestsHasOne: StorageEngineTestsBase { XCTFail("Failed to delete projectA") return } - await fulfillment(of: [mutationEventOnProject], timeout: defaultTimeout) + wait(for: [mutationEventOnProject], timeout: defaultTimeout) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsManyToMany.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsManyToMany.swift index 8cacc8a7de..d7e04398d4 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsManyToMany.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsManyToMany.swift @@ -103,7 +103,7 @@ class StorageEngineTestsManyToMany: StorageEngineTestsBase { XCTFail("Failed to delete post1") return } - await fulfillment(of: [mutationEvents], timeout: defaultTimeout) + wait(for: [mutationEvents], timeout: defaultTimeout) } func testDeleteUserAndPostEditor() { @@ -160,6 +160,6 @@ class StorageEngineTestsManyToMany: StorageEngineTestsBase { XCTFail("Failed to delete post1") return } - await fulfillment(of: [mutationEvents], timeout: defaultTimeout) + wait(for: [mutationEvents], timeout: defaultTimeout) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsSQLiteIndex.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsSQLiteIndex.swift index 15f209d3c6..dcb8fa1c88 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsSQLiteIndex.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Storage/StorageEngineTestsSQLiteIndex.swift @@ -322,7 +322,7 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { result = sResult saveFinished.fulfill() } - await fulfillment(of: [saveFinished], timeout: defaultTimeout) + wait(for: [saveFinished], timeout: defaultTimeout) guard let saveResult = result else { return .failure(causedBy: "Save operation timed out") } @@ -340,7 +340,7 @@ class StorageEngineTestsSQLiteIndex: StorageEngineTestsBase { queryFinished.fulfill() } - await fulfillment(of: [queryFinished], timeout: defaultTimeout) + wait(for: [queryFinished], timeout: defaultTimeout) guard let queryResult = result else { return .failure(causedBy: "Query operation timed out") } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveQueryTaskRunnerTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveQueryTaskRunnerTests.swift index aed205c51a..a172663280 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveQueryTaskRunnerTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Subscribe/ObserveQueryTaskRunnerTests.swift @@ -54,10 +54,10 @@ class ObserveQueryTaskRunnerTests: XCTestCase { querySnapshots.append(querySnapshot) if querySnapshots.count == 1 { XCTAssertEqual(querySnapshot.items.count, 0) - await firstSnapshot.fulfill() + firstSnapshot.fulfill() } else if querySnapshots.count == 2 { XCTAssertEqual(querySnapshot.items.count, 1) - await secondSnapshot.fulfill() + secondSnapshot.fulfill() } } } catch { @@ -85,7 +85,9 @@ class ObserveQueryTaskRunnerTests: XCTestCase { func testGenerateSnapshotOnObserveQueryWhenModelSynced() async throws { let firstSnapshot = expectation(description: "first query snapshots") let secondSnapshot = expectation(description: "second query snapshots") - let thirdSnapshot = expectation(description: "third query snapshot", isInverted: true) + let thirdSnapshot = expectation(description: "third query snapshot") + thirdSnapshot.isInverted = true + let dispatchedModelSyncedEvent = AtomicValue(initialValue: false) let taskRunner = ObserveQueryTaskRunner( modelType: Post.self, @@ -106,14 +108,14 @@ class ObserveQueryTaskRunnerTests: XCTestCase { if querySnapshots.count == 1 { XCTAssertEqual(querySnapshot.items.count, 0) XCTAssertEqual(querySnapshot.isSynced, false) - await firstSnapshot.fulfill() + firstSnapshot.fulfill() } else if querySnapshots.count == 2 { XCTAssertEqual(querySnapshot.items.count, 0) XCTAssertEqual(querySnapshot.isSynced, true) - await secondSnapshot.fulfill() + secondSnapshot.fulfill() } else if querySnapshots.count == 3 { XCTFail("Should not receive third snapshot for a Model change") - await thirdSnapshot.fulfill() + thirdSnapshot.fulfill() } } } catch { @@ -172,7 +174,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { querySnapshots.append(querySnapshot) if querySnapshots.count == 1 { XCTAssertEqual(querySnapshot.items.count, 2) - await firstSnapshot.fulfill() + firstSnapshot.fulfill() } } @@ -213,10 +215,10 @@ class ObserveQueryTaskRunnerTests: XCTestCase { querySnapshots.append(querySnapshot) if querySnapshots.count == 1 { XCTAssertEqual(querySnapshot.items.count, 0) - await firstSnapshot.fulfill() + firstSnapshot.fulfill() } else if querySnapshots.count == 2 { XCTAssertEqual(querySnapshot.items.count, 3) - await secondSnapshot.fulfill() + secondSnapshot.fulfill() } } } catch { @@ -268,11 +270,11 @@ class ObserveQueryTaskRunnerTests: XCTestCase { for try await querySnapshot in snapshots { querySnapshots.append(querySnapshot) if querySnapshots.count == 1 { - await firstSnapshot.fulfill() + firstSnapshot.fulfill() } else if querySnapshots.count == 2 { - await secondSnapshot.fulfill() + secondSnapshot.fulfill() } else if querySnapshots.count == 3 { - await thirdSnapshot.fulfill() + thirdSnapshot.fulfill() } } @@ -280,7 +282,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { XCTAssertTrue(querySnapshots[0].items.count <= querySnapshots[1].items.count) XCTAssertTrue(querySnapshots[1].items.count <= querySnapshots[2].items.count) XCTAssertTrue(querySnapshots[2].items.count <= 1_100) - await validateSnapshotsComplete.fulfill() + validateSnapshotsComplete.fulfill() } catch { XCTFail("Failed with error \(error)") } @@ -308,7 +310,9 @@ class ObserveQueryTaskRunnerTests: XCTestCase { /// func testSuccessfulSubscriptionCancel() async throws { let firstSnapshot = expectation(description: "first query snapshot") - let secondSnapshot = expectation(description: "second query snapshot", isInverted: true) + let secondSnapshot = expectation(description: "second query snapshot") + secondSnapshot.isInverted = true + let taskRunner = ObserveQueryTaskRunner( modelType: Post.self, modelSchema: Post.schema, @@ -326,10 +330,10 @@ class ObserveQueryTaskRunnerTests: XCTestCase { for try await querySnapshot in snapshots { querySnapshots.append(querySnapshot) if querySnapshots.count == 1 { - await firstSnapshot.fulfill() + firstSnapshot.fulfill() } else if querySnapshots.count == 2 { XCTFail("Should not receive second snapshot after cancelling") - await secondSnapshot.fulfill() + secondSnapshot.fulfill() } } } catch { @@ -354,7 +358,9 @@ class ObserveQueryTaskRunnerTests: XCTestCase { /// func testSuccessfulSequenceCancel() async throws { let firstSnapshot = expectation(description: "first query snapshot") - let secondSnapshot = expectation(description: "second query snapshot", isInverted: true) + let secondSnapshot = expectation(description: "second query snapshot") + secondSnapshot.isInverted = true + let completedEvent = expectation(description: "should have completed") let taskRunner = ObserveQueryTaskRunner( modelType: Post.self, @@ -373,13 +379,13 @@ class ObserveQueryTaskRunnerTests: XCTestCase { for try await querySnapshot in snapshots { querySnapshots.append(querySnapshot) if querySnapshots.count == 1 { - await firstSnapshot.fulfill() + firstSnapshot.fulfill() } else if querySnapshots.count == 2 { XCTFail("Should not receive second snapshot after cancelling") - await secondSnapshot.fulfill() + secondSnapshot.fulfill() } } - await completedEvent.fulfill() + completedEvent.fulfill() } catch { XCTFail("Failed with error \(error)") } @@ -413,9 +419,9 @@ class ObserveQueryTaskRunnerTests: XCTestCase { for try await querySnapshot in snapshots { querySnapshots.append(querySnapshot) if querySnapshots.count == 1 { - await firstSnapshot.fulfill() + firstSnapshot.fulfill() } else if querySnapshots.count == 2 { - await secondSnapshot.fulfill() + secondSnapshot.fulfill() } } } catch { @@ -439,7 +445,9 @@ class ObserveQueryTaskRunnerTests: XCTestCase { func testObserveQueryStaredShouldNotStartAgain() async { let firstSnapshot = expectation(description: "first query snapshot") let secondSnapshot = expectation(description: "second query snapshot") - let thirdSnapshot = expectation(description: "third query snapshot", isInverted: true) + let thirdSnapshot = expectation(description: "third query snapshot") + thirdSnapshot.isInverted = true + let taskRunner = ObserveQueryTaskRunner( modelType: Post.self, modelSchema: Post.schema, @@ -457,11 +465,11 @@ class ObserveQueryTaskRunnerTests: XCTestCase { for try await querySnapshot in snapshots { querySnapshots.append(querySnapshot) if querySnapshots.count == 1 { - await firstSnapshot.fulfill() + firstSnapshot.fulfill() } else if querySnapshots.count == 2 { - await secondSnapshot.fulfill() + secondSnapshot.fulfill() } else if querySnapshots.count == 3 { - await thirdSnapshot.fulfill() + thirdSnapshot.fulfill() } } } catch { @@ -480,7 +488,8 @@ class ObserveQueryTaskRunnerTests: XCTestCase { /// ObserveQuery operation entry points are `resetState`, `startObserveQuery`, and `onItemChanges(mutationEvents)`. /// Ensure concurrent random sequences of these API calls do not cause issues such as data race. func testConcurrent() async { - let completeReceived = expectation(description: "complete received", isInverted: true) + let completeReceived = expectation(description: "complete received") + completeReceived.isInverted = true let taskRunner = ObserveQueryTaskRunner( modelType: Post.self, modelSchema: Post.schema, @@ -502,7 +511,7 @@ class ObserveQueryTaskRunnerTests: XCTestCase { do { for try await _ in snapshots { } - await completeReceived.fulfill() + completeReceived.fulfill() } catch { XCTFail("Failed with error \(error)") } @@ -560,24 +569,24 @@ class ObserveQueryTaskRunnerTests: XCTestCase { if querySnapshots.count == 1 { // First snapshot is empty from the initial query XCTAssertEqual(querySnapshot.items.count, 0) - await firstSnapshot.fulfill() + firstSnapshot.fulfill() } else if querySnapshots.count == 2 { // Second snapshot contains `post` since it matches the predicate XCTAssertEqual(querySnapshot.items.count, 1) XCTAssertEqual(querySnapshot.items[0].id, "1") - await secondSnapshot.fulfill() + secondSnapshot.fulfill() } else if querySnapshots.count == 3 { // Third snapshot contains both posts since they both match the predicate XCTAssertEqual(querySnapshot.items.count, 2) XCTAssertEqual(querySnapshot.items[0].id, "1") XCTAssertEqual(querySnapshot.items[1].id, "2") - await thirdSnapshot.fulfill() + thirdSnapshot.fulfill() } else if querySnapshots.count == 4 { // Fourth snapshot no longer has the post2 since it was updated to not match the predicate // and deleted at the same time. XCTAssertEqual(querySnapshot.items.count, 1) XCTAssertEqual(querySnapshot.items[0].id, "1") - await fourthSnapshot.fulfill() + fourthSnapshot.fulfill() } } } catch { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationTests.swift index e1e595ab58..405bb0f18b 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOperationTests.swift @@ -187,7 +187,7 @@ class InitialSyncOperationTests: XCTestCase { operation.main() - await fulfillment(of: [syncCompletionReceived, finishedReceived], timeout: 1.0) + wait(for: [syncCompletionReceived, finishedReceived], timeout: 1.0) sink.cancel() } @@ -492,7 +492,7 @@ class InitialSyncOperationTests: XCTestCase { syncMetadataSaved.fulfill() } } - await fulfillment(of: [syncMetadataSaved], timeout: 1.0) + wait(for: [syncMetadataSaved], timeout: 1.0) let apiWasQueried = expectation(description: "API was queried for a PaginatedList of AnyModel") let responder = QueryRequestListenerResponder> { request, listener in @@ -563,7 +563,7 @@ class InitialSyncOperationTests: XCTestCase { syncMetadataSaved.fulfill() } } - await fulfillment(of: [syncMetadataSaved], timeout: 1.0) + wait(for: [syncMetadataSaved], timeout: 1.0) let apiWasQueried = expectation(description: "API was queried for a PaginatedList of AnyModel") let responder = QueryRequestListenerResponder> { request, listener in diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOrchestratorTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOrchestratorTests.swift index 07ea9b3984..6d85a46cf6 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOrchestratorTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/InitialSyncOrchestratorTests.swift @@ -97,7 +97,16 @@ class InitialSyncOrchestratorTests: XCTestCase { syncCallbackReceived.fulfill() } - await waitForExpectations(timeout: 1) + await fulfillment( + of: [ + syncCallbackReceived, + syncQueriesStartedReceived, + syncStartedReceived, + finishedReceived, + completionFinishedReceived + ], + timeout: 1 + ) XCTAssertEqual(orchestrator.syncOperationQueue.maxConcurrentOperationCount, 1) Amplify.Hub.removeListener(hubListener) sink.cancel() @@ -196,7 +205,16 @@ class InitialSyncOrchestratorTests: XCTestCase { syncCallbackReceived.fulfill() } - await waitForExpectations(timeout: 1) + await fulfillment( + of: [ + syncCallbackReceived, + syncQueriesStartedReceived, + syncStartedReceived, + finishedReceived, + failureCompletionReceived + ], + timeout: 1 + ) XCTAssertEqual(orchestrator.syncOperationQueue.maxConcurrentOperationCount, 1) Amplify.Hub.removeListener(hubListener) sink.cancel() diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ReadyEventEmitterTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ReadyEventEmitterTests.swift index 4c8d0c4b20..9d105456e1 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ReadyEventEmitterTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/InitialSync/ReadyEventEmitterTests.swift @@ -43,7 +43,7 @@ class ReadyEventEmitterTests: XCTestCase { let syncQueriesReadyEventPayload = HubPayload(eventName: HubPayload.EventName.DataStore.syncQueriesReady) Amplify.Hub.dispatch(to: .dataStore, payload: syncQueriesReadyEventPayload) - await fulfillment(of: [readyReceived], timeout: 1) + wait(for: [readyReceived], timeout: 1) readyEventSink?.cancel() } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionWithJSONModelTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionWithJSONModelTests.swift index 522360f5f5..38284d7204 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionWithJSONModelTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/LocalSubscriptionWithJSONModelTests.swift @@ -127,7 +127,7 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { let model = DynamicModel(values: post) let postSchema = ModelRegistry.modelSchema(from: "Post")! dataStorePlugin.save(model, modelSchema: postSchema) { _ in } - await fulfillment(of: [receivedMutationEvent], timeout: 1.0) + wait(for: [receivedMutationEvent], timeout: 1.0) subscription.cancel() } @@ -189,7 +189,7 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { } } - await fulfillment(of: [receivedPostMutationEvent, receivedCommentMutationEvent], timeout: 3.0) + wait(for: [receivedPostMutationEvent, receivedCommentMutationEvent], timeout: 3.0) subscription.cancel() } @@ -225,7 +225,7 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { let model = DynamicModel(values: post) let postSchema = ModelRegistry.modelSchema(from: "Post")! dataStorePlugin.save(model, modelSchema: postSchema) { _ in } - await fulfillment(of: [receivedMutationEvent], timeout: 1.0) + wait(for: [receivedMutationEvent], timeout: 1.0) subscription.cancel() } @@ -250,7 +250,7 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { saveCompleted.fulfill() } - await fulfillment(of: [saveCompleted], timeout: 5.0) + wait(for: [saveCompleted], timeout: 5.0) let newContent = "Updated content as of \(Date())" var newModel = model @@ -275,7 +275,7 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { dataStorePlugin.save(newModel, modelSchema: postSchema) { _ in } - await fulfillment(of: [receivedMutationEvent], timeout: 1.0) + wait(for: [receivedMutationEvent], timeout: 1.0) subscription.cancel() } @@ -313,7 +313,7 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { dataStorePlugin.save(model, modelSchema: postSchema) { _ in } dataStorePlugin.delete(model, modelSchema: postSchema) { _ in } - await fulfillment(of: [receivedMutationEvent], timeout: 1.0) + wait(for: [receivedMutationEvent], timeout: 1.0) subscription.cancel() } @@ -359,7 +359,7 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { savedPost.fulfill() } } - await fulfillment(of: [savedPost], timeout: 1.0) + wait(for: [savedPost], timeout: 1.0) let commentContent = "some content" let comment = ["content": .string(commentContent), @@ -377,7 +377,7 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { savedComment.fulfill() } } - await fulfillment(of: [savedComment], timeout: 1.0) + wait(for: [savedComment], timeout: 1.0) let queryCommentSuccess = expectation(description: "querying for comment should exist") dataStorePlugin.query(DynamicModel.self, @@ -391,7 +391,7 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { XCTFail("\(error)") } } - await fulfillment(of: [queryCommentSuccess], timeout: 10.0) + wait(for: [queryCommentSuccess], timeout: 10.0) let deletePostSuccess = expectation(description: "deleted post successfully") dataStorePlugin.delete(model, modelSchema: postSchema) { result in @@ -402,7 +402,7 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { XCTFail("\(error)") } } - await fulfillment(of: [receivedPostMutationEvent, deletePostSuccess], timeout: 10.0) + wait(for: [receivedPostMutationEvent, deletePostSuccess], timeout: 10.0) subscriptionPost.cancel() let queryCommentEmpty = expectation(description: "querying for comment should be empty") @@ -417,6 +417,6 @@ class LocalSubscriptionWithJSONModelTests: XCTestCase { XCTFail("\(error)") } } - await fulfillment(of: [queryCommentEmpty], timeout: 10.0) + wait(for: [queryCommentEmpty], timeout: 10.0) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationEventClearStateTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationEventClearStateTests.swift index 4d8b57ed76..56860bea60 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationEventClearStateTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationEventClearStateTests.swift @@ -49,8 +49,13 @@ class MutationEventClearStateTests: XCTestCase { mutationEventClearState.clearStateOutgoingMutations { completionExpectation.fulfill() } - await fulfillment(of: [queryExpectation, - saveExpectation, - completionExpectation], timeout: 1.0) + wait( + for: [ + queryExpectation, + saveExpectation, + completionExpectation + ], + timeout: 1.0 + ) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationIngesterConflictResolutionTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationIngesterConflictResolutionTests.swift index 3f1201a368..780d80425b 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationIngesterConflictResolutionTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/MutationIngesterConflictResolutionTests.swift @@ -73,7 +73,7 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { mutationEventVerified.fulfill() } - await waitForExpectations(timeout: 1) + await fulfillment(of: [mutationEventVerified], timeout: 1) } /// - Given: An existing MutationEvent of type .create @@ -161,7 +161,7 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { mutationEventVerified.fulfill() } - await waitForExpectations(timeout: 1.0) + await fulfillment(of: [mutationEventVerified], timeout: 1.0) } // MARK: - Existing == .update @@ -579,7 +579,7 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { mutationEventVerified.fulfill() } - await waitForExpectations(timeout: 1.0) + await fulfillment(of: [mutationEventVerified], timeout: 1.0) } /// - Given: A mutation queue with an in-process .create event @@ -633,7 +633,7 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { mutationEventVerified.fulfill() } - await waitForExpectations(timeout: 1.0) + await fulfillment(of: [mutationEventVerified], timeout: 1.0) } /// - Given: A mutation queue with an in-process .create event @@ -671,7 +671,6 @@ class MutationIngesterConflictResolutionTests: SyncEngineTestBase { mutationEventVerified.fulfill() } - await waitForExpectations(timeout: 1.0) + await fulfillment(of: [mutationEventVerified], timeout: 1.0) } - } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueNetworkTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueNetworkTests.swift index 65613f061f..7151921bf2 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueNetworkTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueNetworkTests.swift @@ -150,7 +150,7 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { let postCopy1 = post Task { _ = try await Amplify.DataStore.save(postCopy1) - await savedUpdate1.fulfill() + savedUpdate1.fulfill() } await fulfillment(of: [savedUpdate1]) @@ -178,7 +178,7 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { // Assert that DataStore has pushed the no-network event. This isn't strictly necessary for // correct operation of the queue. - await waitForExpectations(timeout: 1.0) + await fulfillment(of: [networkUnavailable], timeout: 1.0) // At this point, the MutationEvent table has only a record for update1. It is marked as // `inProcess: false`, because the mutation queue has been fully cancelled by the cleanup @@ -197,7 +197,7 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { let postCopy2 = post Task { _ = try await Amplify.DataStore.save(postCopy2) - await savedUpdate2.fulfill() + savedUpdate2.fulfill() } await fulfillment(of: [savedUpdate2]) @@ -214,7 +214,7 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { let postCopy3 = post Task { _ = try await Amplify.DataStore.save(postCopy3) - await savedFinalUpdate.fulfill() + savedFinalUpdate.fulfill() } await fulfillment(of: [savedFinalUpdate]) @@ -250,7 +250,8 @@ class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { apiPlugin.responders = [.mutateRequestListener: acceptSubsequentMutations] reachabilitySubject.send(ReachabilityUpdate(isOnline: true)) - await waitForExpectations(timeout: 5.0) + + await fulfillment(of: [networkAvailableAgain, syncStarted, expectedFinalContentReceived, outboxEmpty], timeout: 5.0) } // MARK: - Utilities diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTests.swift index 3e4bf4886e..24f0d5a131 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTests.swift @@ -84,12 +84,19 @@ class OutgoingMutationQueueTests: SyncEngineTestBase { let saveSuccess = expectation(description: "save success") Task { _ = try await Amplify.DataStore.save(post) - await saveSuccess.fulfill() + saveSuccess.fulfill() } await fulfillment(of: [saveSuccess], timeout: 1.0) - - - await waitForExpectations(timeout: 5.0, handler: nil) + + await fulfillment( + of: [ + outboxStatusOnStart, + outboxStatusOnMutationEnqueued, + outboxMutationEnqueued, + createMutationSent + ], + timeout: 5.0 + ) Amplify.Hub.removeListener(hubListener) } @@ -188,7 +195,18 @@ class OutgoingMutationQueueTests: SyncEngineTestBase { try await startAmplify() } - await waitForExpectations(timeout: 5.0, handler: nil) + + + await fulfillment( + of: [ + outboxStatusOnStart, + outboxStatusOnMutationEnqueued, + mutation1Sent, + mutation2Sent + ], + timeout: 5.0 + ) + Amplify.Hub.removeListener(hubListener) } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTestsWithMockStateMachine.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTestsWithMockStateMachine.swift index 9552459629..34fac59b71 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTestsWithMockStateMachine.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/OutgoingMutationQueueTestsWithMockStateMachine.swift @@ -76,7 +76,7 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { receivedSubscription.fulfill() } stateMachine.state = .starting(apiBehavior, publisher, reconciliationQueue) - await fulfillment(of: [receivedSubscription], timeout: 1.0) + wait(for: [receivedSubscription], timeout: 1.0) let json = "{\"id\":\"1234\",\"title\":\"t\",\"content\":\"c\",\"createdAt\":\"2020-09-03T22:55:13.424Z\"}" let futureResult = MutationEvent(modelId: "1", @@ -102,7 +102,7 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { stateMachine.state = .requestingEvent - await fulfillment(of: [enqueueEvent, apiMutationReceived], timeout: 1) + wait(for: [enqueueEvent, apiMutationReceived], timeout: 1) let processEvent = expectation(description: "state requestingEvent, processedEvent") stateMachine.pushExpectActionCriteria { action in @@ -120,7 +120,7 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { let remoteMutationSync = MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata) listenerFromRequest(.success(.success(remoteMutationSync))) - await fulfillment(of: [processEvent], timeout: 1) + wait(for: [processEvent], timeout: 1) } func testRequestingEvent_nosubscription() { @@ -143,7 +143,7 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { receivedSubscription.fulfill() } stateMachine.state = .starting(apiBehavior, publisher, reconciliationQueue) - await fulfillment(of: [receivedSubscription], timeout: 0.1) + wait(for: [receivedSubscription], timeout: 0.1) // Mock incoming mutation event let post = Post(title: "title", @@ -169,7 +169,7 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { apiBehavior.responders[.mutateRequestListener] = responder stateMachine.state = .requestingEvent - await fulfillment(of: [enqueueEvent, mutateAPICallExpecation], timeout: 0.1) + wait(for: [enqueueEvent, mutateAPICallExpecation], timeout: 0.1) // While we are expecting the mutationEvent to be processed by making an API call, // stop the mutation queue. Note that we are not testing that the operation @@ -181,7 +181,7 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { mutationQueueStopped.fulfill() } mutationQueue.stopSyncingToCloud { } - await fulfillment(of: [mutationQueueStopped], timeout: 0.1) + wait(for: [mutationQueueStopped], timeout: 0.1) // Re-enable syncing let startReceivedAgain = expectation(description: "Start received again") @@ -196,7 +196,7 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { mutationEventPublisher: publisher, reconciliationQueue: reconciliationQueue) - await fulfillment(of: [startReceivedAgain], timeout: 1) + wait(for: [startReceivedAgain], timeout: 1) // After - enabling, mock the callback from API to be completed let processEvent = expectation(description: "state requestingEvent, processedEvent") @@ -215,7 +215,7 @@ class OutgoingMutationQueueMockStateTest: XCTestCase { let remoteMutationSync = MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata) listenerFromRequest(.success(.success(remoteMutationSync))) - await fulfillment(of: [processEvent], timeout: 1) + wait(for: [processEvent], timeout: 1) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/ProcessMutationErrorFromCloudOperationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/ProcessMutationErrorFromCloudOperationTests.swift index dc4b0b55c9..12afd41348 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/ProcessMutationErrorFromCloudOperationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/ProcessMutationErrorFromCloudOperationTests.swift @@ -79,7 +79,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { apiError: apiError, completion: completion) queue.addOperation(operation) - await fulfillment(of: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } /// - Given: APIError @@ -122,7 +122,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { apiError: apiError, completion: completion) queue.addOperation(operation) - await fulfillment(of: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } /// - Given: GraphQLError with no errors @@ -165,7 +165,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { graphQLResponseError: graphQLResponseError, completion: completion) queue.addOperation(operation) - await fulfillment(of: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } /// - Given: GraphQLError with no error @@ -209,7 +209,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { graphQLResponseError: graphQLResponseError, completion: completion) queue.addOperation(operation) - await fulfillment(of: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } /// - Given: GraphQLError more than one error to handle @@ -254,7 +254,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { graphQLResponseError: graphQLResponseError, completion: completion) queue.addOperation(operation) - await fulfillment(of: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } /// - Given: GraphQLError ConditionalCheck @@ -305,7 +305,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { graphQLResponseError: graphQLResponseError, completion: completion) queue.addOperation(operation) - await fulfillment(of: [expectHubEvent, expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectHubEvent, expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) Amplify.Hub.removeListener(hubListener) } @@ -345,7 +345,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { graphQLResponseError: graphQLResponseError, completion: completion) queue.addOperation(operation) - await fulfillment(of: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } func testProcessMutationErrorFromCloudOperationSuccessForOperationDisabled() throws { @@ -384,7 +384,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { graphQLResponseError: graphQLResponseError, completion: completion) queue.addOperation(operation) - await fulfillment(of: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } func testProcessMutationErrorFromCloudOperationSuccessForUnknownError() throws { @@ -423,7 +423,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { graphQLResponseError: graphQLResponseError, completion: completion) queue.addOperation(operation) - await fulfillment(of: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectErrorHandlerCalled, expectCompletion], timeout: defaultAsyncWaitTimeout) } /// - Given: Conflict Unhandled error @@ -455,7 +455,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { graphQLResponseError: graphQLResponseError, completion: completion) queue.addOperation(operation) - await fulfillment(of: [expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) } /// - Given: Conflict Unhandled error @@ -491,7 +491,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { graphQLResponseError: graphQLResponseError, completion: completion) queue.addOperation(operation) - await fulfillment(of: [expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) } /// - Given: Conflict Unhandled error @@ -521,7 +521,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { graphQLResponseError: graphQLResponseError, completion: completion) queue.addOperation(operation) - await fulfillment(of: [expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) } /// - Given: Conflict Unhandled error @@ -583,8 +583,8 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { queue.addOperation(operation) - await fulfillment(of: [expectConflicthandlerCalled], timeout: defaultAsyncWaitTimeout) - await fulfillment(of: [apiMutateCalled], timeout: defaultAsyncWaitTimeout) + wait(for: [expectConflicthandlerCalled], timeout: defaultAsyncWaitTimeout) + wait(for: [apiMutateCalled], timeout: defaultAsyncWaitTimeout) guard let eventListener = eventListenerOptional else { XCTFail("Listener was not called through MockAPICategoryPlugin") return @@ -597,7 +597,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let mockResponse = MutationSync(model: try localPost.eraseToAnyModel(), syncMetadata: updatedMetadata) eventListener(.success(.success(mockResponse))) - await fulfillment(of: [expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) } /// - Given: Conflict Unhandled error @@ -660,8 +660,8 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { queue.addOperation(operation) - await fulfillment(of: [expectConflicthandlerCalled], timeout: defaultAsyncWaitTimeout) - await fulfillment(of: [apiMutateCalled], timeout: defaultAsyncWaitTimeout) + wait(for: [expectConflicthandlerCalled], timeout: defaultAsyncWaitTimeout) + wait(for: [apiMutateCalled], timeout: defaultAsyncWaitTimeout) guard let eventListener = eventListenerOptional else { XCTFail("Listener was not called through MockAPICategoryPlugin") return @@ -674,7 +674,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let mockResponse = MutationSync(model: try localPost.eraseToAnyModel(), syncMetadata: updatedMetadata) eventListener(.success(.success(mockResponse))) - await fulfillment(of: [expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) } /// - Given: Conflict Unhandled error @@ -739,9 +739,9 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { completion: completion) queue.addOperation(operation) - await fulfillment(of: [modelSavedEvent], timeout: defaultAsyncWaitTimeout) - await fulfillment(of: [expectHubEvent], timeout: defaultAsyncWaitTimeout) - await fulfillment(of: [expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [modelSavedEvent], timeout: defaultAsyncWaitTimeout) + wait(for: [expectHubEvent], timeout: defaultAsyncWaitTimeout) + wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) Amplify.Hub.removeListener(hubListener) } @@ -803,10 +803,10 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { queue.addOperation(operation) - await fulfillment(of: [modelDeletedEvent], timeout: defaultAsyncWaitTimeout) - await fulfillment(of: [metadataSavedEvent], timeout: defaultAsyncWaitTimeout) - await fulfillment(of: [expectHubEvent], timeout: defaultAsyncWaitTimeout) - await fulfillment(of: [expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [modelDeletedEvent], timeout: defaultAsyncWaitTimeout) + wait(for: [metadataSavedEvent], timeout: defaultAsyncWaitTimeout) + wait(for: [expectHubEvent], timeout: defaultAsyncWaitTimeout) + wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) Amplify.Hub.removeListener(hubListener) } @@ -884,11 +884,11 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { completion: completion) queue.addOperation(operation) - await fulfillment(of: [expectConflicthandlerCalled], timeout: defaultAsyncWaitTimeout) - await fulfillment(of: [modelSavedEvent], timeout: defaultAsyncWaitTimeout) - await fulfillment(of: [metadataSavedEvent], timeout: defaultAsyncWaitTimeout) - await fulfillment(of: [expectHubEvent], timeout: defaultAsyncWaitTimeout) - await fulfillment(of: [expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectConflicthandlerCalled], timeout: defaultAsyncWaitTimeout) + wait(for: [modelSavedEvent], timeout: defaultAsyncWaitTimeout) + wait(for: [metadataSavedEvent], timeout: defaultAsyncWaitTimeout) + wait(for: [expectHubEvent], timeout: defaultAsyncWaitTimeout) + wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) Amplify.Hub.removeListener(hubListener) } @@ -954,8 +954,8 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { queue.addOperation(operation) - await fulfillment(of: [expectConflicthandlerCalled], timeout: defaultAsyncWaitTimeout) - await fulfillment(of: [apiMutateCalled], timeout: defaultAsyncWaitTimeout) + wait(for: [expectConflicthandlerCalled], timeout: defaultAsyncWaitTimeout) + wait(for: [apiMutateCalled], timeout: defaultAsyncWaitTimeout) guard let eventListener = eventListenerOptional else { XCTFail("Listener was not called through MockAPICategoryPlugin") return @@ -967,7 +967,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { version: 3) let mockResponse = MutationSync(model: try localPost.eraseToAnyModel(), syncMetadata: updatedMetadata) eventListener(.success(.success(mockResponse))) - await fulfillment(of: [expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) } /// - Given: Conflict Unhandled error @@ -1032,8 +1032,8 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { completion: completion) queue.addOperation(operation) - await fulfillment(of: [expectConflicthandlerCalled], timeout: defaultAsyncWaitTimeout) - await fulfillment(of: [apiMutateCalled], timeout: defaultAsyncWaitTimeout) + wait(for: [expectConflicthandlerCalled], timeout: defaultAsyncWaitTimeout) + wait(for: [apiMutateCalled], timeout: defaultAsyncWaitTimeout) guard let eventListener = eventListenerOptional else { XCTFail("Listener was not called through MockAPICategoryPlugin") return @@ -1045,7 +1045,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { version: 3) let mockResponse = MutationSync(model: try localPost.eraseToAnyModel(), syncMetadata: updatedMetadata) eventListener(.success(.success(mockResponse))) - await fulfillment(of: [expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) } /// - Given: Conflict Unhandled error @@ -1113,8 +1113,8 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { completion: completion) queue.addOperation(operation) - await fulfillment(of: [expectConflicthandlerCalled], timeout: defaultAsyncWaitTimeout) - await fulfillment(of: [apiMutateCalled], timeout: defaultAsyncWaitTimeout) + wait(for: [expectConflicthandlerCalled], timeout: defaultAsyncWaitTimeout) + wait(for: [apiMutateCalled], timeout: defaultAsyncWaitTimeout) guard let eventListener = eventListenerOptional else { XCTFail("Listener was not called through MockAPICategoryPlugin") return @@ -1123,8 +1123,8 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { let error = GraphQLError(message: "some other error") eventListener(.success(.failure(.error([error])))) - await fulfillment(of: [expectErrorHandlerCalled], timeout: defaultAsyncWaitTimeout) - await fulfillment(of: [expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectErrorHandlerCalled], timeout: defaultAsyncWaitTimeout) + wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) } /// Given: GraphQL "OperationDisabled" error @@ -1159,7 +1159,7 @@ class ProcessMutationErrorFromCloudOperationTests: XCTestCase { completion: completion) queue.addOperation(operation) - await fulfillment(of: [expectCompletion], timeout: defaultAsyncWaitTimeout) + wait(for: [expectCompletion], timeout: defaultAsyncWaitTimeout) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSync/RemoteSyncAPIInvocationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSync/RemoteSyncAPIInvocationTests.swift index 35755d3213..0879f7d345 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSync/RemoteSyncAPIInvocationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSync/RemoteSyncAPIInvocationTests.swift @@ -107,12 +107,19 @@ class RemoteSyncAPIInvocationTests: XCTestCase { let startSuccess = expectation(description: "start success") Task { _ = try await Amplify.DataStore.start() - await startSuccess.fulfill() + startSuccess.fulfill() } await fulfillment(of: [startSuccess], timeout: 1.0) - - await waitForExpectations(timeout: 1.0) + await fulfillment( + of: [ + createSubscriptionStarted, + updateSubscriptionStarted, + deleteSubscriptionStarted + ], + timeout: 1.0 + ) } + // TODO: Implement the test below /// - Given: Amplify configured with an API diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSyncEngineTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSyncEngineTests.swift index f9c90aab2b..da315bde7e 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSyncEngineTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/RemoteSyncEngineTests.swift @@ -64,7 +64,7 @@ class RemoteSyncEngineTests: XCTestCase { remoteSyncEngine.start(api: MockAPICategoryPlugin(), auth: nil) - await fulfillment(of: [failureOnStorageAdapter], timeout: defaultAsyncWaitTimeout) + wait(for: [failureOnStorageAdapter], timeout: defaultAsyncWaitTimeout) remoteSyncEngineSink.cancel() } @@ -130,7 +130,20 @@ class RemoteSyncEngineTests: XCTestCase { remoteSyncEngine.start(api: apiPlugin, auth: nil) - await waitForExpectations(timeout: defaultAsyncWaitTimeout) + await fulfillment( + of: [ + storageAdapterAvailable, + subscriptionsPaused, + mutationsPaused, + stateMutationsCleared, + subscriptionsInitialized, + subscriptionsEstablishedReceived, + cleanedup, + failureOnInitialSync, + retryAdviceReceivedNetworkError + ], + timeout: defaultAsyncWaitTimeout + ) remoteSyncEngineSink.cancel() Amplify.Hub.removeListener(hubListener) } @@ -182,15 +195,20 @@ class RemoteSyncEngineTests: XCTestCase { remoteSyncEngine.start(api: apiPlugin, auth: nil) - await fulfillment(of: [storageAdapterAvailable, - subscriptionsPaused, - mutationsPaused, - stateMutationsCleared, - subscriptionsInitialized, - performedInitialSync, - subscriptionActivation, - mutationQueueStarted, - syncStarted], timeout: defaultAsyncWaitTimeout) + wait( + for: [ + storageAdapterAvailable, + subscriptionsPaused, + mutationsPaused, + stateMutationsCleared, + subscriptionsInitialized, + performedInitialSync, + subscriptionActivation, + mutationQueueStarted, + syncStarted + ], + timeout: defaultAsyncWaitTimeout + ) remoteSyncEngineSink.cancel() } @@ -253,17 +271,22 @@ class RemoteSyncEngineTests: XCTestCase { remoteSyncEngine.start(api: apiPlugin, auth: nil) - await fulfillment(of: [storageAdapterAvailable, - subscriptionsPaused, - mutationsPaused, - stateMutationsCleared, - subscriptionsInitialized, - performedInitialSync, - subscriptionActivation, - mutationQueueStarted, - syncStarted, - cleanedUp, - forceFailToNotRestartSyncEngine], timeout: defaultAsyncWaitTimeout) + wait( + for: [ + storageAdapterAvailable, + subscriptionsPaused, + mutationsPaused, + stateMutationsCleared, + subscriptionsInitialized, + performedInitialSync, + subscriptionActivation, + mutationQueueStarted, + syncStarted, + cleanedUp, + forceFailToNotRestartSyncEngine + ], + timeout: defaultAsyncWaitTimeout + ) remoteSyncEngineSink.cancel() } @@ -330,18 +353,23 @@ class RemoteSyncEngineTests: XCTestCase { remoteSyncEngine.start(api: apiPlugin, auth: nil) - await fulfillment(of: [storageAdapterAvailable, - subscriptionsPaused, - mutationsPaused, - stateMutationsCleared, - subscriptionsInitialized, - performedInitialSync, - subscriptionActivation, - mutationQueueStarted, - syncStarted, - cleanedUpForTermination, - completionBlockCalled, - forceFailToNotRestartSyncEngine], timeout: defaultAsyncWaitTimeout) + wait( + for: [ + storageAdapterAvailable, + subscriptionsPaused, + mutationsPaused, + stateMutationsCleared, + subscriptionsInitialized, + performedInitialSync, + subscriptionActivation, + mutationQueueStarted, + syncStarted, + cleanedUpForTermination, + completionBlockCalled, + forceFailToNotRestartSyncEngine + ], + timeout: defaultAsyncWaitTimeout + ) remoteSyncEngineSink.cancel() } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueueTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueueTests.swift index b10e865a7d..7969b27416 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueueTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/AWSIncomingEventReconciliationQueueTests.swift @@ -78,8 +78,8 @@ class AWSIncomingEventReconciliationQueueTests: XCTestCase { operationQueue.addOperation(cancellableOperation) } operationQueue.isSuspended = false - await waitForExpectations(timeout: 2) + await fulfillment(of: [expectStarted, expectInitialized], timeout: 2) // Take action on the sink to prevent compiler warnings about unused variables. sink.cancel() } @@ -113,8 +113,8 @@ class AWSIncomingEventReconciliationQueueTests: XCTestCase { operationQueue.addOperation(cancellableOperation) } operationQueue.isSuspended = false - await waitForExpectations(timeout: 2) + await fulfillment(of: [expectStarted, expectInitialized], timeout: 2) sink.cancel() } @@ -152,8 +152,8 @@ class AWSIncomingEventReconciliationQueueTests: XCTestCase { operationQueue.addOperation(cancellableOperation) } operationQueue.isSuspended = false - await waitForExpectations(timeout: 2) + await fulfillment(of: [expectStarted, expectInitialized], timeout: 2) sink.cancel() } @@ -187,8 +187,8 @@ class AWSIncomingEventReconciliationQueueTests: XCTestCase { operationQueue.addOperation(cancellableOperation) } operationQueue.isSuspended = false - await waitForExpectations(timeout: 2) + await fulfillment(of: [expectStarted, expectInitialized], timeout: 2) sink.cancel() } @@ -228,8 +228,8 @@ class AWSIncomingEventReconciliationQueueTests: XCTestCase { operationQueue.addOperation(cancellableOperation) } operationQueue.isSuspended = false - await waitForExpectations(timeout: 2) + await fulfillment(of: [expectStarted, expectInitialized], timeout: 2) sink.cancel() } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ModelReconciliationDeleteTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ModelReconciliationDeleteTests.swift index 0408f19ca2..b1b3d978bd 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ModelReconciliationDeleteTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ModelReconciliationDeleteTests.swift @@ -38,7 +38,7 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { version: 2) let localMetadataSaved = expectation(description: "Local metadata saved") storageAdapter.save(localSyncMetadata) { _ in localMetadataSaved.fulfill() } - await waitForExpectations(timeout: 1.0) + await fulfillment(of: [localMetadataSaved], timeout: 1) var valueListenerFromRequest: MutationSyncInProcessListener? let expectationListener = expectation(description: "listener") @@ -57,8 +57,8 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { mockRemoteSyncEngineFor_testUpdateAfterDelete() try await startAmplifyAndWaitForSync() } - await waitForExpectations(timeout: 2.0) + await fulfillment(of: [expectationListener], timeout: 2) guard let valueListener = valueListenerFromRequest else { XCTFail("Incoming responder didn't set up listener") return @@ -149,8 +149,8 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { mockRemoteSyncEngineFor_testDeleteWithNoLocalModel() try await startAmplifyAndWaitForSync() } - await waitForExpectations(timeout: 1) - + + await fulfillment(of: [expectationListener], timeout: 1) guard let valueListener = valueListenerFromRequest else { XCTFail("Incoming responder didn't set up listener") return @@ -176,8 +176,7 @@ class ModelReconciliationDeleteTests: SyncEngineTestBase { let remoteMutationSync = MutationSync(model: anyModel, syncMetadata: remoteSyncMetadata) valueListener(.data(.success(remoteMutationSync))) - await waitForExpectations(timeout: 1) - + await fulfillment(of: [syncReceivedNotification], timeout: 1) let finalLocalMetadata = try storageAdapter.queryMutationSyncMetadata(for: model.id, modelName: MockSynced.modelName) XCTAssertEqual(finalLocalMetadata?.version, 2) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ModelReconciliationQueueBehaviorTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ModelReconciliationQueueBehaviorTests.swift index 11cb3fdd98..34e381fba5 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ModelReconciliationQueueBehaviorTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ModelReconciliationQueueBehaviorTests.swift @@ -120,7 +120,17 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { queue.start() - await waitForExpectations(timeout: 5.0) + await fulfillment( + of: [ + event1Saved, + event2Saved, + event3Saved, + eventsSentViaPublisher1, + eventsSentViaPublisher2, + eventsSentViaPublisher3 + ], + timeout: 5 + ) queueSink.cancel() } @@ -190,7 +200,15 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { queue.start() - await waitForExpectations(timeout: 5.0) + await fulfillment( + of: [ + event1Saved, + event3Saved, + eventsSentViaPublisher1, + eventsSentViaPublisher3 + ], + timeout: 5 + ) queueSink.cancel() } @@ -283,7 +301,15 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { queue.start() - await waitForExpectations(timeout: 5.0) + await fulfillment( + of: [ + eventsSentViaPublisher1, + eventsSentViaPublisher2, + eventsSentViaPublisher3, + allEventsProcessed + ], + timeout: 5 + ) queueSink.cancel() } @@ -351,7 +377,15 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { queue.start() - await waitForExpectations(timeout: 1.0) + await fulfillment( + of: [ + event1ShouldBeProcessed, + event2ShouldBeProcessed, + eventsSentViaPublisher1, + eventsSentViaPublisher2 + ], + timeout: 1 + ) let event1ShouldNotBeProcessed = expectation(description: "Event 1 should not be processed") event1ShouldNotBeProcessed.isInverted = true @@ -393,7 +427,15 @@ class ModelReconciliationQueueBehaviorTests: ReconciliationQueueTestBase { let mutationSync = MutationSync(model: model, syncMetadata: syncMetadata) subscriptionEventsSubject.send(.mutationEvent(mutationSync)) - await waitForExpectations(timeout: 1.0) + await fulfillment( + of: [ + event1ShouldNotBeProcessed, + event2ShouldNotBeProcessed, + event3ShouldBeProcessed, + eventsSentViaPublisher3 + ], + timeout: 1 + ) queueSink.cancel() } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndSaveQueueTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndSaveQueueTests.swift index f25a46e793..aeb93311cb 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndSaveQueueTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/SubscriptionSync/ReconcileAndSaveQueueTests.swift @@ -56,9 +56,9 @@ class ReconcileAndSaveQueueTests: XCTestCase { stateMachine: stateMachine) queue.addOperation(operation, modelName: Post.modelName) XCTAssertEqual(stateMachine.state, ReconcileAndLocalSaveOperation.State.waiting) - await fulfillment(of: [operationAdded], timeout: 1) + wait(for: [operationAdded], timeout: 1) stateMachine.state = .finished - await fulfillment(of: [operationRemoved], timeout: 1) + wait(for: [operationRemoved], timeout: 1) sink.cancel() } @@ -85,10 +85,10 @@ class ReconcileAndSaveQueueTests: XCTestCase { stateMachine: stateMachine) queue.addOperation(operation, modelName: Post.modelName) XCTAssertEqual(stateMachine.state, ReconcileAndLocalSaveOperation.State.waiting) - await fulfillment(of: [operationAdded], timeout: 1) + wait(for: [operationAdded], timeout: 1) queue.cancelOperations(modelName: Post.modelName) - await fulfillment(of: [cancelledOperations], timeout: 1) + wait(for: [cancelledOperations], timeout: 1) sink.cancel() } @@ -115,10 +115,10 @@ class ReconcileAndSaveQueueTests: XCTestCase { stateMachine: stateMachine) queue.addOperation(operation, modelName: Post.modelName) XCTAssertEqual(stateMachine.state, ReconcileAndLocalSaveOperation.State.waiting) - await fulfillment(of: [operationAdded], timeout: 1) + wait(for: [operationAdded], timeout: 1) queue.cancelAllOperations() - await fulfillment(of: [cancelledOperations], timeout: 1) + wait(for: [cancelledOperations], timeout: 1) sink.cancel() } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/MutationEventExtensionsTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/MutationEventExtensionsTests.swift index 552c1b2492..e709ebe364 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/MutationEventExtensionsTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/MutationEventExtensionsTests.swift @@ -59,7 +59,7 @@ class MutationEventExtensionsTest: BaseDataStoreTests { updatingVersionExpectation.fulfill() } } - await fulfillment(of: [updatingVersionExpectation], timeout: 1) + wait(for: [updatingVersionExpectation], timeout: 1) // query for head of mutation event table for given model id and check if it has the updated version MutationEvent.pendingMutationEvents(forModel: post, @@ -77,7 +77,7 @@ class MutationEventExtensionsTest: BaseDataStoreTests { queryAfterUpdatingVersionExpectation.fulfill() } } - await fulfillment(of: [queryAfterUpdatingVersionExpectation], timeout: 1) + wait(for: [queryAfterUpdatingVersionExpectation], timeout: 1) } /// - Given: A pending mutation events queue with two events(update and delete) containing `nil` version, @@ -130,7 +130,7 @@ class MutationEventExtensionsTest: BaseDataStoreTests { updatingVersionExpectation.fulfill() } } - await fulfillment(of: [updatingVersionExpectation], timeout: 1) + wait(for: [updatingVersionExpectation], timeout: 1) // query for head of mutation event table for given model id and check if it has the updated version MutationEvent.pendingMutationEvents(forModel: post, @@ -149,7 +149,7 @@ class MutationEventExtensionsTest: BaseDataStoreTests { queryAfterUpdatingVersionExpectation.fulfill() } } - await fulfillment(of: [queryAfterUpdatingVersionExpectation], timeout: 1) + wait(for: [queryAfterUpdatingVersionExpectation], timeout: 1) } /// - Given: A pending mutation events queue with event containing version 2, a sent mutation event model @@ -194,7 +194,7 @@ class MutationEventExtensionsTest: BaseDataStoreTests { updatingVersionExpectation.fulfill() } } - await fulfillment(of: [updatingVersionExpectation], timeout: 1) + wait(for: [updatingVersionExpectation], timeout: 1) // query for head of mutation event table for given model id and check if it has the correct version MutationEvent.pendingMutationEvents(forModel: post1, @@ -212,7 +212,7 @@ class MutationEventExtensionsTest: BaseDataStoreTests { queryAfterUpdatingVersionExpectation.fulfill() } } - await fulfillment(of: [queryAfterUpdatingVersionExpectation], timeout: 1) + wait(for: [queryAfterUpdatingVersionExpectation], timeout: 1) } /// - Given: A pending mutation events queue with event containing version 1, a sent mutation event model @@ -258,7 +258,7 @@ class MutationEventExtensionsTest: BaseDataStoreTests { updatingVersionExpectation.fulfill() } } - await fulfillment(of: [updatingVersionExpectation], timeout: 1) + wait(for: [updatingVersionExpectation], timeout: 1) // query for head of mutation event table for given model id and check if it has the correct version MutationEvent.pendingMutationEvents(forModel: post1, @@ -276,7 +276,7 @@ class MutationEventExtensionsTest: BaseDataStoreTests { queryAfterUpdatingVersionExpectation.fulfill() } } - await fulfillment(of: [queryAfterUpdatingVersionExpectation], timeout: 1) + wait(for: [queryAfterUpdatingVersionExpectation], timeout: 1) } /// - Given: A pending mutation events queue with event containing version 1, a sent mutation event model @@ -321,7 +321,7 @@ class MutationEventExtensionsTest: BaseDataStoreTests { updatingVersionExpectation.fulfill() } } - await fulfillment(of: [updatingVersionExpectation], timeout: 1) + wait(for: [updatingVersionExpectation], timeout: 1) // query for head of mutation event table for given model id and check if it has the correct version MutationEvent.pendingMutationEvents(forModel: post1, @@ -339,7 +339,7 @@ class MutationEventExtensionsTest: BaseDataStoreTests { queryAfterUpdatingVersionExpectation.fulfill() } } - await fulfillment(of: [queryAfterUpdatingVersionExpectation], timeout: 1) + wait(for: [queryAfterUpdatingVersionExpectation], timeout: 1) } private func createMutationEvent(model: Model, @@ -378,7 +378,7 @@ class MutationEventExtensionsTest: BaseDataStoreTests { } mutationEventSaveExpectation.fulfill() } - await fulfillment(of: [mutationEventSaveExpectation], timeout: 1) + wait(for: [mutationEventSaveExpectation], timeout: 1) } // verify the head of queue is expected @@ -399,6 +399,6 @@ class MutationEventExtensionsTest: BaseDataStoreTests { headOfQueueExpectation.fulfill() } } - await fulfillment(of: [headOfQueueExpectation], timeout: 1) + wait(for: [headOfQueueExpectation], timeout: 1) } } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/MutationEventQueryTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/MutationEventQueryTests.swift index feda211fd5..9e1eb5df65 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/MutationEventQueryTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/Support/MutationEventQueryTests.swift @@ -29,7 +29,7 @@ class MutationEventQueryTests: BaseDataStoreTests { } } - await fulfillment(of: [querySuccess], timeout: 1) + wait(for: [querySuccess], timeout: 1) } func testQueryPendingMutationEvent() { @@ -55,7 +55,7 @@ class MutationEventQueryTests: BaseDataStoreTests { case .failure(let error): XCTFail("\(error)") } } - await fulfillment(of: [querySuccess], timeout: 1) + wait(for: [querySuccess], timeout: 1) } func testQueryPendingMutationEventsForModelIds() { @@ -70,7 +70,7 @@ class MutationEventQueryTests: BaseDataStoreTests { } saveMutationEvent1.fulfill() } - await fulfillment(of: [saveMutationEvent1], timeout: 1) + wait(for: [saveMutationEvent1], timeout: 1) let saveMutationEvent2 = expectation(description: "save mutationEvent1 success") storageAdapter.save(mutationEvent2) { result in @@ -80,7 +80,7 @@ class MutationEventQueryTests: BaseDataStoreTests { } saveMutationEvent2.fulfill() } - await fulfillment(of: [saveMutationEvent2], timeout: 1) + wait(for: [saveMutationEvent2], timeout: 1) let querySuccess = expectation(description: "query for metadata success") var mutationEvents = [mutationEvent1] @@ -98,7 +98,7 @@ class MutationEventQueryTests: BaseDataStoreTests { } } - await fulfillment(of: [querySuccess], timeout: 1) + wait(for: [querySuccess], timeout: 1) } private func generateRandomMutationEvent() -> MutationEvent { diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/BaseDataStoreTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/BaseDataStoreTests.swift index 686c41a705..6318ef6ce8 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/BaseDataStoreTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/BaseDataStoreTests.swift @@ -102,7 +102,7 @@ class BaseDataStoreTests: XCTestCase { if let model = models.first { save(model: model, index: 0) - await fulfillment(of: [saveComplete], timeout: 1.0) + wait(for: [saveComplete], timeout: 1.0) } else { saveComplete.fulfill() } diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/SyncEngineTestBase.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/SyncEngineTestBase.swift index ab1aa26bbf..39be1f31c2 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/SyncEngineTestBase.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/TestSupport/SyncEngineTestBase.swift @@ -241,7 +241,7 @@ class SyncEngineTestBase: XCTestCase { mutationEventSaved.fulfill() } } - await fulfillment(of: [mutationEventSaved], timeout: 1.0) + wait(for: [mutationEventSaved], timeout: 1.0) } /// Saves a Post record directly to StorageAdapter. Used for pre-populating database before tests @@ -255,7 +255,7 @@ class SyncEngineTestBase: XCTestCase { postSaved.fulfill() } } - await fulfillment(of: [postSaved], timeout: 1.0) + wait(for: [postSaved], timeout: 1.0) } // MARK: - Helpers diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyBaseTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyBaseTest.swift index 1b562be5c1..781d532348 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyBaseTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginCPKTests/PrimaryKey/AWSDataStorePrimaryKeyBaseTest.swift @@ -121,8 +121,14 @@ extension AWSDataStorePrimaryKeyBaseTest { .store(in: &requests) try await Amplify.DataStore.start() - - await waitForExpectations(timeout: 60) + await fulfillment( + of: [ + ready, + subscriptionsEstablished, + modelsSynced + ], + timeout: 60 + ) } /// Assert that a save and a delete mutation complete successfully. @@ -152,8 +158,11 @@ extension AWSDataStorePrimaryKeyBaseTest { let savedModels = try await Amplify.DataStore.save(model) XCTAssertNotNil(savedModels) - await waitForExpectations(timeout: 60) - + await fulfillment( + of: [mutationSaveProcessed], + timeout: 60 + ) + let mutationDeleteProcessed = expectation(description: "mutation delete processed") Amplify .Hub @@ -173,7 +182,10 @@ extension AWSDataStorePrimaryKeyBaseTest { .store(in: &requests) try await Amplify.DataStore.delete(model) - await waitForExpectations(timeout: 60) + await fulfillment( + of: [mutationDeleteProcessed], + timeout: 60 + ) } /// Assert that a save and a delete mutation complete successfully. @@ -211,8 +223,8 @@ extension AWSDataStorePrimaryKeyBaseTest { // save child _ = try await Amplify.DataStore.save(child) - await waitForExpectations(timeout: 60) - + await fulfillment(of: [mutationSaveProcessed], timeout: 60) + guard shouldDeleteParent else { return } @@ -242,6 +254,6 @@ extension AWSDataStorePrimaryKeyBaseTest { // delete parent try await Amplify.DataStore.delete(parent) - await waitForExpectations(timeout: 60) + await fulfillment(of: [mutationDeleteProcessed], timeout: 60) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreConsecutiveUpdatesTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreConsecutiveUpdatesTests.swift index a25289f8e2..eb21319b2e 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreConsecutiveUpdatesTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreConsecutiveUpdatesTests.swift @@ -83,7 +83,7 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { let queryResult = try await queryPost(byId: updatedPost.id) XCTAssertEqual(queryResult, updatedPost) - await waitForExpectations(timeout: networkTimeout) + await fulfillment(of: [updateSyncReceived], timeout: networkTimeout) // query the updated post in eventual consistent state let queryResultAfterSync = try await queryPost(byId: updatedPost.id) @@ -221,12 +221,12 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { if mutationEvent.mutationType == GraphQLMutationType.create.rawValue { XCTAssertEqual(post, newPost) XCTAssertEqual(mutationEvent.version, 1) - Task { await saveSyncReceived.fulfill() } + saveSyncReceived.fulfill() } if mutationEvent.version == 3 { XCTAssertEqual(post, updatedPost) - Task { await deleteSyncReceived.fulfill() } + deleteSyncReceived.fulfill() } } @@ -254,22 +254,22 @@ class DataStoreConsecutiveUpdatesTests: SyncEngineIntegrationTestBase { let queryRequest = GraphQLRequest.query(modelName: updatedPost.modelName, byId: updatedPost.id) let mutationSyncResult = try await Amplify.API.query(request: queryRequest) - switch mutationSyncResult { - case .success(let data): - guard let post = data else { - XCTFail("Failed to get data") - return - } - - XCTAssertEqual(post.model["title"] as? String, updatedPost.title) - XCTAssertEqual(post.model["content"] as? String, updatedPost.content) - XCTAssertEqual(post.model["rating"] as? Double, updatedPost.rating) - - XCTAssertTrue(post.syncMetadata.deleted) - XCTAssertEqual(post.syncMetadata.version, 3) - case .failure(let error): - XCTFail("Error: \(error)") - } + switch mutationSyncResult { + case .success(let data): + guard let post = data else { + XCTFail("Failed to get data") + return + } + + XCTAssertEqual(post.model["title"] as? String, updatedPost.title) + XCTAssertEqual(post.model["content"] as? String, updatedPost.content) + XCTAssertEqual(post.model["rating"] as? Double, updatedPost.rating) + + XCTAssertTrue(post.syncMetadata.deleted) + XCTAssertEqual(post.syncMetadata.version, 3) + case .failure(let error): + XCTFail("Error: \(error)") + } } /// - Given: API has been setup with `Post` model registered diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreCustomPrimaryKeyTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreCustomPrimaryKeyTests.swift index 5bba4ed773..1c89de647a 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreCustomPrimaryKeyTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreCustomPrimaryKeyTests.swift @@ -69,7 +69,7 @@ class DataStoreCustomPrimaryKeyTests: SyncEngineIntegrationTestBase { // create customer order _ = try await Amplify.DataStore.save(customerOrder) - await waitForExpectations(timeout: networkTimeout) + await fulfillment(of: [createReceived], timeout: networkTimeout) // update customer order let updateReceived = expectation(description: "Update notification received") @@ -102,8 +102,8 @@ class DataStoreCustomPrimaryKeyTests: SyncEngineIntegrationTestBase { return } _ = try await Amplify.DataStore.save(updatedCustomerOrder) - await waitForExpectations(timeout: networkTimeout) - + await fulfillment(of: [updateReceived], timeout: networkTimeout) + // query the updated order let queriedOrder = try await Amplify.DataStore.query(CustomerOrder.self, byId: updatedCustomerOrder.id) guard let order = queriedOrder else { @@ -144,8 +144,8 @@ class DataStoreCustomPrimaryKeyTests: SyncEngineIntegrationTestBase { } _ = try await Amplify.DataStore.delete(CustomerOrder.self, withIdentifier: updatedCustomerOrder.id) - await waitForExpectations(timeout: networkTimeout) - + await fulfillment(of: [deleteReceived], timeout: networkTimeout) + // query the customer order after deletion let queriedOrder2 = try await Amplify.DataStore.query(CustomerOrder.self, byId: updatedCustomerOrder.id) XCTAssertNil(queriedOrder2) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreEndToEndTests.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreEndToEndTests.swift index 3854743fb2..1576d90407 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreEndToEndTests.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginIntegrationTests/DataStoreEndToEndTests.swift @@ -686,7 +686,7 @@ class DataStoreEndToEndTests: SyncEngineIntegrationTestBase { _ = try await Amplify.DataStore.save(newPost) - await waitForExpectations(timeout: networkTimeout) + await fulfillment(of: [createReceived], timeout: networkTimeout) } } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressBaseTest.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressBaseTest.swift index 613e17fb10..e6923fd0ed 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressBaseTest.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/DataStoreStressTests/DataStoreStressBaseTest.swift @@ -74,6 +74,6 @@ class DataStoreStressBaseTest: XCTestCase { try await Amplify.DataStore.start() - await waitForExpectations(timeout: networkTimeout) + await fulfillment(of: [eventReceived], timeout: networkTimeout) } } diff --git a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Configuration/AWSLocationGeoPluginConfigurationTests.swift b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Configuration/AWSLocationGeoPluginConfigurationTests.swift index a1566b2fe2..0d69798866 100644 --- a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Configuration/AWSLocationGeoPluginConfigurationTests.swift +++ b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Configuration/AWSLocationGeoPluginConfigurationTests.swift @@ -382,12 +382,10 @@ class AWSLocationGeoPluginConfigurationTests: XCTestCase { (AWSLocationGeoPluginConfiguration.Section.maps.key, mapsConfigJSON), (AWSLocationGeoPluginConfiguration.Section.searchIndices.key, GeoPluginTestConfig.searchConfigJSON)) XCTAssertThrowsError(try AWSLocationGeoPluginConfiguration(config: config)) { error in - guard case let PluginError.pluginConfigurationError(errorDescription, _, _) = error else { + guard case PluginError.pluginConfigurationError(_, _, _) = error else { XCTFail("Expected PluginError pluginConfigurationError, got: \(error)") return } - XCTAssertEqual(errorDescription, - GeoPluginConfigError.mapStyleURLInvalid(mapName: mapName).errorDescription) } } diff --git a/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/Mocks/MockAnalyticsClient.swift b/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/Mocks/MockAnalyticsClient.swift index 4a12397f71..72c48c74c5 100644 --- a/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/Mocks/MockAnalyticsClient.swift +++ b/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/Mocks/MockAnalyticsClient.swift @@ -73,10 +73,10 @@ actor MockAnalyticsClient: AnalyticsClientBehaviour { } - private var recordExpectation: AsyncExpectation? - func setRecordExpectation(_ expectation: AsyncExpectation, count: Int = 1) async { + private var recordExpectation: XCTestExpectation? + func setRecordExpectation(_ expectation: XCTestExpectation, count: Int = 1) { recordExpectation = expectation - await recordExpectation?.setExpectedFulfillmentCount(count) + recordExpectation?.expectedFulfillmentCount = count } var recordCount = 0 @@ -86,23 +86,19 @@ actor MockAnalyticsClient: AnalyticsClientBehaviour { recordCount += 1 lastRecordedEvent = event recordedEvents.append(event) - Task { - await recordExpectation?.fulfill() - } + recordExpectation?.fulfill() } - private var submitEventsExpectation: AsyncExpectation? - func setSubmitEventsExpectation(_ expectation: AsyncExpectation, count: Int = 1) async { + private var submitEventsExpectation: XCTestExpectation? + func setSubmitEventsExpectation(_ expectation: XCTestExpectation, count: Int = 1) { submitEventsExpectation = expectation - await submitEventsExpectation?.setExpectedFulfillmentCount(count) + submitEventsExpectation?.expectedFulfillmentCount = count } var submitEventsCount = 0 func submitEvents() async throws -> [PinpointEvent] { submitEventsCount += 1 - Task { - await submitEventsExpectation?.fulfill() - } + submitEventsExpectation?.fulfill() return [] } diff --git a/AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/AWSCloudWatchLoggingMonitorTests.swift b/AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/AWSCloudWatchLoggingMonitorTests.swift index 07378c4aee..48f66b98b0 100644 --- a/AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/AWSCloudWatchLoggingMonitorTests.swift +++ b/AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/AWSCloudWatchLoggingMonitorTests.swift @@ -31,7 +31,7 @@ final class AWSCloudWatchLoggingMonitorTests: XCTestCase { /// Then: the delegate is autoamtically invoked func testDelegateIsInvokedOnInterval() { monitor.setAutomaticFlushIntervals() - await fulfillment(of: [invokedExpectation], timeout: 3) + wait(for: [invokedExpectation], timeout: 3) } } diff --git a/AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/LoggingNetworkMonitorTests.swift b/AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/LoggingNetworkMonitorTests.swift index 86c2a246e4..58ab0d8ace 100644 --- a/AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/LoggingNetworkMonitorTests.swift +++ b/AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/LoggingNetworkMonitorTests.swift @@ -25,7 +25,7 @@ final class LoggingNetworkMonitorTests: XCTestCase { loggingMonitor.startMonitoring(using: DispatchQueue(label: "AWSCloudWatchingLogging.NetworkMonitor")) - await fulfillment(of: [onlineExpectation], timeout: TestCommonConstants.networkTimeout) + wait(for: [onlineExpectation], timeout: TestCommonConstants.networkTimeout) XCTAssertTrue(loggingMonitor.isOnline) loggingMonitor.stopMonitoring() } diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StorageDownloadFileOperationTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StorageDownloadFileOperationTests.swift index faecad2df9..b87d1cd939 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StorageDownloadFileOperationTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StorageDownloadFileOperationTests.swift @@ -68,7 +68,7 @@ class AWSS3StorageDownloadFileOperationTests: AWSS3StorageOperationTestBase { operation.start() - await waitForExpectations(timeout: 1) + await fulfillment(of: [failedInvoked], timeout: 1) XCTAssertTrue(operation.isFinished) } @@ -177,7 +177,7 @@ class AWSS3StorageDownloadFileOperationTests: AWSS3StorageOperationTestBase { operation.start() - await waitForExpectations(timeout: 1) + await fulfillment(of: [inProcessInvoked, completeInvoked], timeout: 1) XCTAssertTrue(operation.isFinished) mockStorageService.verifyDownload(serviceKey: expectedServiceKey, fileURL: url) } diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StorageGetDataOperationTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StorageGetDataOperationTests.swift index 89c4183eb7..5acea18c20 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StorageGetDataOperationTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StorageGetDataOperationTests.swift @@ -45,26 +45,28 @@ class AWSS3StorageDownloadDataOperationTests: AWSS3StorageOperationTestBase { mockAuthService.getIdentityIdError = AuthError.service("", "", "") let request = StorageDownloadDataRequest(key: testKey, options: StorageDownloadDataRequest.Options()) let failedInvoked = expectation(description: "failed was invoked on operation") - let operation = AWSS3StorageDownloadDataOperation(request, - storageConfiguration: testStorageConfiguration, - storageService: mockStorageService, - authService: mockAuthService, - progressListener: nil) { event in - switch event { - case .failure(let error): - guard case .authError = error else { - XCTFail("Should have failed with authError") - return - } - failedInvoked.fulfill() - default: - XCTFail("Should have received failed event") - } + let operation = AWSS3StorageDownloadDataOperation( + request, + storageConfiguration: testStorageConfiguration, + storageService: mockStorageService, + authService: mockAuthService, + progressListener: nil + ) { event in + switch event { + case .failure(let error): + guard case .authError = error else { + XCTFail("Should have failed with authError") + return + } + failedInvoked.fulfill() + default: + XCTFail("Should have received failed event") + } } operation.start() - await waitForExpectations(timeout: 1) + await fulfillment(of: [failedInvoked], timeout: 1) XCTAssertTrue(operation.isFinished) } @@ -96,7 +98,7 @@ class AWSS3StorageDownloadDataOperationTests: AWSS3StorageOperationTestBase { operation.start() - await waitForExpectations(timeout: 1) + await fulfillment(of: [inProcessInvoked, completeInvoked], timeout: 1) XCTAssertTrue(operation.isFinished) mockStorageService.verifyDownload(serviceKey: expectedServiceKey, fileURL: nil) } @@ -129,7 +131,7 @@ class AWSS3StorageDownloadDataOperationTests: AWSS3StorageOperationTestBase { operation.start() - await waitForExpectations(timeout: 1) + await fulfillment(of: [inProcessInvoked, failInvoked], timeout: 1) XCTAssertTrue(operation.isFinished) mockStorageService.verifyDownload(serviceKey: expectedServiceKey, fileURL: nil) } @@ -164,7 +166,10 @@ class AWSS3StorageDownloadDataOperationTests: AWSS3StorageOperationTestBase { operation.start() - await waitForExpectations(timeout: 1) + await fulfillment( + of: [inProcessInvoked, completeInvoked], + timeout: 1 + ) XCTAssertTrue(operation.isFinished) mockStorageService.verifyDownload(serviceKey: expectedServiceKey, fileURL: nil) } diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StorageRemoveOperationTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StorageRemoveOperationTests.swift index aea952020b..5369bc68d4 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StorageRemoveOperationTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StorageRemoveOperationTests.swift @@ -64,7 +64,7 @@ class AWSS3StorageRemoveOperationTests: AWSS3StorageOperationTestBase { } operation.start() - await waitForExpectations(timeout: 1) + await fulfillment(of: [failedInvoked], timeout: 1) XCTAssertTrue(operation.isFinished) } @@ -89,7 +89,7 @@ class AWSS3StorageRemoveOperationTests: AWSS3StorageOperationTestBase { operation.start() - await waitForExpectations(timeout: 1) + await fulfillment(of: [completeInvoked], timeout: 1) XCTAssertTrue(operation.isFinished) mockStorageService.verifyDelete(serviceKey: expectedServiceKey) } @@ -115,7 +115,7 @@ class AWSS3StorageRemoveOperationTests: AWSS3StorageOperationTestBase { operation.start() - await waitForExpectations(timeout: 1) + await fulfillment(of: [failedInvoked], timeout: 1) XCTAssertTrue(operation.isFinished) mockStorageService.verifyDelete(serviceKey: expectedServiceKey) } @@ -142,7 +142,7 @@ class AWSS3StorageRemoveOperationTests: AWSS3StorageOperationTestBase { operation.start() - waitForExpectations(timeout: 1) + wait(for: [completeInvoked], timeout: 1) XCTAssertTrue(operation.isFinished) mockStorageService.verifyDelete(serviceKey: expectedServiceKey) } diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StorageUploadFileOperationTests2.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StorageUploadFileOperationTests2.swift index e4c89f5d03..b78a527e21 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StorageUploadFileOperationTests2.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StorageUploadFileOperationTests2.swift @@ -68,7 +68,7 @@ final class AWSS3StorageUploadFileOperationTests2: AWSS3StorageOperationTestBase resultListener: resultListener) operation.start() - await fulfillment(of: [progressExpectation, resultExpectation], timeout: 1) + wait(for: [progressExpectation, resultExpectation], timeout: 1) XCTAssertTrue(operation.isFinished) } } diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/FileSystemTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/FileSystemTests.swift index 0cd19df7e3..2ccce7c3ab 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/FileSystemTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/FileSystemTests.swift @@ -222,7 +222,7 @@ class FileSystemTests: XCTestCase { step?(0) - await fulfillment(of: [exp], timeout: 5.0) + wait(for: [exp], timeout: 5.0) XCTAssertGreaterThan(parts.count, 0) XCTAssertGreaterThan(rebuild.count, 0) diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/StorageMultipartUploadSessionTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/StorageMultipartUploadSessionTests.swift index 744abb3fb8..fa808b4ccc 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/StorageMultipartUploadSessionTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/StorageMultipartUploadSessionTests.swift @@ -68,7 +68,7 @@ class StorageMultipartUploadSessionTests: XCTestCase { session.startUpload() - await fulfillment(of: [initiatedExp, completedExp], timeout: 300.0) + wait(for: [initiatedExp, completedExp], timeout: 300.0) XCTAssertEqual(session.inProgressCount, 0) XCTAssertTrue(session.isCompleted) @@ -115,7 +115,7 @@ class StorageMultipartUploadSessionTests: XCTestCase { session.startUpload() - await fulfillment(of: [initiatedExp, completedExp], timeout: 300.0) + wait(for: [initiatedExp, completedExp], timeout: 300.0) XCTAssertEqual(session.inProgressCount, 0) XCTAssertTrue(session.isAborted) @@ -169,7 +169,7 @@ class StorageMultipartUploadSessionTests: XCTestCase { session.startUpload() - await fulfillment(of: [initiatedExp, completedExp], timeout: 300.0) + wait(for: [initiatedExp, completedExp], timeout: 300.0) XCTAssertEqual(session.inProgressCount, 0) XCTAssertTrue(session.isCompleted) @@ -219,7 +219,7 @@ class StorageMultipartUploadSessionTests: XCTestCase { session.startUpload() - await fulfillment(of: [initiatedExp, completedExp], timeout: 300.0) + wait(for: [initiatedExp, completedExp], timeout: 300.0) XCTAssertEqual(session.inProgressCount, 0) XCTAssertTrue(session.isCompleted) @@ -269,7 +269,7 @@ class StorageMultipartUploadSessionTests: XCTestCase { session.startUpload() - await fulfillment(of: [initiatedExp, completedExp], timeout: 300.0) + wait(for: [initiatedExp, completedExp], timeout: 300.0) XCTAssertEqual(session.inProgressCount, 0) XCTAssertTrue(session.isAborted) diff --git a/AmplifyTests/CategoryTests/API/APICategoryClientGraphQLTests.swift b/AmplifyTests/CategoryTests/API/APICategoryClientGraphQLTests.swift index 0fd9e9c69f..09a85d35ab 100644 --- a/AmplifyTests/CategoryTests/API/APICategoryClientGraphQLTests.swift +++ b/AmplifyTests/CategoryTests/API/APICategoryClientGraphQLTests.swift @@ -38,11 +38,11 @@ class APICategoryClientGraphQLTests: XCTestCase { let queryCompleted = expectation(description: "query completed") Task { _ = try await Amplify.API.query(request: request) - await queryCompleted.fulfill() + queryCompleted.fulfill() } + await fulfillment(of: [queryCompleted], timeout: 0.5) - - await waitForExpectations(timeout: 0.5) + await fulfillment(of: [methodWasInvokedOnPlugin], timeout: 0.5) } func testMutate() async throws { @@ -59,11 +59,10 @@ class APICategoryClientGraphQLTests: XCTestCase { let mutateCompleted = expectation(description: "mutate completed") Task { _ = try await Amplify.API.mutate(request: request) - await mutateCompleted.fulfill() + mutateCompleted.fulfill() } await fulfillment(of: [mutateCompleted], timeout: 0.5) - - await waitForExpectations(timeout: 0.5) + await fulfillment(of: [methodWasInvokedOnPlugin], timeout: 0.5) } // MARK: - Utilities diff --git a/AmplifyTests/CategoryTests/API/APICategoryConfigurationTests.swift b/AmplifyTests/CategoryTests/API/APICategoryConfigurationTests.swift index 6f8716ef31..c15801e609 100644 --- a/AmplifyTests/CategoryTests/API/APICategoryConfigurationTests.swift +++ b/AmplifyTests/CategoryTests/API/APICategoryConfigurationTests.swift @@ -118,11 +118,11 @@ class APICategoryConfigurationTests: XCTestCase { let getCompleted = expectation(description: "get completed") Task { _ = try await Amplify.API.get(request: RESTRequest()) - await getCompleted.fulfill() + getCompleted.fulfill() } - await fulfillment(of: [getCompleted], timeout: 0.5) - await waitForExpectations(timeout: 1.0) + await fulfillment(of: [getCompleted], timeout: 0.5) + await fulfillment(of: [methodInvokedOnDefaultPlugin], timeout: 1) } // TODO: this test is disabled for now since `catchBadInstruction` only takes in closure @@ -188,11 +188,16 @@ class APICategoryConfigurationTests: XCTestCase { Task { let plugin = try Amplify.API.getPlugin(for: "MockSecondAPICategoryPlugin") _ = try await plugin.get(request: RESTRequest()) - await getCompleted.fulfill() + getCompleted.fulfill() } - await fulfillment(of: [getCompleted], timeout: 0.5) - - await waitForExpectations(timeout: 1.0) + await fulfillment( + of: [ + getCompleted, + methodShouldBeInvokedOnSecondPlugin, + methodShouldNotBeInvokedOnDefaultPlugin + ], + timeout: 1.0 + ) } func testCanConfigurePluginDirectly() throws { diff --git a/AmplifyTests/CategoryTests/API/RetryableGraphQLOperationTests.swift b/AmplifyTests/CategoryTests/API/RetryableGraphQLOperationTests.swift index 2a525d5c6c..c76e6ec0cd 100644 --- a/AmplifyTests/CategoryTests/API/RetryableGraphQLOperationTests.swift +++ b/AmplifyTests/CategoryTests/API/RetryableGraphQLOperationTests.swift @@ -52,7 +52,7 @@ class RetryableGraphQLOperationTests: XCTestCase { } operation.main() - await fulfillment(of: [requestFactoryExpectation, resultExpectation], timeout: 10) + wait(for: [requestFactoryExpectation, resultExpectation], timeout: 10) } /// Given: a RetryableGraphQLOperation with a maxRetries of 1 @@ -86,7 +86,7 @@ class RetryableGraphQLOperationTests: XCTestCase { } operation.main() - await fulfillment(of: [requestFactoryExpectation, resultExpectation], timeout: 10) + wait(for: [requestFactoryExpectation, resultExpectation], timeout: 10) } /// Given: a RetryableGraphQLOperation with a maxRetries of 2 @@ -121,7 +121,7 @@ class RetryableGraphQLOperationTests: XCTestCase { } operation.main() - await fulfillment(of: [requestFactoryExpectation, resultExpectation], timeout: 10) + wait(for: [requestFactoryExpectation, resultExpectation], timeout: 10) } } diff --git a/AmplifyTests/CategoryTests/Auth/AuthCategoryConfigurationTests.swift b/AmplifyTests/CategoryTests/Auth/AuthCategoryConfigurationTests.swift index 21e47000ae..f9c3b38696 100644 --- a/AmplifyTests/CategoryTests/Auth/AuthCategoryConfigurationTests.swift +++ b/AmplifyTests/CategoryTests/Auth/AuthCategoryConfigurationTests.swift @@ -200,7 +200,7 @@ class AuthCategoryConfigurationTests: XCTestCase { try Amplify.configure(amplifyConfig) _ = try await Amplify.Auth.getPlugin(for: "MockSecondAuthCategoryPlugin") .update(oldPassword: "current", to: "new", options: nil) - await waitForExpectations(timeout: 1.0) + await fulfillment(of: [methodShouldBeInvokedOnSecondPlugin], timeout: 1.0) } /// Test if we get error when trying default plugin when multiple plugin added. diff --git a/AmplifyTests/CategoryTests/DataStore/DataStoreCategoryClientAPITests.swift b/AmplifyTests/CategoryTests/DataStore/DataStoreCategoryClientAPITests.swift index 628dc21348..5a7ad073b2 100644 --- a/AmplifyTests/CategoryTests/DataStore/DataStoreCategoryClientAPITests.swift +++ b/AmplifyTests/CategoryTests/DataStore/DataStoreCategoryClientAPITests.swift @@ -39,12 +39,12 @@ class DataStoreCategoryClientAPITests: XCTestCase { let saveSuccess = expectation(description: "saved successful") Task { _ = try await Amplify.DataStore.save(TestModel.make()) - await saveSuccess.fulfill() + saveSuccess.fulfill() } - await fulfillment(of: [saveSuccess], timeout: 0.5) - - - await waitForExpectations(timeout: 0.5) + await fulfillment( + of: [saveSuccess, methodWasInvokedOnPlugin], + timeout: 1 + ) } } diff --git a/AmplifyTests/CategoryTests/DataStore/DataStoreCategoryConfigurationTests.swift b/AmplifyTests/CategoryTests/DataStore/DataStoreCategoryConfigurationTests.swift index 64e820491e..871f372c46 100644 --- a/AmplifyTests/CategoryTests/DataStore/DataStoreCategoryConfigurationTests.swift +++ b/AmplifyTests/CategoryTests/DataStore/DataStoreCategoryConfigurationTests.swift @@ -30,13 +30,12 @@ class DataStoreCategoryConfigurationTests: XCTestCase { } try Amplify.add(plugin: plugin) - let amplifyConfig = AmplifyConfiguration() try Amplify.configure(amplifyConfig) XCTAssertNotNil(Amplify.DataStore) XCTAssertNotNil(Amplify.DataStore.plugin) - await fulfillment(of: [methodInvokedOnDefaultPlugin], timeout: 1.0) + wait(for: [methodInvokedOnDefaultPlugin], timeout: 1.0) } func testCanConfigureDataStorePlugin() throws { @@ -137,12 +136,13 @@ class DataStoreCategoryConfigurationTests: XCTestCase { let saveSuccess = expectation(description: "save successful") Task { _ = try await Amplify.DataStore.save(TestModel.make()) - await saveSuccess.fulfill() + saveSuccess.fulfill() } - await fulfillment(of: [saveSuccess], timeout: 1.0) - - await waitForExpectations(timeout: 1.0) + await fulfillment( + of: [saveSuccess, methodInvokedOnDefaultPlugin], + timeout: 1.0 + ) } // TODO: this test is disabled for now since `catchBadInstruction` only takes in closure @@ -208,11 +208,17 @@ class DataStoreCategoryConfigurationTests: XCTestCase { Task { _ = try await Amplify.DataStore.getPlugin(for: "MockSecondDataStoreCategoryPlugin") .save(TestModel.make(), where: nil) - await saveSuccess.fulfill() + saveSuccess.fulfill() } - await fulfillment(of: [saveSuccess], timeout: 1.0) - - await waitForExpectations(timeout: 1.0) + + await fulfillment( + of: [ + saveSuccess, + methodShouldBeInvokedOnSecondPlugin, + methodShouldNotBeInvokedOnDefaultPlugin + ], + timeout: 1.0 + ) } func testCanConfigurePluginDirectly() throws { diff --git a/AmplifyTests/CategoryTests/DataStore/Model/Collection/ArrayLiteralListProviderTests.swift b/AmplifyTests/CategoryTests/DataStore/Model/Collection/ArrayLiteralListProviderTests.swift index bbe49aadf3..70835d17d1 100644 --- a/AmplifyTests/CategoryTests/DataStore/Model/Collection/ArrayLiteralListProviderTests.swift +++ b/AmplifyTests/CategoryTests/DataStore/Model/Collection/ArrayLiteralListProviderTests.swift @@ -40,7 +40,7 @@ class ArrayLiteralListProviderTests: XCTestCase { } } - await fulfillment(of: [loadComplete], timeout: 1) + wait(for: [loadComplete], timeout: 1) } func testLoadAsync() async throws { @@ -71,7 +71,7 @@ class ArrayLiteralListProviderTests: XCTestCase { } } - await fulfillment(of: [getNextPageComplete], timeout: 1) + wait(for: [getNextPageComplete], timeout: 1) } func testGetNextPageAsync() async { diff --git a/AmplifyTests/CategoryTests/DataStore/Model/ListTests.swift b/AmplifyTests/CategoryTests/DataStore/Model/ListTests.swift index 303c5766d7..26cefa0422 100644 --- a/AmplifyTests/CategoryTests/DataStore/Model/ListTests.swift +++ b/AmplifyTests/CategoryTests/DataStore/Model/ListTests.swift @@ -134,7 +134,7 @@ class ListTests: XCTestCase { let fetchSuccess = expectation(description: "fetch successful") Task { try await list.fetch() - await fetchSuccess.fulfill() + fetchSuccess.fulfill() } await fulfillment(of: [fetchSuccess], timeout: 1.0) @@ -168,7 +168,7 @@ class ListTests: XCTestCase { let fetchSuccess = expectation(description: "fetch successful") Task { try await list.fetch() - await fetchSuccess.fulfill() + fetchSuccess.fulfill() } await fulfillment(of: [fetchSuccess], timeout: 1.0) XCTAssertEqual(list.count, 2) @@ -181,7 +181,7 @@ class ListTests: XCTestCase { list.makeIterator().forEach { _ in iterateSuccess.fulfill() } - await waitForExpectations(timeout: 1) + await fulfillment(of: [iterateSuccess], timeout: 1) XCTAssertFalse(list.listProvider.hasNextPage()) do { _ = try await list.listProvider.getNextPage() @@ -200,7 +200,7 @@ class ListTests: XCTestCase { let fetchSuccess = expectation(description: "fetch successful") Task { try await list.fetch() - await fetchSuccess.fulfill() + fetchSuccess.fulfill() } await fulfillment(of: [fetchSuccess], timeout: 1.0) XCTAssertEqual(list.count, 0) @@ -225,7 +225,7 @@ class ListTests: XCTestCase { } catch { XCTAssertNotNil(error) } - await fetchCompleted.fulfill() + fetchCompleted.fulfill() } await fulfillment(of: [fetchCompleted], timeout: 1.0) } diff --git a/AmplifyTests/CategoryTests/Hub/AmplifyOperationHubTests.swift b/AmplifyTests/CategoryTests/Hub/AmplifyOperationHubTests.swift index ae1c51b53a..baa6629239 100644 --- a/AmplifyTests/CategoryTests/Hub/AmplifyOperationHubTests.swift +++ b/AmplifyTests/CategoryTests/Hub/AmplifyOperationHubTests.swift @@ -48,7 +48,7 @@ class AmplifyOperationHubTests: XCTestCase { operation.doMockDispatch() - await waitForExpectations(timeout: 1.0) + await fulfillment(of: [listenerWasInvoked], timeout: 1.0) } /// Given: A configured system diff --git a/AmplifyTests/CategoryTests/Hub/DefaultPluginTests/DefaultHubPluginConcurrencyTests.swift b/AmplifyTests/CategoryTests/Hub/DefaultPluginTests/DefaultHubPluginConcurrencyTests.swift index eb07b39b2a..0f8284a3d5 100644 --- a/AmplifyTests/CategoryTests/Hub/DefaultPluginTests/DefaultHubPluginConcurrencyTests.swift +++ b/AmplifyTests/CategoryTests/Hub/DefaultPluginTests/DefaultHubPluginConcurrencyTests.swift @@ -79,7 +79,7 @@ class DefaultHubPluginConcurrencyTests: XCTestCase { } } - await waitForExpectations(timeout: 5.0) + await fulfillment(of: messagesReceived, timeout: 5.0) } } diff --git a/AmplifyTests/CategoryTests/Hub/DefaultPluginTests/DefaultHubPluginCustomChannelTests.swift b/AmplifyTests/CategoryTests/Hub/DefaultPluginTests/DefaultHubPluginCustomChannelTests.swift index 76248f4893..0e7e0892f5 100644 --- a/AmplifyTests/CategoryTests/Hub/DefaultPluginTests/DefaultHubPluginCustomChannelTests.swift +++ b/AmplifyTests/CategoryTests/Hub/DefaultPluginTests/DefaultHubPluginCustomChannelTests.swift @@ -51,7 +51,7 @@ class DefaultHubPluginCustomChannelTests: XCTestCase { plugin.dispatch(to: .custom("CustomChannel1"), payload: HubPayload(eventName: "TEST_EVENT")) - await waitForExpectations(timeout: 0.5) + await fulfillment(of: [eventReceived], timeout: 0.5) } /// Given: A listener to a custom channel @@ -72,7 +72,7 @@ class DefaultHubPluginCustomChannelTests: XCTestCase { plugin.dispatch(to: .custom("CustomChannel2"), payload: HubPayload(eventName: "TEST_EVENT")) - await waitForExpectations(timeout: 0.5) + await fulfillment(of: [eventReceived], timeout: 0.5) } /// Given: Multiple listeners to a custom channel @@ -102,7 +102,7 @@ class DefaultHubPluginCustomChannelTests: XCTestCase { plugin.dispatch(to: .custom("CustomChannel1"), payload: HubPayload(eventName: "TEST_EVENT")) - await waitForExpectations(timeout: 0.5) + await fulfillment(of: [listener1Invoked, listener2Invoked], timeout: 0.5) } } diff --git a/AmplifyTests/CategoryTests/Hub/DefaultPluginTests/DefaultHubPluginTests.swift b/AmplifyTests/CategoryTests/Hub/DefaultPluginTests/DefaultHubPluginTests.swift index 04a909b2cc..e6a3bf08ab 100644 --- a/AmplifyTests/CategoryTests/Hub/DefaultPluginTests/DefaultHubPluginTests.swift +++ b/AmplifyTests/CategoryTests/Hub/DefaultPluginTests/DefaultHubPluginTests.swift @@ -69,7 +69,7 @@ class DefaultHubPluginTests: XCTestCase { } plugin.dispatch(to: .storage, payload: HubPayload(eventName: "TEST_EVENT")) - await waitForExpectations(timeout: 0.5) + await fulfillment(of: [expectedMessageReceived], timeout: 0.5) } /// Given: The default Hub plugin with a registered listener @@ -92,7 +92,7 @@ class DefaultHubPluginTests: XCTestCase { } plugin.dispatch(to: .storage, payload: HubPayload(eventName: "TEST_EVENT")) - await waitForExpectations(timeout: 0.5) + await fulfillment(of: [messageReceived], timeout: 0.5) } /// Given: A subscription token from a previous call to the default Hub plugin's `listen` method @@ -129,7 +129,7 @@ class DefaultHubPluginTests: XCTestCase { } plugin.dispatch(to: .storage, payload: HubPayload(eventName: "TEST_EVENT")) - await waitForExpectations(timeout: 0.5) + await fulfillment(of: [try XCTUnwrap(currentExpectation)], timeout: 0.5) plugin.removeListener(unsubscribeToken) try? await Task.sleep(seconds: 0.01) @@ -147,7 +147,7 @@ class DefaultHubPluginTests: XCTestCase { XCTAssertFalse(isStillRegistered.get(), "Should not be registered after removeListener") plugin.dispatch(to: .storage, payload: HubPayload(eventName: "TEST_EVENT")) - await waitForExpectations(timeout: 0.5) + await fulfillment(of: [try XCTUnwrap(currentExpectation)], timeout: 0.5) } /// Given: The default Hub plugin diff --git a/AmplifyTests/CategoryTests/Notifications/Push/PushNotificationsCategoryClientAPITests.swift b/AmplifyTests/CategoryTests/Notifications/Push/PushNotificationsCategoryClientAPITests.swift index 137579cb39..bd5d44a782 100644 --- a/AmplifyTests/CategoryTests/Notifications/Push/PushNotificationsCategoryClientAPITests.swift +++ b/AmplifyTests/CategoryTests/Notifications/Push/PushNotificationsCategoryClientAPITests.swift @@ -44,7 +44,7 @@ class PushNotificationsCategoryClientAPITests: XCTestCase { } try await category.identifyUser(userId: "test") - await waitForExpectations(timeout: 1.0) + await fulfillment(of: [methodInvoked], timeout: 1.0) } func testRegisterDeviceToken_shouldSucceed() async throws { @@ -58,7 +58,7 @@ class PushNotificationsCategoryClientAPITests: XCTestCase { } try await category.registerDevice(apnsToken: data) - await waitForExpectations(timeout: 1.0) + await fulfillment(of: [methodInvoked], timeout: 1.0) } func testRecordNotificationReceived_shouldSucceed() async throws { @@ -72,7 +72,7 @@ class PushNotificationsCategoryClientAPITests: XCTestCase { } try await category.recordNotificationReceived(userInfo) - await waitForExpectations(timeout: 1.0) + await fulfillment(of: [methodInvoked], timeout: 1.0) } #if !os(tvOS) @@ -87,7 +87,7 @@ class PushNotificationsCategoryClientAPITests: XCTestCase { } try await category.recordNotificationOpened(response) - await waitForExpectations(timeout: 1.0) + await fulfillment(of: [methodInvoked], timeout: 1.0) } #endif diff --git a/AmplifyTests/CoreTests/AmplifyConfigurationInitializationTests.swift b/AmplifyTests/CoreTests/AmplifyConfigurationInitializationTests.swift index 3ab56abf21..ca7e49c381 100644 --- a/AmplifyTests/CoreTests/AmplifyConfigurationInitializationTests.swift +++ b/AmplifyTests/CoreTests/AmplifyConfigurationInitializationTests.swift @@ -167,7 +167,7 @@ class AmplifyConfigurationInitializationTests: XCTestCase { let config = AmplifyConfiguration(analytics: analyticsConfiguration) try Amplify.configure(config) - await waitForExpectations(timeout: 1.0) + await fulfillment(of: [notificationReceived], timeout: 1.0) } // MARK: - Utilities diff --git a/AmplifyTests/CoreTests/AmplifyTaskTests.swift b/AmplifyTests/CoreTests/AmplifyTaskTests.swift index 8e85cad7c6..318b0077ee 100644 --- a/AmplifyTests/CoreTests/AmplifyTaskTests.swift +++ b/AmplifyTests/CoreTests/AmplifyTaskTests.swift @@ -59,7 +59,7 @@ class AmplifyTaskTests: XCTestCase { sink.cancel() } - await fulfillment(of: [exp1, exp2], timeout: 5.0) + wait(for: [exp1, exp2], timeout: 5.0) XCTAssertEqual(input.sum(), output) XCTAssertNil(thrown) diff --git a/AmplifyTests/CoreTests/ChildTaskTests.swift b/AmplifyTests/CoreTests/ChildTaskTests.swift index 30d2800bd1..2a093f87e4 100644 --- a/AmplifyTests/CoreTests/ChildTaskTests.swift +++ b/AmplifyTests/CoreTests/ChildTaskTests.swift @@ -85,7 +85,7 @@ class ChildTaskTests: XCTestCase { XCTAssertTrue(thrown is CancellationError) } - await waitForExpectations(timeout: 0.01) + await fulfillment(of: [cancelExp], timeout: 0.01) task.cancel() // Ensure the channel's AsyncSequence does not block after completion @@ -115,7 +115,7 @@ class ChildTaskTests: XCTestCase { XCTAssertTrue(thrown is CancellationError) } - await waitForExpectations(timeout: 0.01) + await fulfillment(of: [cancelExp], timeout: 0.01) // Ensure the channel's AsyncSequence does not block after completion for await _ in progressSequence { diff --git a/AmplifyTests/CoreTests/ConfigurationTests.swift b/AmplifyTests/CoreTests/ConfigurationTests.swift index 240e24accf..08f5c25b44 100644 --- a/AmplifyTests/CoreTests/ConfigurationTests.swift +++ b/AmplifyTests/CoreTests/ConfigurationTests.swift @@ -62,7 +62,7 @@ class ConfigurationTests: XCTestCase { let amplifyConfig = AmplifyConfiguration(logging: loggingConfig) try Amplify.configure(amplifyConfig) - await fulfillment(of: [configureWasInvoked], timeout: 1.0) + wait(for: [configureWasInvoked], timeout: 1.0) } func testMultipleConfigureCallsThrowError() throws {